<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Modules\SportsActivity\Services\AcademyPricingService;

class AcademyPricingController extends Controller
{
    public function index(Request $request)
    {
        $this->authorize('sa.pricing.view');

        $academies = AcademyPricingService::listAcademies();
        $sessionCards = AcademyPricingService::getSessionCardPricing();

        return $this->view('SportsActivity.Views.pricing.academies', [
            'academies' => $academies,
            'sessionCards' => $sessionCards,
        ]);
    }

    public function academies(Request $request)
    {
        $this->authorize('sa.pricing.view');
        $academies = AcademyPricingService::listAcademies();
        return $this->json(['academies' => $academies]);
    }

    public function academyDetail(Request $request, string $code)
    {
        $this->authorize('sa.pricing.view');

        $db = \App\Core\App::getInstance()->db();
        $rows = $db->select(
            "SELECT * FROM sa_academy_pricing
             WHERE academy_code = ? AND is_active = 1
             AND effective_from <= CURDATE()
             AND (effective_to IS NULL OR effective_to >= CURDATE())
             ORDER BY category, sort_order",
            [$code]
        );

        if (empty($rows)) {
            return $this->json(['error' => 'لا توجد بيانات لهذه الأكاديمية'], 404);
        }

        $grouped = [];
        foreach ($rows as $row) {
            $grouped[$row['category']][] = $row;
        }

        return $this->json([
            'academy_code' => $code,
            'academy_name_ar' => $rows[0]['academy_name_ar'],
            'categories' => $grouped,
        ]);
    }

    public function sessionCards(Request $request)
    {
        $this->authorize('sa.pricing.view');
        return $this->json(['cards' => AcademyPricingService::getSessionCardPricing()]);
    }

    public function laneRentals(Request $request)
    {
        $this->authorize('sa.pricing.view');
        $laneType = $request->get('lane_type');
        return $this->json(['rentals' => AcademyPricingService::getLaneRentalPricing($laneType)]);
    }

    public function facilityRentals(Request $request)
    {
        $this->authorize('sa.pricing.view');

        $facilityType = $request->get('facility_type', '');
        $entityType = $request->get('entity_type', '');

        $db = \App\Core\App::getInstance()->db();

        $sql = "SELECT * FROM sa_rental_entity_pricing WHERE is_active = 1
                AND effective_from <= CURDATE()
                AND (effective_to IS NULL OR effective_to >= CURDATE())";
        $params = [];

        if ($facilityType) {
            $sql .= " AND facility_type = ?";
            $params[] = $facilityType;
        }
        if ($entityType) {
            $sql .= " AND entity_type = ?";
            $params[] = $entityType;
        }

        $sql .= " ORDER BY facility_type, entity_type, time_period";

        return $this->json(['rentals' => $db->select($sql, $params)]);
    }

    public function calculate(Request $request)
    {
        $this->authorize('sa.pricing.view');

        $academyCode = (string) ($request->post('academy_code') ?? '');
        $levelNameAr = (string) ($request->post('level_name_ar') ?? '');
        $isMember = (bool) ($request->post('is_member') ?? false);
        $months = max(1, (int) ($request->post('months') ?? 1));
        $hasSibling = (bool) ($request->post('has_sibling') ?? false);

        if (!$academyCode || !$levelNameAr) {
            return $this->json(['error' => 'يجب تحديد الأكاديمية والمستوى'], 422);
        }

        $result = AcademyPricingService::getSubscriptionPrice(
            $academyCode,
            $levelNameAr,
            $isMember,
            $months,
            $hasSibling
        );

        return $this->json($result);
    }
}
