<?php

namespace App\Controllers\Report;

use App\Controllers\BaseController;
use App\Libraries\ExcelExporter;
use App\Models\OrderModel;
use App\Models\ActivityLogModel;

class Excel extends BaseController
{
    public function downloadSales()
    {
        // 1. Validasi Input
        if (!$this->validate(['start' => 'required', 'end' => 'required'])) {
            return redirect()->back()->with('error', 'Pilih rentang tanggal yang valid.');
        }

        $start = $this->request->getGet('start');
        $end   = $this->request->getGet('end');
        
        $orderModel = new OrderModel();
        // Mengambil data lengkap dengan JOIN untuk keperluan Excel
        $data = $orderModel->getReportData($start, $end);
        
        // 2. Audit Trail
        (new ActivityLogModel())->logActivity(
            session()->get('id_user') ?? 1, 
            "Mengunduh Laporan Penjualan (Excel) periode: $start s/d $end"
        );
        
        $exporter = new ExcelExporter();
        return $exporter->exportLaporan($data, 'Laporan_Penjualan', 'Sales_Report_' . date('Ymd'));
    }
}