<?php
declare(strict_types=1);

namespace App\Modules\FacilityGrids\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Modules\FacilityGrids\Services\PoolFinancialService;

final class PoolFinancialDashboardController extends Controller
{
    private PoolFinancialService $financialService;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->financialService = new PoolFinancialService();
    }

    public function dashboard(Request $request, string $gridId): Response
    {
        $this->authorize('facility_grid.view');

        $filter = $request->get('filter', 'monthly');
        $from = $request->get('from');
        $to = $request->get('to');

        $range = $this->financialService->getDateRange($filter, $from, $to);
        $data = $this->financialService->getDashboardData((int) $gridId, $range['from'], $range['to']);

        return $this->view('FacilityGrids.Views.pool_financial_dashboard', [
            'grid_id' => (int) $gridId,
            'filter' => $filter,
            'data' => $data,
        ]);
    }

    public function export(Request $request, string $gridId): Response
    {
        $this->authorize('facility_grid.view');

        $filter = $request->get('filter', 'monthly');
        $from = $request->get('from');
        $to = $request->get('to');

        $range = $this->financialService->getDateRange($filter, $from, $to);
        $data = $this->financialService->getDashboardData((int) $gridId, $range['from'], $range['to']);

        $html = $this->renderExportHtml($data, $range);

        $response = new Response();
        return $response->html($html, 200, [
            'Content-Type' => 'text/html; charset=utf-8',
            'Content-Disposition' => 'attachment; filename="pool_report_' . date('Y-m-d') . '.html"',
        ]);
    }

    private function renderExportHtml(array $data, array $range): string
    {
        $html = '<!DOCTYPE html><html dir="rtl" lang="ar"><head><meta charset="utf-8">';
        $html .= '<title>تقرير حمام السباحة المالي</title>';
        $html .= '<style>body{font-family:Cairo,sans-serif;padding:20px;direction:rtl;}';
        $html .= 'table{width:100%;border-collapse:collapse;margin:15px 0;}';
        $html .= 'th,td{border:1px solid #ddd;padding:8px;text-align:right;}';
        $html .= 'th{background:#f4f4f4;}.header{text-align:center;margin-bottom:20px;}';
        $html .= '.stat{display:inline-block;margin:10px;padding:15px;border:1px solid #ddd;border-radius:5px;min-width:150px;text-align:center;}</style></head><body>';
        $html .= '<div class="header"><h1>التقرير المالي - حمام السباحة</h1>';
        $html .= '<p>الفترة: من ' . $range['from'] . ' إلى ' . $range['to'] . '</p></div>';

        $html .= '<div style="text-align:center;">';
        $html .= '<div class="stat"><strong>إجمالي الإيرادات</strong><br>' . number_format($data['total_revenue'], 2) . ' ج.م</div>';
        $html .= '<div class="stat"><strong>إيرادات الحجوزات</strong><br>' . number_format($data['booking_revenue'], 2) . ' ج.م</div>';
        $html .= '<div class="stat"><strong>إيرادات الأوقات الحرة</strong><br>' . number_format($data['free_time_revenue'], 2) . ' ج.م</div>';
        $html .= '<div class="stat"><strong>عدد الحجوزات</strong><br>' . $data['total_bookings'] . '</div>';
        $html .= '<div class="stat"><strong>المستخدمين الفريدين</strong><br>' . $data['unique_users'] . '</div>';
        $html .= '</div>';

        if (!empty($data['revenue_by_type'])) {
            $html .= '<h3>الإيرادات حسب نوع الحاجز</h3><table><tr><th>النوع</th><th>العدد</th><th>الإيرادات</th></tr>';
            foreach ($data['revenue_by_type'] as $row) {
                $html .= '<tr><td>' . e($row['booker_type']) . '</td><td>' . $row['count'] . '</td><td>' . number_format((float) $row['revenue'], 2) . ' ج.م</td></tr>';
            }
            $html .= '</table>';
        }

        if (!empty($data['monthly_trend'])) {
            $html .= '<h3>الاتجاه الشهري</h3><table><tr><th>الشهر</th><th>الحجوزات</th><th>الإيرادات</th></tr>';
            foreach ($data['monthly_trend'] as $row) {
                $html .= '<tr><td>' . $row['month'] . '</td><td>' . $row['bookings'] . '</td><td>' . number_format((float) $row['revenue'], 2) . ' ج.م</td></tr>';
            }
            $html .= '</table>';
        }

        $html .= '<p style="text-align:center;color:#888;margin-top:30px;">تم إنشاء التقرير: ' . date('Y-m-d H:i') . '</p>';
        $html .= '</body></html>';

        return $html;
    }
}
