<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\SportsActivity\Services\SaPlayerReportService;
use App\Modules\SportsActivity\Services\SaFinanceReportService;
use App\Modules\Reports\Services\ReportExporter;
use App\Shared\Services\PdfExportService;

class SaReportController extends Controller
{
    public function playerReport(Request $request): Response
    {
        $db = App::getInstance()->db();

        $filters = [
            'discipline_id'  => $request->get('discipline_id', ''),
            'program_id'     => $request->get('program_id', ''),
            'group_id'       => $request->get('group_id', ''),
            'player_id'      => $request->get('player_id', ''),
            'player_type'    => $request->get('player_type', ''),
            'medical_status' => $request->get('medical_status', ''),
            'payment_status' => $request->get('payment_status', ''),
            'branch_id'      => $request->get('branch_id', ''),
        ];

        $hasFilters = array_filter($filters, fn($v) => $v !== '' && $v !== null);
        $report = !empty($hasFilters) ? SaPlayerReportService::generate($filters) : null;

        $disciplines = $db->select("SELECT id, name_ar FROM sa_disciplines WHERE is_active = 1 AND is_archived = 0 ORDER BY name_ar");
        $programs = $db->select("SELECT id, name_ar, discipline_id FROM sa_programs WHERE is_active = 1 AND is_archived = 0 ORDER BY name_ar");
        $groups = $db->select("SELECT id, name_ar, program_id FROM sa_groups WHERE is_archived = 0 AND status = 'active' ORDER BY name_ar");
        $branches = $db->select("SELECT id, name_ar FROM branches WHERE is_active = 1");

        return $this->view('SportsActivity.Views.reports.players', [
            'filters'     => $filters,
            'report'      => $report,
            'disciplines' => $disciplines,
            'programs'    => $programs,
            'groups'      => $groups,
            'branches'    => $branches,
        ]);
    }

    public function financeReport(Request $request): Response
    {
        $db = App::getInstance()->db();

        $filters = [
            'discipline_id' => $request->get('discipline_id', ''),
            'period_preset' => $request->get('period_preset', 'monthly'),
            'date_from'     => $request->get('date_from', ''),
            'date_to'       => $request->get('date_to', ''),
            'branch_id'     => $request->get('branch_id', ''),
        ];

        $report = SaFinanceReportService::generate($filters);

        $disciplines = $db->select("SELECT id, name_ar FROM sa_disciplines WHERE is_active = 1 AND is_archived = 0 ORDER BY name_ar");
        $branches = $db->select("SELECT id, name_ar FROM branches WHERE is_active = 1");

        return $this->view('SportsActivity.Views.reports.finance', [
            'filters'     => $filters,
            'report'      => $report,
            'disciplines' => $disciplines,
            'branches'    => $branches,
        ]);
    }

    public function exportPlayerCsv(Request $request): Response
    {
        $filters = [
            'discipline_id'  => $request->get('discipline_id', ''),
            'program_id'     => $request->get('program_id', ''),
            'group_id'       => $request->get('group_id', ''),
            'player_id'      => $request->get('player_id', ''),
            'player_type'    => $request->get('player_type', ''),
            'medical_status' => $request->get('medical_status', ''),
            'payment_status' => $request->get('payment_status', ''),
            'branch_id'      => $request->get('branch_id', ''),
        ];

        $report = SaPlayerReportService::generate($filters);
        $csv = ReportExporter::toCsv($report, ['name' => 'player_report']);
        $filename = 'تقرير_اللاعبين_' . date('Y-m-d_His') . '.csv';

        $response = new Response();
        return $response->html("\xEF\xBB\xBF" . $csv, 200)->withHeaders([
            'Content-Type'        => 'text/csv; charset=utf-8',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ]);
    }

    public function exportPlayerPdf(Request $request): Response
    {
        $filters = [
            'discipline_id'  => $request->get('discipline_id', ''),
            'program_id'     => $request->get('program_id', ''),
            'group_id'       => $request->get('group_id', ''),
            'player_id'      => $request->get('player_id', ''),
            'player_type'    => $request->get('player_type', ''),
            'medical_status' => $request->get('medical_status', ''),
            'payment_status' => $request->get('payment_status', ''),
            'branch_id'      => $request->get('branch_id', ''),
        ];

        $report = SaPlayerReportService::generate($filters);
        $html = self::buildPlayerPdfHtml($report);
        $filename = 'تقرير_اللاعبين_' . date('Y-m-d_His') . '.pdf';

        return PdfExportService::renderToPdf($html, $filename);
    }

    public function exportFinanceCsv(Request $request): Response
    {
        $filters = [
            'discipline_id' => $request->get('discipline_id', ''),
            'period_preset' => $request->get('period_preset', 'monthly'),
            'date_from'     => $request->get('date_from', ''),
            'date_to'       => $request->get('date_to', ''),
            'branch_id'     => $request->get('branch_id', ''),
        ];

        $report = SaFinanceReportService::generate($filters);
        $csv = ReportExporter::toCsv($report, ['name' => 'finance_report']);
        $filename = 'التقرير_المالي_' . date('Y-m-d_His') . '.csv';

        $response = new Response();
        return $response->html("\xEF\xBB\xBF" . $csv, 200)->withHeaders([
            'Content-Type'        => 'text/csv; charset=utf-8',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ]);
    }

    public function exportFinancePdf(Request $request): Response
    {
        $filters = [
            'discipline_id' => $request->get('discipline_id', ''),
            'period_preset' => $request->get('period_preset', 'monthly'),
            'date_from'     => $request->get('date_from', ''),
            'date_to'       => $request->get('date_to', ''),
            'branch_id'     => $request->get('branch_id', ''),
        ];

        $report = SaFinanceReportService::generate($filters);
        $html = self::buildFinancePdfHtml($report);
        $filename = 'التقرير_المالي_' . date('Y-m-d_His') . '.pdf';

        return PdfExportService::renderToPdf($html, $filename);
    }

    private static function buildPlayerPdfHtml(array $report): string
    {
        $rows = $report['rows'] ?? [];
        $columns = $report['columns'] ?? [];
        $total = $report['total'] ?? 0;

        $tableRows = '';
        foreach ($rows as $row) {
            $tableRows .= '<tr>';
            foreach (array_keys($columns) as $key) {
                $tableRows .= '<td>' . htmlspecialchars((string) ($row[$key] ?? '—'), ENT_QUOTES, 'UTF-8') . '</td>';
            }
            $tableRows .= '</tr>';
        }

        $headers = '';
        foreach ($columns as $label) {
            $headers .= '<th>' . htmlspecialchars($label, ENT_QUOTES, 'UTF-8') . '</th>';
        }

        return '<!DOCTYPE html><html dir="rtl" lang="ar"><head><meta charset="utf-8">
<style>
body{font-family:Arial,"Tahoma",sans-serif;font-size:11px;direction:rtl;margin:20px;}
h1{font-size:18px;text-align:center;margin-bottom:4px;color:#0D7377;}
.meta{text-align:center;font-size:10px;color:#6B7280;margin-bottom:16px;}
table{width:100%;border-collapse:collapse;margin-top:10px;}
th{background:#0D7377;color:#fff;padding:6px 8px;text-align:right;font-size:10px;white-space:nowrap;}
td{padding:5px 8px;border-bottom:1px solid #E5E7EB;font-size:10px;}
tr:nth-child(even){background:#F9FAFB;}
.total{margin-top:10px;font-weight:bold;font-size:12px;}
</style></head><body>
<h1>تقرير اللاعبين — الأنشطة الرياضية</h1>
<div class="meta">تاريخ التقرير: ' . date('Y-m-d H:i') . ' | إجمالي: ' . $total . ' لاعب</div>
<table><thead><tr>' . $headers . '</tr></thead><tbody>' . $tableRows . '</tbody></table>
<div class="total">إجمالي اللاعبين: ' . $total . '</div>
</body></html>';
    }

    private static function buildFinancePdfHtml(array $report): string
    {
        $summary = $report['summary'] ?? [];
        $revenueBreakdown = $report['revenue_breakdown'] ?? [];
        $costBreakdown = $report['cost_breakdown'] ?? [];
        $trend = $report['monthly_trend'] ?? [];
        $dateFrom = $report['date_from'] ?? '';
        $dateTo = $report['date_to'] ?? '';

        $revRows = '';
        foreach ($revenueBreakdown as $item) {
            $revRows .= '<tr><td>' . htmlspecialchars($item['label'], ENT_QUOTES, 'UTF-8') . '</td><td style="text-align:left;direction:ltr;">' . number_format((float) $item['amount'], 2) . '</td><td style="text-align:center;">' . (int) ($item['count'] ?? 0) . '</td></tr>';
        }

        $costRows = '';
        foreach ($costBreakdown as $item) {
            $costRows .= '<tr><td>' . htmlspecialchars($item['label'], ENT_QUOTES, 'UTF-8') . '</td><td style="text-align:left;direction:ltr;">' . number_format((float) $item['amount'], 2) . '</td><td></td></tr>';
        }

        $trendRows = '';
        foreach ($trend as $t) {
            $trendRows .= '<tr><td>' . htmlspecialchars($t['month'], ENT_QUOTES, 'UTF-8') . '</td><td style="text-align:left;direction:ltr;">' . number_format((float) $t['revenue'], 2) . '</td></tr>';
        }

        $totalRevenue = number_format((float) ($summary['total_revenue'] ?? 0), 2);
        $totalCosts = number_format((float) ($summary['total_costs'] ?? 0), 2);
        $netProfit = number_format((float) ($summary['net_profit'] ?? 0), 2);
        $profitColor = bccomp($summary['net_profit'] ?? '0', '0', 2) >= 0 ? '#059669' : '#DC2626';

        return '<!DOCTYPE html><html dir="rtl" lang="ar"><head><meta charset="utf-8">
<style>
body{font-family:Arial,"Tahoma",sans-serif;font-size:11px;direction:rtl;margin:20px;}
h1{font-size:18px;text-align:center;margin-bottom:4px;color:#0D7377;}
h2{font-size:14px;margin:16px 0 8px;color:#374151;border-bottom:1px solid #E5E7EB;padding-bottom:4px;}
.meta{text-align:center;font-size:10px;color:#6B7280;margin-bottom:16px;}
.cards{display:flex;gap:16px;margin-bottom:16px;}
.card{flex:1;padding:12px;border-radius:8px;text-align:center;}
.card-rev{background:#ECFDF5;color:#065F46;}
.card-cost{background:#FEF2F2;color:#991B1B;}
.card-profit{background:#EFF6FF;color:#1E40AF;}
.card .num{font-size:20px;font-weight:700;}
.card .lbl{font-size:10px;margin-top:2px;}
table{width:100%;border-collapse:collapse;}
th{background:#F3F4F6;padding:6px 8px;text-align:right;font-size:10px;font-weight:600;color:#374151;}
td{padding:5px 8px;border-bottom:1px solid #E5E7EB;font-size:10px;}
</style></head><body>
<h1>التقرير المالي — الأنشطة الرياضية</h1>
<div class="meta">الفترة: ' . htmlspecialchars($dateFrom, ENT_QUOTES, 'UTF-8') . ' إلى ' . htmlspecialchars($dateTo, ENT_QUOTES, 'UTF-8') . ' | تاريخ التقرير: ' . date('Y-m-d H:i') . '</div>
<div class="cards">
<div class="card card-rev"><div class="num">' . $totalRevenue . '</div><div class="lbl">إجمالي الإيرادات</div></div>
<div class="card card-cost"><div class="num">' . $totalCosts . '</div><div class="lbl">إجمالي التكاليف</div></div>
<div class="card card-profit"><div class="num" style="color:' . $profitColor . ';">' . $netProfit . '</div><div class="lbl">صافي الربح</div></div>
</div>
<h2>تفصيل الإيرادات</h2>
<table><thead><tr><th>البند</th><th style="text-align:left;">المبلغ (ج.م)</th><th style="text-align:center;">العدد</th></tr></thead><tbody>' . $revRows . '</tbody></table>
<h2>التكاليف</h2>
<table><thead><tr><th>البند</th><th style="text-align:left;">المبلغ (ج.م)</th><th></th></tr></thead><tbody>' . $costRows . '</tbody></table>
' . (!empty($trendRows) ? '<h2>الاتجاه الشهري</h2><table><thead><tr><th>الشهر</th><th style="text-align:left;">الإيرادات (ج.م)</th></tr></thead><tbody>' . $trendRows . '</tbody></table>' : '') . '
</body></html>';
    }
}
