<?php
declare(strict_types=1);

namespace App\Modules\FacilityGrids\Services;

use App\Core\App;

final class PoolFinancialService
{
    private \App\Core\Database $db;

    public function __construct()
    {
        $this->db = App::getInstance()->db();
    }

    public function getDashboardData(int $gridId, string $dateFrom, string $dateTo): array
    {
        $grid = $this->db->selectOne("SELECT facility_id FROM facility_grids WHERE id = ?", [$gridId]);
        if (!$grid) {
            return [];
        }

        $facilityId = (int) $grid['facility_id'];

        $revenue = $this->db->selectOne(
            "SELECT COALESCE(SUM(total_amount), 0) as total_revenue,
                    COUNT(*) as total_bookings
             FROM reservations
             WHERE facility_id = ? AND reservation_date BETWEEN ? AND ?
             AND status NOT IN ('cancelled', 'no_show')",
            [$facilityId, $dateFrom, $dateTo]
        );

        $revenueByType = $this->db->select(
            "SELECT booker_type, COUNT(*) as count, COALESCE(SUM(total_amount), 0) as revenue
             FROM reservations
             WHERE facility_id = ? AND reservation_date BETWEEN ? AND ?
             AND status NOT IN ('cancelled', 'no_show')
             GROUP BY booker_type",
            [$facilityId, $dateFrom, $dateTo]
        );

        $freeTimeRevenue = $this->db->selectOne(
            "SELECT COALESCE(SUM(amount_paid), 0) as total, COUNT(*) as entries
             FROM free_time_entries
             WHERE facility_id = ? AND entry_date BETWEEN ? AND ? AND status = 'active'",
            [$facilityId, $dateFrom, $dateTo]
        );

        $uniqueUsers = $this->db->selectOne(
            "SELECT COUNT(DISTINCT booker_id) as cnt FROM reservations
             WHERE facility_id = ? AND reservation_date BETWEEN ? AND ?
             AND status NOT IN ('cancelled', 'no_show')",
            [$facilityId, $dateFrom, $dateTo]
        );

        $attendanceSummary = $this->db->selectOne(
            "SELECT COUNT(DISTINCT CASE WHEN entity_type = 'coach' THEN entity_id END) as total_coaches,
                    COUNT(DISTINCT CASE WHEN entity_type = 'trainee' THEN entity_id END) as total_trainees,
                    ROUND(AVG(CASE WHEN status = 'present' THEN 100.0 ELSE 0.0 END), 1) as avg_attendance_rate
             FROM facility_attendance
             WHERE grid_id = ? AND attendance_date BETWEEN ? AND ?",
            [$gridId, $dateFrom, $dateTo]
        );

        $monthlyTrend = $this->db->select(
            "SELECT DATE_FORMAT(reservation_date, '%Y-%m') as month,
                    COALESCE(SUM(total_amount), 0) as revenue, COUNT(*) as bookings
             FROM reservations
             WHERE facility_id = ? AND reservation_date BETWEEN ? AND ?
             AND status NOT IN ('cancelled', 'no_show')
             GROUP BY DATE_FORMAT(reservation_date, '%Y-%m')
             ORDER BY month",
            [$facilityId, $dateFrom, $dateTo]
        );

        return [
            'total_revenue' => (float) ($revenue['total_revenue'] ?? 0) + (float) ($freeTimeRevenue['total'] ?? 0),
            'booking_revenue' => (float) ($revenue['total_revenue'] ?? 0),
            'free_time_revenue' => (float) ($freeTimeRevenue['total'] ?? 0),
            'total_bookings' => (int) ($revenue['total_bookings'] ?? 0),
            'free_time_entries' => (int) ($freeTimeRevenue['entries'] ?? 0),
            'revenue_by_type' => $revenueByType,
            'unique_users' => (int) ($uniqueUsers['cnt'] ?? 0),
            'attendance' => $attendanceSummary,
            'monthly_trend' => $monthlyTrend,
            'period' => ['from' => $dateFrom, 'to' => $dateTo],
        ];
    }

    public function getDateRange(string $filter, ?string $from = null, ?string $to = null): array
    {
        $today = date('Y-m-d');

        return match ($filter) {
            'daily' => ['from' => $today, 'to' => $today],
            'weekly' => ['from' => date('Y-m-d', strtotime('monday this week')), 'to' => date('Y-m-d', strtotime('sunday this week'))],
            'monthly' => ['from' => date('Y-m-01'), 'to' => date('Y-m-t')],
            'yearly' => ['from' => date('Y-01-01'), 'to' => date('Y-12-31')],
            '5years' => ['from' => date('Y-m-d', strtotime('-5 years')), 'to' => $today],
            'custom' => ['from' => $from ?? $today, 'to' => $to ?? $today],
            default => ['from' => date('Y-m-01'), 'to' => date('Y-m-t')],
        };
    }
}
