<?php
declare(strict_types=1);

namespace App\Modules\FacilityGrids\Models;

use App\Core\Model;
use App\Core\App;

class FacilityMonthlyPlan extends Model
{
    protected static string $table = 'facility_monthly_plans';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $autoTrackAuthor = true;

    protected static array $fillable = [
        'grid_id', 'plan_month', 'plan_name_ar', 'plan_name_en', 'status',
        'working_days_json', 'day_hours_start', 'day_hours_end',
        'night_hours_start', 'night_hours_end', 'cloned_from_id',
        'total_sessions', 'total_coaches', 'total_trainees', 'notes',
        'activated_at', 'activated_by',
    ];

    public static function getStatuses(): array
    {
        return [
            'draft'    => 'مسودة',
            'active'   => 'نشطة',
            'archived' => 'مؤرشفة',
        ];
    }

    public static function getForGrid(int $gridId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM facility_monthly_plans WHERE grid_id = ? ORDER BY plan_month DESC",
            [$gridId]
        );
    }

    public static function getActive(int $gridId): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne(
            "SELECT * FROM facility_monthly_plans WHERE grid_id = ? AND status = 'active' ORDER BY plan_month DESC LIMIT 1",
            [$gridId]
        ) ?: null;
    }

    public function getWorkingDays(): array
    {
        $raw = $this->working_days_json;
        if (empty($raw)) return [1, 2, 3, 4, 5, 6];
        $decoded = json_decode($raw, true);
        return is_array($decoded) ? array_map('intval', $decoded) : [1, 2, 3, 4, 5, 6];
    }

    public function getScheduleCount(): int
    {
        $db = App::getInstance()->db();
        $row = $db->selectOne(
            "SELECT COUNT(*) AS cnt FROM facility_zone_schedules WHERE plan_id = ? AND is_active = 1",
            [(int) $this->id]
        );
        return (int) ($row['cnt'] ?? 0);
    }

    public static function clonePlan(int $sourcePlanId, string $newMonth, string $newNameAr): ?self
    {
        $db = App::getInstance()->db();
        $source = $db->selectOne("SELECT * FROM facility_monthly_plans WHERE id = ?", [$sourcePlanId]);
        if (!$source) return null;

        $plan = self::create([
            'grid_id'            => (int) $source['grid_id'],
            'plan_month'         => $newMonth,
            'plan_name_ar'       => $newNameAr,
            'plan_name_en'       => $source['plan_name_en'],
            'status'             => 'draft',
            'working_days_json'  => $source['working_days_json'],
            'day_hours_start'    => $source['day_hours_start'],
            'day_hours_end'      => $source['day_hours_end'],
            'night_hours_start'  => $source['night_hours_start'],
            'night_hours_end'    => $source['night_hours_end'],
            'cloned_from_id'     => $sourcePlanId,
            'notes'              => 'منسوخة من: ' . ($source['plan_name_ar'] ?? ''),
        ]);

        $schedules = $db->select(
            "SELECT * FROM facility_zone_schedules WHERE plan_id = ? AND is_active = 1",
            [$sourcePlanId]
        );

        foreach ($schedules as $s) {
            $db->insert('facility_zone_schedules', [
                'grid_id'             => (int) $s['grid_id'],
                'plan_id'             => (int) $plan->id,
                'plan_month'          => $newMonth,
                'schedule_name'       => $s['schedule_name'],
                'zone_selection_type' => $s['zone_selection_type'],
                'zone_selection_json' => $s['zone_selection_json'],
                'day_of_week'         => (int) $s['day_of_week'],
                'start_time'          => $s['start_time'],
                'end_time'            => $s['end_time'],
                'activity_type'       => $s['activity_type'],
                'coach_id'            => $s['coach_id'] ? (int) $s['coach_id'] : null,
                'coach_name'          => $s['coach_name'],
                'academy_id'          => $s['academy_id'] ? (int) $s['academy_id'] : null,
                'academy_name'        => $s['academy_name'],
                'age_group'           => $s['age_group'],
                'gender'              => $s['gender'],
                'max_occupants'       => (int) $s['max_occupants'],
                'color'               => $s['color'],
                'effective_from'      => $newMonth . '-01',
                'effective_to'        => date('Y-m-t', strtotime($newMonth . '-01')),
                'is_active'           => 1,
                'notes'               => $s['notes'],
                'created_at'          => date('Y-m-d H:i:s'),
                'updated_at'          => date('Y-m-d H:i:s'),
            ]);
        }

        $plan->update([
            'total_sessions' => count($schedules),
        ]);

        return $plan;
    }
}
