<?php
namespace App\Controllers;

use App\Models\ReportModel;
use App\Models\ProductModel;

class ReportController extends BaseController
{
    public function index()
    {
        $productModel = new ProductModel();
        $data['categories'] = $productModel->getCategories();
        $data['products'] = $productModel->getProductsWithCategory();
        $data['title'] = 'Reportes';
        return view('reports/index', $data);
    }

    public function generate()
    {
        $data = $this->buildReportData();
        return view('reports/index', $data);
    }

    public function download()
    {
        $data = $this->buildReportData();
        $html = view('reports/download', $data);

        return $this->response
            ->setContentType('text/html')
            ->setHeader('Content-Disposition', 'attachment; filename="reporte_' . date('Y-m-d') . '.html"')
            ->setBody($html);
    }

    private function buildReportData()
    {
        $reportModel = new ReportModel();

        $startDate = $this->request->getPost('start_date');
        $endDate   = $this->request->getPost('end_date');
        $categoryId = $this->request->getPost('id_categoria');
        $productId  = $this->request->getPost('id_producto');

        $data['sales'] = $reportModel->getFilteredSales($startDate, $endDate, $categoryId, $productId);
        $data['profits'] = $reportModel->getFilteredProfits($startDate, $endDate, $categoryId, $productId);
        $data['totalSales'] = array_sum(array_column($data['sales'], 'subtotal'));
        $data['totalProfits'] = array_sum(array_column($data['profits'], 'ganancia'));
        $data['startDate'] = $startDate;
        $data['endDate'] = $endDate;
        $data['categoryId'] = $categoryId;
        $data['productId'] = $productId;

        $productModel = new ProductModel();
        $data['categories'] = $productModel->getCategories();
        $data['products'] = $productModel->getProductsWithCategory();
        $data['title'] = 'Reportes';

        return $data;
    }
}

