<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers\Api;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Modules\SportsActivity\Services\PoolGridTemplateService;

class PoolGridTemplateApiController extends Controller
{
    public function list(Request $request, string $id): Response
    {
        $templates = PoolGridTemplateService::getTemplates((int) $id);
        return $this->json(['templates' => $templates]);
    }

    public function store(Request $request, string $id): Response
    {
        $body = $request->jsonBody();
        $name = trim((string) ($body['name'] ?? ''));
        $description = trim((string) ($body['description'] ?? ''));
        $color = trim((string) ($body['color'] ?? '#3B82F6'));
        $entries = $body['entries'] ?? [];

        if (!$name) {
            return $this->json(['error' => 'اسم القالب مطلوب'], 400);
        }

        $result = PoolGridTemplateService::createTemplate((int) $id, $name, $description ?: null, $color, $entries);

        return $this->json($result, $result['success'] ? 200 : 422);
    }

    public function update(Request $request, string $id, string $tid): Response
    {
        $body = $request->jsonBody();
        $name = trim((string) ($body['name'] ?? ''));
        $description = trim((string) ($body['description'] ?? ''));
        $color = trim((string) ($body['color'] ?? '#3B82F6'));
        $entries = $body['entries'] ?? [];

        if (!$name) {
            return $this->json(['error' => 'اسم القالب مطلوب'], 400);
        }

        $db = \App\Core\App::getInstance()->db();
        $ts = date('Y-m-d H:i:s');

        $db->update('sa_pool_zone_templates', [
            'name'        => $name,
            'description' => $description ?: null,
            'color'       => $color,
            'updated_at'  => $ts,
        ], 'id = ?', [(int) $tid]);

        // Replace entries
        $db->delete('sa_pool_zone_template_entries', 'template_id = ?', [(int) $tid]);

        foreach ($entries as $entry) {
            $zoneJson = $entry['zone_selection_json'] ?? '{}';
            if (is_array($zoneJson)) {
                $zoneJson = json_encode($zoneJson, JSON_UNESCAPED_UNICODE);
            }

            $db->insert('sa_pool_zone_template_entries', [
                'template_id'         => (int) $tid,
                'day_of_week'         => (int) ($entry['day_of_week'] ?? 0),
                'start_time'          => $entry['start_time'] ?? '09:00:00',
                'end_time'            => $entry['end_time'] ?? '10:00:00',
                'zone_selection_type' => $entry['zone_selection_type'] ?? 'all',
                'zone_selection_json' => $zoneJson,
                'assignment_type'     => $entry['assignment_type'] ?? 'training',
                'group_id'            => !empty($entry['group_id']) ? (int) $entry['group_id'] : null,
                'coach_id'            => !empty($entry['coach_id']) ? (int) $entry['coach_id'] : null,
                'label'               => $entry['label'] ?? $name,
                'notes'               => $entry['notes'] ?? null,
                'created_at'          => $ts,
                'updated_at'          => $ts,
            ]);
        }

        return $this->json(['success' => true]);
    }

    public function delete(Request $request, string $id, string $tid): Response
    {
        $result = PoolGridTemplateService::deleteTemplate((int) $tid);
        return $this->json($result, $result['success'] ? 200 : 422);
    }

    public function expand(Request $request, string $id, string $tid): Response
    {
        $body = $request->jsonBody();
        $fromDate = trim((string) ($body['from_date'] ?? ''));
        $toDate = trim((string) ($body['to_date'] ?? ''));

        if (!$fromDate || !$toDate) {
            return $this->json(['error' => 'التواريخ مطلوبة'], 400);
        }

        if ($fromDate > $toDate) {
            return $this->json(['error' => 'تاريخ البداية يجب أن يكون قبل النهاية'], 400);
        }

        // Max 60 days to prevent accidental mass generation
        $daysDiff = (strtotime($toDate) - strtotime($fromDate)) / 86400;
        if ($daysDiff > 60) {
            return $this->json(['error' => 'الحد الأقصى 60 يوم للتوسيع'], 400);
        }

        $result = PoolGridTemplateService::expandTemplate((int) $tid, $fromDate, $toDate);

        return $this->json($result, $result['success'] ? 200 : 422);
    }

    public function rollback(Request $request, string $id, string $tid, string $rid): Response
    {
        $result = PoolGridTemplateService::rollbackRun((int) $rid);
        return $this->json($result, $result['success'] ? 200 : 422);
    }
}
