<?php
declare(strict_types=1);

namespace App\Modules\FacilityDashboards\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;

class FacilityDashboardController extends Controller
{
    public function show(Request $request, string $id): Response
    {
        $this->authorize('facility.dashboard');
        $db = App::getInstance()->db();

        $facility = $db->selectOne("SELECT * FROM facilities WHERE id = ? AND is_archived = 0", [(int) $id]);
        if (!$facility) {
            return $this->redirect('/facilities')->withError('المرفق غير موجود');
        }

        $today = date('Y-m-d');

        // Date filter: day, week, month, or custom range
        $filterMode = trim((string) $request->get('filter', 'day'));
        $dateFrom = trim((string) $request->get('date_from', ''));
        $dateTo = trim((string) $request->get('date_to', ''));

        switch ($filterMode) {
            case 'week':
                $periodStart = date('Y-m-d', strtotime('monday this week'));
                $periodEnd = date('Y-m-d', strtotime('sunday this week'));
                $periodLabel = 'هذا الأسبوع';
                break;
            case 'month':
                $periodStart = date('Y-m-01');
                $periodEnd = date('Y-m-t');
                $periodLabel = 'هذا الشهر';
                break;
            case 'custom':
                $periodStart = $dateFrom ?: $today;
                $periodEnd = $dateTo ?: $today;
                $periodLabel = $periodStart . ' — ' . $periodEnd;
                break;
            default: // day
                $periodStart = $today;
                $periodEnd = $today;
                $periodLabel = 'اليوم';
                break;
        }

        $todayBookings = $db->select(
            "SELECT * FROM reservations WHERE facility_id = ? AND reservation_date = ? AND status NOT IN ('cancelled') ORDER BY start_time ASC",
            [(int) $id, $today]
        );

        $periodBookings = $db->select(
            "SELECT * FROM reservations WHERE facility_id = ? AND reservation_date BETWEEN ? AND ? AND status NOT IN ('cancelled') ORDER BY reservation_date ASC, start_time ASC",
            [(int) $id, $periodStart, $periodEnd]
        );

        $periodRevenue = $db->selectOne(
            "SELECT COALESCE(SUM(total_amount), 0) AS total FROM reservations WHERE facility_id = ? AND reservation_date BETWEEN ? AND ? AND payment_id IS NOT NULL AND status NOT IN ('cancelled')",
            [(int) $id, $periodStart, $periodEnd]
        );

        $todayRevenue = $db->selectOne(
            "SELECT COALESCE(SUM(total_amount), 0) AS total FROM reservations WHERE facility_id = ? AND reservation_date = ? AND payment_id IS NOT NULL AND status NOT IN ('cancelled')",
            [(int) $id, $today]
        );

        $weekStart = date('Y-m-d', strtotime('monday this week'));
        $weekRevenue = $db->selectOne(
            "SELECT COALESCE(SUM(total_amount), 0) AS total FROM reservations WHERE facility_id = ? AND reservation_date >= ? AND reservation_date <= ? AND payment_id IS NOT NULL AND status NOT IN ('cancelled')",
            [(int) $id, $weekStart, date('Y-m-d', strtotime('sunday this week'))]
        );

        $monthStart = date('Y-m-01');
        $monthRevenue = $db->selectOne(
            "SELECT COALESCE(SUM(total_amount), 0) AS total FROM reservations WHERE facility_id = ? AND reservation_date >= ? AND reservation_date <= ? AND payment_id IS NOT NULL AND status NOT IN ('cancelled')",
            [(int) $id, $monthStart, date('Y-m-t')]
        );

        $upcomingBookings = $db->select(
            "SELECT * FROM reservations WHERE facility_id = ? AND reservation_date > ? AND status = 'confirmed' ORDER BY reservation_date ASC, start_time ASC LIMIT 10",
            [(int) $id, $today]
        );

        return $this->view('FacilityDashboards.Views.dashboard', [
            'facility'        => $facility,
            'todayBookings'   => $todayBookings,
            'periodBookings'  => $periodBookings,
            'todayRevenue'    => (float) ($todayRevenue['total'] ?? 0),
            'weekRevenue'     => (float) ($weekRevenue['total'] ?? 0),
            'monthRevenue'    => (float) ($monthRevenue['total'] ?? 0),
            'periodRevenue'   => (float) ($periodRevenue['total'] ?? 0),
            'periodLabel'     => $periodLabel,
            'filterMode'      => $filterMode,
            'dateFrom'        => $dateFrom,
            'dateTo'          => $dateTo,
            'upcomingBookings' => $upcomingBookings,
        ]);
    }
}
