<?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
    {
        $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');
        $monthStart = date('Y-m-01');
        $weekStart = date('Y-m-d', strtotime('monday this week'));

        $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]
        );

        $todayRevenue = $db->selectOne(
            "SELECT COALESCE(SUM(final_amount), 0) AS total FROM reservations WHERE facility_id = ? AND reservation_date = ? AND payment_status = 'paid'",
            [(int) $id, $today]
        );

        $weekRevenue = $db->selectOne(
            "SELECT COALESCE(SUM(final_amount), 0) AS total FROM reservations WHERE facility_id = ? AND reservation_date >= ? AND payment_status = 'paid'",
            [(int) $id, $weekStart]
        );

        $monthRevenue = $db->selectOne(
            "SELECT COALESCE(SUM(final_amount), 0) AS total FROM reservations WHERE facility_id = ? AND reservation_date >= ? AND payment_status = 'paid'",
            [(int) $id, $monthStart]
        );

        $monthBookingCount = $db->selectOne(
            "SELECT COUNT(*) AS cnt FROM reservations WHERE facility_id = ? AND reservation_date >= ? AND status NOT IN ('cancelled')",
            [(int) $id, $monthStart]
        );

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

        return $this->view('FacilityDashboards.Views.dashboard', [
            'facility'          => $facility,
            'todayBookings'     => $todayBookings,
            'todayRevenue'      => (float) ($todayRevenue['total'] ?? 0),
            'weekRevenue'       => (float) ($weekRevenue['total'] ?? 0),
            'monthRevenue'      => (float) ($monthRevenue['total'] ?? 0),
            'monthBookingCount' => (int) ($monthBookingCount['cnt'] ?? 0),
            'upcomingBookings'  => $upcomingBookings,
        ]);
    }
}
