<?php
declare(strict_types=1);

namespace App\Modules\FacilityGrids\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\FacilityGrids\Models\FacilityGrid;
use App\Modules\FacilityGrids\Models\FacilityMonthlyPlan;

class MonthlyPlanController extends Controller
{
    public function index(Request $request, string $gridId): Response
    {
        $this->authorize('facility_grid.manage');
        $grid = FacilityGrid::find((int) $gridId);
        if (!$grid) return $this->redirect('/facility-grids')->withError('الشبكة غير موجودة');

        $plans = FacilityMonthlyPlan::getForGrid((int) $gridId);

        return $this->view('FacilityGrids.Views.monthly_plans', [
            'grid'  => $grid,
            'plans' => $plans,
        ]);
    }

    public function create(Request $request, string $gridId): Response
    {
        $this->authorize('facility_grid.manage');
        $grid = FacilityGrid::find((int) $gridId);
        if (!$grid) return $this->redirect('/facility-grids')->withError('الشبكة غير موجودة');

        $existingPlans = FacilityMonthlyPlan::getForGrid((int) $gridId);

        return $this->view('FacilityGrids.Views.monthly_plan_create', [
            'grid'          => $grid,
            'existingPlans' => $existingPlans,
        ]);
    }

    public function store(Request $request, string $gridId): Response
    {
        $this->authorize('facility_grid.manage');
        $grid = FacilityGrid::find((int) $gridId);
        if (!$grid) return $this->redirect('/facility-grids')->withError('الشبكة غير موجودة');

        $planMonth = trim((string) $request->post('plan_month', ''));
        $planNameAr = trim((string) $request->post('plan_name_ar', ''));

        if (!$planMonth || !$planNameAr) {
            return $this->redirect("/facility-grids/{$gridId}/plans/create")->withError('الشهر والاسم مطلوبان');
        }

        $db = App::getInstance()->db();
        $existing = $db->selectOne(
            "SELECT id FROM facility_monthly_plans WHERE grid_id = ? AND plan_month = ?",
            [(int) $gridId, $planMonth]
        );
        if ($existing) {
            return $this->redirect("/facility-grids/{$gridId}/plans/create")->withError('توجد خطة لهذا الشهر بالفعل');
        }

        $cloneFromId = $request->post('clone_from_id') ? (int) $request->post('clone_from_id') : null;

        if ($cloneFromId) {
            $plan = FacilityMonthlyPlan::clonePlan($cloneFromId, $planMonth, $planNameAr);
            if (!$plan) {
                return $this->redirect("/facility-grids/{$gridId}/plans/create")->withError('فشل نسخ الخطة');
            }
            return $this->redirect("/facility-grids/{$gridId}/plans")->withSuccess("تم نسخ الخطة: {$planNameAr}");
        }

        $workingDays = $request->post('working_days') ?: [1, 2, 3, 4, 5, 6];

        FacilityMonthlyPlan::create([
            'grid_id'           => (int) $gridId,
            'plan_month'        => $planMonth,
            'plan_name_ar'      => $planNameAr,
            'plan_name_en'      => trim((string) $request->post('plan_name_en', '')),
            'status'            => 'draft',
            'working_days_json' => json_encode(array_map('intval', (array) $workingDays)),
            'day_hours_start'   => $request->post('day_hours_start', '06:00'),
            'day_hours_end'     => $request->post('day_hours_end', '14:00'),
            'night_hours_start' => $request->post('night_hours_start', '14:00'),
            'night_hours_end'   => $request->post('night_hours_end', '22:00'),
            'notes'             => trim((string) $request->post('notes', '')),
        ]);

        return $this->redirect("/facility-grids/{$gridId}/plans")->withSuccess("تم إنشاء الخطة: {$planNameAr}");
    }

    public function show(Request $request, string $gridId, string $planId): Response
    {
        $this->authorize('facility_grid.view');
        $grid = FacilityGrid::find((int) $gridId);
        $plan = FacilityMonthlyPlan::find((int) $planId);
        if (!$grid || !$plan) return $this->redirect('/facility-grids')->withError('غير موجود');

        $db = App::getInstance()->db();
        $schedules = $db->select(
            "SELECT fzs.*, c.id AS coach_exists
             FROM facility_zone_schedules fzs
             LEFT JOIN coaches c ON c.id = fzs.coach_id
             WHERE fzs.plan_id = ? AND fzs.is_active = 1
             ORDER BY fzs.day_of_week ASC, fzs.start_time ASC",
            [(int) $planId]
        );

        $dayNames = ['الأحد', 'الإثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'];

        return $this->view('FacilityGrids.Views.monthly_plan_show', [
            'grid'      => $grid,
            'plan'      => $plan,
            'schedules' => $schedules,
            'dayNames'  => $dayNames,
        ]);
    }

    public function activate(Request $request, string $gridId, string $planId): Response
    {
        $this->authorize('facility_grid.manage');
        $plan = FacilityMonthlyPlan::find((int) $planId);
        if (!$plan || (int) $plan->grid_id !== (int) $gridId) {
            return $this->redirect("/facility-grids/{$gridId}/plans")->withError('خطة غير موجودة');
        }

        $db = App::getInstance()->db();
        $db->query(
            "UPDATE facility_monthly_plans SET status = 'archived', updated_at = NOW() WHERE grid_id = ? AND status = 'active'",
            [(int) $gridId]
        );

        $employee = App::getInstance()->currentEmployee();
        $plan->update([
            'status'       => 'active',
            'activated_at' => date('Y-m-d H:i:s'),
            'activated_by' => $employee ? (int) $employee->id : null,
        ]);

        return $this->redirect("/facility-grids/{$gridId}/plans")->withSuccess('تم تفعيل الخطة');
    }

    public function archive(Request $request, string $gridId, string $planId): Response
    {
        $this->authorize('facility_grid.manage');
        $plan = FacilityMonthlyPlan::find((int) $planId);
        if (!$plan || (int) $plan->grid_id !== (int) $gridId) {
            return $this->redirect("/facility-grids/{$gridId}/plans")->withError('خطة غير موجودة');
        }

        $plan->update(['status' => 'archived']);
        return $this->redirect("/facility-grids/{$gridId}/plans")->withSuccess('تم أرشفة الخطة');
    }

    public function diff(Request $request, string $gridId, string $planId): Response
    {
        $this->authorize('facility_grid.view');
        $plan = FacilityMonthlyPlan::find((int) $planId);
        if (!$plan) return $this->json(['success' => false]);

        $clonedFromId = $plan->cloned_from_id ? (int) $plan->cloned_from_id : null;
        if (!$clonedFromId) return $this->json(['success' => true, 'diff' => [], 'message' => 'لا توجد خطة سابقة للمقارنة']);

        $db = App::getInstance()->db();
        $currentSchedules = $db->select(
            "SELECT schedule_name, day_of_week, start_time, end_time, coach_name, academy_name, zone_selection_json FROM facility_zone_schedules WHERE plan_id = ? AND is_active = 1",
            [(int) $planId]
        );
        $previousSchedules = $db->select(
            "SELECT schedule_name, day_of_week, start_time, end_time, coach_name, academy_name, zone_selection_json FROM facility_zone_schedules WHERE plan_id = ? AND is_active = 1",
            [$clonedFromId]
        );

        $added = count($currentSchedules) - count($previousSchedules);

        return $this->json([
            'success'  => true,
            'current'  => count($currentSchedules),
            'previous' => count($previousSchedules),
            'added'    => max(0, $added),
            'removed'  => max(0, -$added),
        ]);
    }
}
