<?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\ProfitReportService;
use App\Modules\Reporting\Application\Services\ReportFileExportService;

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

    public function show(): 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', '')),
            trim((string) Request::get('q', '')),
        );
        $page = max(1, (int) Request::get('page', 1));
        $pagination = paginate_rows($data['salesRows'] ?? [], $page, 25);
        $data['salesRows'] = $pagination['items'];

        Response::view('pages/profit_report', $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 === '') {
            $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, 'طباعة تقرير الأرباح المبدئي');
            return;
        }

        $data = $this->service->report(
            trim((string) Request::get('from', '')),
            trim((string) Request::get('to', '')),
            trim((string) Request::get('q', '')),
        );

        print_view($format, 'profit_report', [
            'title' => 'تقرير الأرباح المبدئي',
            'meta' => ['date' => date('Y-m-d')],
            'company' => company_profile(db()),
            'footer' => [],
            'from' => $data['from'],
            'to' => $data['to'],
            'q' => $data['q'],
            'summary' => $data['summary'],
            'salesRows' => $data['salesRows'],
            'returnRows' => $data['returnRows'],
            'expenseRows' => $data['expenseRows'],
            'expenseByCategory' => $data['expenseByCategory'],
        ]);
    }

    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', '')), trim((string) Request::get('q', '')));
        $rows = [];
        $i = 0;
        foreach (($data['salesRows'] ?? []) as $r) {
            $i++;
            $rows[] = [$i, 'بيع', substr((string)($r['invoice_date'] ?? $r['inv_date'] ?? ''),0,10), (string)($r['invoice_no'] ?? $r['inv_no'] ?? ''), (string)($r['customer_name'] ?? $r['party_name'] ?? ''), format_money($r['total'] ?? $r['grand_total'] ?? 0), format_money($r['cost_total'] ?? 0), format_money($r['profit'] ?? 0)];
        }
        foreach (($data['returnRows'] ?? []) as $r) {
            $i++;
            $rows[] = [$i, 'مرتجع', substr((string)($r['ret_date'] ?? ''),0,10), (string)($r['ret_no'] ?? ''), (string)($r['customer_name'] ?? $r['party_name'] ?? ''), format_money($r['total'] ?? 0), '', format_money(-1 * abs((float)($r['total'] ?? 0)))];
        }
        $summary = is_array($data['summary'] ?? null) ? $data['summary'] : [];
        (new ReportFileExportService())->sendExcel('profit-report-' . date('Ymd-His'), 'تقرير الأرباح', [
            'الفترة' => (string)($data['from'] ?? '') . ' - ' . (string)($data['to'] ?? ''),
            'بحث' => (string)($data['q'] ?? ''),
            'إجمالي المبيعات' => format_money($summary['sales_total'] ?? $summary['sales'] ?? 0),
            'إجمالي المصروفات' => format_money($summary['expenses_total'] ?? $summary['expenses'] ?? 0),
            'صافي الربح' => format_money($summary['net_profit'] ?? $summary['profit'] ?? 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, 'profit-report-' . date('Ymd-His'));
    }

}
