<?php

declare(strict_types=1);

namespace App\Modules\Reporting\Presentation\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Core\Response;
use App\Modules\Reporting\Application\Services\ExpenseReportService;
use App\Modules\Reporting\Application\Services\ReportFileExportService;

final class ExpenseReportController
{
    public function __construct(private ?ExpenseReportService $service = null)
    {
        $this->service ??= new ExpenseReportService(db());
    }

    public function index(): void
    {
        Auth::requireLogin();
        require_permission('expenses.report.view');
        $this->service->ensureSchema();

        $data = $this->service->report(
            trim((string) Request::get('from', '')),
            trim((string) Request::get('to', '')),
            (int) Request::get('category_id', 0),
            (int) Request::get('item_id', 0),
            trim((string) Request::get('account_source_type', '')),
            (int) Request::get('cashbox_id', 0),
            (int) Request::get('bank_account_id', 0),
            trim((string) Request::get('q', '')),
        );
        $page = max(1, (int) Request::get('page', 1));
        $pagination = paginate_rows($data['rows'] ?? [], $page, 25);
        $data['rows'] = $pagination['items'];

        Response::view('pages/expenses/reports', $data + [
            'page' => $pagination['page'],
            'per_page' => $pagination['per_page'],
            'total_pages' => $pagination['total_pages'],
            'total_rows' => $pagination['total_rows'],
            'from_row' => $pagination['from'],
            'to_row' => $pagination['to'],
            'page_title' => 'تقارير المصروفات',
            'breadcrumbs' => [
                ['label' => 'لوحة التحكم', 'url' => '/admin/dashboard'],
                ['label' => 'المصاريف'],
                ['label' => 'تقارير المصروفات'],
            ],
        ]);
    }

    public function print(): void
    {
        Auth::requireLogin();
        require_permission('expenses.report.view');
        $this->service->ensureSchema();

        $format = strtolower(trim((string) Request::get('format', '')));
        if ($format === '') {
            $this->chooseFormat('طباعة تقارير المصروفات');
            return;
        }

        $data = $this->service->report(
            trim((string) Request::get('from', '')),
            trim((string) Request::get('to', '')),
            (int) Request::get('category_id', 0),
            (int) Request::get('item_id', 0),
            trim((string) Request::get('account_source_type', '')),
            (int) Request::get('cashbox_id', 0),
            (int) Request::get('bank_account_id', 0),
            trim((string) Request::get('q', '')),
        );

        print_view($format, 'expense_report', [
            'title' => 'تقارير المصروفات',
            'rows' => $data['rows'],
            'totals' => $data['totals'],
            'byCategory' => $data['byCategory'],
            'from' => $data['from'],
            'to' => $data['to'],
            'q' => $data['q'],
        ]);
    }


    public function exportExcel(): void
    {
        Auth::requireLogin();
        require_permission('expenses.report.view');
        $this->service->ensureSchema();
        $data = $this->service->report(
            trim((string) Request::get('from', '')),
            trim((string) Request::get('to', '')),
            (int) Request::get('category_id', 0),
            (int) Request::get('item_id', 0),
            trim((string) Request::get('account_source_type', '')),
            (int) Request::get('cashbox_id', 0),
            (int) Request::get('bank_account_id', 0),
            trim((string) Request::get('q', ''))
        );
        $rows = [];
        $i = 0;
        foreach (($data['rows'] ?? []) as $r) {
            $i++;
            $rows[] = [$i, substr((string)($r['expense_date'] ?? $r['pay_date'] ?? ''),0,10), (string)($r['category_name'] ?? ''), (string)($r['item_name'] ?? ''), (string)($r['account_source_type'] ?? ''), (string)($r['notes'] ?? $r['purpose'] ?? ''), format_money($r['amount'] ?? 0)];
        }
        $totals = is_array($data['totals'] ?? null) ? $data['totals'] : [];
        (new ReportFileExportService())->sendExcel('expense-report-' . date('Ymd-His'), 'تقرير المصروفات', [
            'الفترة' => (string)($data['from'] ?? '') . ' - ' . (string)($data['to'] ?? ''),
            'بحث' => (string)($data['q'] ?? ''),
            'الإجمالي' => format_money($totals['amount'] ?? $totals['total'] ?? 0),
        ], ['#','التاريخ','التصنيف','البند','المصدر','البيان','المبلغ'], $rows);
    }

    public function exportPdf(): void
    {
        Auth::requireLogin();
        require_permission('expenses.report.view');
        $_GET['format'] = 'a4';
        ob_start();
        $this->print();
        $html = (string)ob_get_clean();
        (new ReportFileExportService())->sendPdfFromHtml($html, 'expense-report-' . date('Ymd-His'));
    }

    private function chooseFormat(string $title): void
    {
        $basePath = Request::path();
        $qs = $_GET;
        $qs['format'] = 'a4';
        $a4Url = $basePath . '?' . http_build_query($qs);
        $qs['format'] = 'receipt';
        $receiptUrl = $basePath . '?' . http_build_query($qs);
        print_format_chooser($a4Url, $receiptUrl, $title);
    }
}
