<?php
namespace App\Modules\Calendar\Controllers;

class CalendarController extends \Core\Controller {

    // ─────────────────────────────────────────────────────────────
    //  MAIN VIEW
    // ─────────────────────────────────────────────────────────────
    public function index() {
        $model    = $this->model('Calendar/Models/CalendarModel');
        $viewMode = $_GET['view'] ?? 'month';

        $year  = isset($_GET['year'])  ? (int)$_GET['year']  : (int)date('Y');
        $month = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('n');

        if ($month < 1)  { $month = 12; $year--; }
        if ($month > 12) { $month = 1;  $year++; }

        $targetDate = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

        $eventsByDate     = [];
        $events           = [];
        $timeBlocksByDate = [];
        $startOfWeek      = null;
        $endOfWeek        = null;

        if ($viewMode === 'day') {
            $events     = $model->getEventsByDate($this->userId, $targetDate);
            $timeBlocks = $model->getTimeBlocks($this->userId, $targetDate);
            foreach ($timeBlocks as $tb) {
                $timeBlocksByDate[$tb->block_date][] = $tb;
            }
        } elseif ($viewMode === 'week') {
            $dateObj   = new \DateTime($targetDate);
            $dayOfWeek = (int)$dateObj->format('w');
            $offset    = ($dayOfWeek === 6) ? 0 : ($dayOfWeek + 1);
            $startOfWeek = clone $dateObj;
            $startOfWeek->modify("-{$offset} days");
            $endOfWeek = clone $startOfWeek;
            $endOfWeek->modify('+6 days');

            $events     = $model->getEventsInDateRange($this->userId, $startOfWeek->format('Y-m-d'), $endOfWeek->format('Y-m-d'));
            $timeBlocks = $model->getTimeBlocksInRange($this->userId, $startOfWeek->format('Y-m-d'), $endOfWeek->format('Y-m-d'));
            foreach ($timeBlocks as $tb) {
                $timeBlocksByDate[$tb->block_date][] = $tb;
            }
        } else {
            $events     = $model->getEventsByMonth($this->userId, $year, $month);
            $startDate  = sprintf("%04d-%02d-01", $year, $month);
            $endDate    = date("Y-m-t", strtotime($startDate));
            $timeBlocks = $model->getTimeBlocksInRange($this->userId, $startDate, $endDate);
            foreach ($timeBlocks as $tb) {
                $timeBlocksByDate[$tb->block_date][] = $tb;
            }
        }

        // Fetch tasks with due_dates
        $tasks = [];
        $db    = \Core\Database::getInstance();
        if ($viewMode === 'day') {
            $tasks = $db->query(
                "SELECT * FROM todo_tasks WHERE user_id = ? AND (due_date = ? OR (due_date IS NULL AND target_date = ?)) AND deleted_at IS NULL",
                [$this->userId, $targetDate, $targetDate]
            )->fetchAll();
        } elseif ($viewMode === 'week') {
            $tasks = $db->query(
                "SELECT * FROM todo_tasks WHERE user_id = ? AND (due_date >= ? AND due_date <= ? OR (due_date IS NULL AND target_date >= ? AND target_date <= ?)) AND deleted_at IS NULL",
                [$this->userId, $startOfWeek->format('Y-m-d'), $endOfWeek->format('Y-m-d'), $startOfWeek->format('Y-m-d'), $endOfWeek->format('Y-m-d')]
            )->fetchAll();
        } else {
            $tasksStart = sprintf("%04d-%02d-01", $year, $month);
            $tasksEnd   = date("Y-m-t", strtotime($tasksStart));
            $tasks = $db->query(
                "SELECT * FROM todo_tasks WHERE user_id = ? AND (due_date >= ? AND due_date <= ? OR (due_date IS NULL AND target_date >= ? AND target_date <= ?)) AND deleted_at IS NULL",
                [$this->userId, $tasksStart, $tasksEnd, $tasksStart, $tasksEnd]
            )->fetchAll();
        }

        // Merge tasks as pseudo-events
        foreach ($tasks as $task) {
            $pseudoEvent = new \stdClass();
            $pseudoEvent->id          = 'task_' . $task->id;
            $pseudoEvent->task_id     = $task->id;
            $pseudoEvent->title       = $task->title;
            $pseudoEvent->description = $task->description ?? '';
            $pseudoEvent->event_date  = !empty($task->due_date) ? $task->due_date : $task->target_date;
            $pseudoEvent->start_time  = null;
            $pseudoEvent->end_time    = null;
            $pseudoEvent->color_hex   = null;
            $pseudoEvent->category    = 'tasks';
            $pseudoEvent->is_task     = true;
            $pseudoEvent->status      = $task->status;
            $pseudoEvent->is_overdue  = ($pseudoEvent->event_date < date('Y-m-d') && $task->status !== 'done');
            $events[] = $pseudoEvent;
        }

        foreach ($events as $ev) {
            $eventsByDate[$ev->event_date][] = $ev;
        }

        // Intelligence data
        $missedEvents   = $model->getMissedEvents($this->userId);
        $weeklyPattern  = $model->getWeeklyPattern($this->userId);
        $energySchedule = $model->getEnergySchedule($this->userId);
        
        $milestones = $model->getGoalMilestones($this->userId, $year, $month);
        $timeUsage  = $model->getTimeUsageAnalytics($this->userId, 
            $viewMode === 'day' ? $targetDate : ($viewMode === 'week' ? $startOfWeek->format('Y-m-d') : sprintf("%04d-%02d-01", $year, $month)), 
            $viewMode === 'day' ? $targetDate : ($viewMode === 'week' ? $endOfWeek->format('Y-m-d') : date("Y-m-t", strtotime(sprintf("%04d-%02d-01", $year, $month))))
        );

        $customCategories = $model->getCategories($this->userId);

        $this->view('Calendar/Views/index', [
            'title'            => 'نظام إدارة الوقت الذكي',
            'year'             => $year,
            'month'            => $month,
            'targetDate'       => $targetDate,
            'viewMode'         => $viewMode,
            'eventsByDate'     => $eventsByDate,
            'events'           => $events,
            'timeBlocksByDate' => $timeBlocksByDate,
            'missedEvents'     => $missedEvents,
            'weeklyPattern'    => $weeklyPattern,
            'energySchedule'   => $energySchedule,
            'milestones'       => $milestones,
            'timeUsage'        => $timeUsage,
            'customCategories' => $customCategories,
            'startOfWeek'      => $startOfWeek,
            'endOfWeek'        => $endOfWeek,
        ]);
    }

    // ─────────────────────────────────────────────────────────────
    //  STORE EVENT (with update support)
    // ─────────────────────────────────────────────────────────────
    public function store() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') return;

        verify_csrf_token($_POST['csrf_token'] ?? '');
        $model = $this->model('Calendar/Models/CalendarModel');

        $data = [
            'title'               => get_secure_post('title'),
            'description'         => get_secure_post('description'),
            'category'            => get_secure_post('category') ?: 'other',
            'event_type'          => get_secure_post('event_type') ?: 'event',
            'event_date'          => get_secure_post('event_date') ?: null,
            'start_time'          => get_secure_post('start_time') !== '' ? get_secure_post('start_time') : null,
            'end_time'            => get_secure_post('end_time') !== '' ? get_secure_post('end_time') : null,
            'color_hex'           => get_secure_post('color_hex') ?: '#0d6efd',
            'recurrence_type'     => get_secure_post('recurrence_type') ?: 'none',
            'recurrence_end_date' => get_secure_post('recurrence_end_date') !== '' ? get_secure_post('recurrence_end_date') : null,
            'create_task'         => isset($_POST['create_task']) ? 1 : 0,
        ];

        // Conflict check
        if (!empty($data['start_time']) && !empty($data['end_time'])) {
            $ignoreId = !empty($_POST['event_id']) ? (int)$_POST['event_id'] : null;
            $conflict = $model->detectConflict($this->userId, $data['event_date'], $data['start_time'], $data['end_time'], $ignoreId);
            if ($conflict) {
                set_flash_message('calendar', 'يوجد تعارض مع الحدث: ' . $conflict->title, 'danger');
                redirect($_SERVER['HTTP_REFERER'] ?? '/calendar/index');
                exit;
            }
        }

        // Retroactive logging is allowed, but we validate recurrence.

        if ($data['recurrence_type'] !== 'none' && $data['recurrence_end_date'] && $data['recurrence_end_date'] < $data['event_date']) {
            set_flash_message('calendar', 'تاريخ انتهاء التكرار لا يمكن أن يكون قبل تاريخ الحدث.', 'danger');
            redirect($_SERVER['HTTP_REFERER'] ?? '/calendar/index');
            exit;
        }

        if (!empty($_POST['event_id'])) {
            $scope = get_secure_post('edit_scope') ?: 'all';
            $model->updateEvent((int)$_POST['event_id'], $this->userId, $data, $scope);
            set_flash_message('calendar', 'تم تحديث الحدث بنجاح.', 'info');
        } else {
            $model->addEvent($this->userId, $data);
            set_flash_message('calendar', 'تم حفظ الحدث بنجاح.', 'success');
        }

        redirect($_SERVER['HTTP_REFERER'] ?? '/calendar/index');
    }

    // ─────────────────────────────────────────────────────────────
    //  RESCHEDULE (Drag & Drop) — CSRF protected
    // ─────────────────────────────────────────────────────────────
    public function reschedule() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') return;

        $data    = json_decode(file_get_contents('php://input'), true);
        $csrf    = $data['csrf_token'] ?? '';
        verify_csrf_token($csrf);

        $eventId = $data['event_id'] ?? null;
        $newDate = $data['new_date'] ?? null;

        if (!$eventId || !$newDate) {
            echo json_encode(['success' => false, 'message' => 'بيانات مفقودة']);
            exit;
        }

        // Allow retroactive rescheduling if needed by the user.

        $model = $this->model('Calendar/Models/CalendarModel');
        if ($model->rescheduleEvent($eventId, $this->userId, $newDate)) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'حدث خطأ داخلي أثناء النقل']);
        }
        exit;
    }

    // ─────────────────────────────────────────────────────────────
    //  ARCHIVE EVENT
    // ─────────────────────────────────────────────────────────────
    public function archive($id) {
        $model = $this->model('Calendar/Models/CalendarModel');
        if ($model->delete($id, $this->userId)) {
            set_flash_message('calendar', 'تم أرشفة الحدث.', 'warning');
        } else {
            set_flash_message('calendar', 'حدث خطأ أثناء المحاولة.', 'danger');
        }
        redirect($_SERVER['HTTP_REFERER'] ?? '/calendar');
    }

    // ─────────────────────────────────────────────────────────────
    //  TIME BLOCKS — Store
    // ─────────────────────────────────────────────────────────────
    public function storeTimeBlock() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') return;

        $data = json_decode(file_get_contents('php://input'), true);
        verify_csrf_token($data['csrf_token'] ?? '');

        $blockData = [
            'title'      => htmlspecialchars(strip_tags($data['title'] ?? ''), ENT_QUOTES, 'UTF-8'),
            'block_date' => $data['block_date'] ?? date('Y-m-d'),
            'start_time' => $data['start_time'] ?? '08:00',
            'end_time'   => $data['end_time'] ?? '09:00',
            'category'   => $data['category'] ?? 'focus',
            'color_hex'  => $data['color_hex'] ?? '#6366f1',
            'notes'      => htmlspecialchars(strip_tags($data['notes'] ?? ''), ENT_QUOTES, 'UTF-8'),
        ];

        if (empty($blockData['title'])) {
            echo json_encode(['success' => false, 'message' => 'العنوان مطلوب']);
            exit;
        }

        $model = $this->model('Calendar/Models/CalendarModel');
        $id    = $model->addTimeBlock($this->userId, $blockData);
        echo json_encode(['success' => true, 'id' => $id]);
        exit;
    }

    // ─────────────────────────────────────────────────────────────
    //  TIME BLOCKS — Delete
    // ─────────────────────────────────────────────────────────────
    public function deleteTimeBlock() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') return;

        $data = json_decode(file_get_contents('php://input'), true);
        verify_csrf_token($data['csrf_token'] ?? '');

        $id    = (int)($data['block_id'] ?? 0);
        $model = $this->model('Calendar/Models/CalendarModel');
        $model->deleteTimeBlock($id, $this->userId);
        echo json_encode(['success' => true]);
        exit;
    }

    // ─────────────────────────────────────────────────────────────
    //  TASK QUICK TOGGLE
    // ─────────────────────────────────────────────────────────────
    public function taskToggle() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') return;

        $data = json_decode(file_get_contents('php://input'), true);
        verify_csrf_token($data['csrf_token'] ?? '');

        $taskId    = (int)($data['task_id'] ?? 0);
        $newStatus = ($data['status'] ?? 'pending') === 'done' ? 'done' : 'pending';

        if (!$taskId) {
            echo json_encode(['success' => false, 'message' => 'معرف المهمة مفقود']);
            exit;
        }

        $db = \Core\Database::getInstance();
        $db->query(
            "UPDATE todo_tasks SET status = ? WHERE id = ? AND user_id = ? AND deleted_at IS NULL",
            [$newStatus, $taskId, $this->userId]
        );
        echo json_encode(['success' => true, 'new_status' => $newStatus]);
        exit;
    }

    // ─────────────────────────────────────────────────────────────
    //  DAY SUMMARY (AJAX for hover tooltip)
    // ─────────────────────────────────────────────────────────────
    public function daySummary() {
        $date  = $_GET['date'] ?? date('Y-m-d');
        $model = $this->model('Calendar/Models/CalendarModel');
        echo json_encode($model->getDaySummary($this->userId, $date));
        exit;
    }

    // ─────────────────────────────────────────────────────────────
    //  WEEKLY PATTERN (AJAX)
    // ─────────────────────────────────────────────────────────────
    public function weeklyPattern() {
        $model   = $this->model('Calendar/Models/CalendarModel');
        $pattern = $model->getWeeklyPattern($this->userId);
        echo json_encode(['success' => true, 'pattern' => $pattern]);
        exit;
    }

    // ─────────────────────────────────────────────────────────────
    //  ENERGY SCHEDULE (AJAX)
    // ─────────────────────────────────────────────────────────────
    public function energySchedule() {
        $model = $this->model('Calendar/Models/CalendarModel');
        $data  = $model->getEnergySchedule($this->userId);
        echo json_encode(['success' => true, 'data' => $data]);
        exit;
    }

    // ─────────────────────────────────────────────────────────────
    //  SUGGEST RESCHEDULE (AJAX)
    // ─────────────────────────────────────────────────────────────
    public function suggestReschedule() {
        $eventId = (int)($_GET['event_id'] ?? 0);
        if (!$eventId) {
            echo json_encode(['success' => false]);
            exit;
        }

        $model = $this->model('Calendar/Models/CalendarModel');
        $event = $model->getEventById($eventId, $this->userId);

        if (!$event) {
            echo json_encode(['success' => false, 'message' => 'الحدث غير موجود']);
            exit;
        }

        // Suggest next available weekday from today
        $suggested = new \DateTime();
        $suggested->modify('+1 day');
        // Skip Fridays (6) and Saturdays (7 in DAYOFWEEK); PHP w: 5=Fri, 6=Sat
        $tries = 0;
        while (in_array((int)$suggested->format('w'), [5, 6]) && $tries < 7) {
            $suggested->modify('+1 day');
            $tries++;
        }

        echo json_encode([
            'success'       => true,
            'original_date' => $event->event_date,
            'suggested_date'=> $suggested->format('Y-m-d'),
            'event_title'   => $event->title,
            'event_id'      => $event->id,
        ]);
        exit;
    }

    // ─────────────────────────────────────────────────────────────
    //  CATEGORY CRUD
    // ─────────────────────────────────────────────────────────────
    public function addCategory() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') return;
        verify_csrf_token($_POST['csrf_token'] ?? '');
        $name = get_secure_post('name');
        if (empty($name)) {
            set_flash_message('calendar', 'اسم التصنيف مطلوب', 'danger');
            redirect($_SERVER['HTTP_REFERER']);
            exit;
        }

        $colors = [
            ['bg' => '#e0e7ff', 'text' => '#4338ca', 'border' => '#818cf8'],
            ['bg' => '#fce7f3', 'text' => '#be185d', 'border' => '#f472b6'],
            ['bg' => '#dcfce7', 'text' => '#15803d', 'border' => '#4ade80'],
            ['bg' => '#fef9c3', 'text' => '#a16207', 'border' => '#facc15'],
            ['bg' => '#f3f4f6', 'text' => '#374151', 'border' => '#9ca3af'],
            ['bg' => '#e0f2fe', 'text' => '#0369a1', 'border' => '#38bdf8'],
            ['bg' => '#fef2f2', 'text' => '#b91c1c', 'border' => '#f87171'],
            ['bg' => '#fdf4ff', 'text' => '#86198f', 'border' => '#e879f9'],
        ];

        // random select color since UI doesn't provide picking yet unless we do
        $bg = get_secure_post('bg_color');
        if (empty($bg) || $bg == '#000000') {
            $rand = $colors[array_rand($colors)];
        } else {
            // we do a simple assumption the user picked bg, we generate borders or just use it
            $rand = ['bg' => $bg, 'text' => '#ffffff', 'border' => $bg];
        }

        $model = $this->model('Calendar/Models/CalendarModel');
        $model->addCategory($this->userId, [
            'name' => $name,
            'bg_color' => $rand['bg'],
            'text_color' => $rand['text'],
            'border_color' => $rand['border'],
        ]);
        set_flash_message('calendar', 'تم إضافة التصنيف بنجاح', 'success');
        redirect($_SERVER['HTTP_REFERER']);
    }

    public function deleteCategory($id) {
        $model = $this->model('Calendar/Models/CalendarModel');
        $model->deleteCategory($this->userId, $id);
        set_flash_message('calendar', 'تم حذف التصنيف', 'info');
        redirect($_SERVER['HTTP_REFERER']);
    }
}
