<?php
namespace App\Modules\Todo\Models;

class TodoModel extends \Core\Model {
    protected $table = 'todo_tasks';
    protected $moduleName = 'Todo';
    protected $useSoftDeletes = false;

    // ─────────────────────────────────────────────────────────────
    // CATEGORY UNIFICATION
    // ─────────────────────────────────────────────────────────────
    public function getCategories($userId) {
        // Fallback or read from calendar_categories if exists
        try {
            return $this->query("SELECT * FROM calendar_categories WHERE user_id = ? ORDER BY id ASC", [$userId])->fetchAll();
        } catch (\Exception $e) {
            return []; // Safe fallback
        }
    }

    // ─────────────────────────────────────────────────────────────
    // DAHSBOARD TASKS & OVERDUE
    // ─────────────────────────────────────────────────────────────
    public function getDashboardTasks($userId, $targetDate) {
        $today = date('Y-m-d');
        // Retrieve ONLY tasks for the exact target date to maintain pure planning
        $sql = "SELECT t.*, c.title as event_title 
                FROM {$this->table} t
                LEFT JOIN calendar_events c ON t.event_id = c.id
                WHERE t.user_id = ? AND t.target_date = ? AND t.deleted_at IS NULL 
                ORDER BY t.is_daily_focus DESC, 
                CASE t.priority WHEN 'high' THEN 1 WHEN 'medium' THEN 2 ELSE 3 END ASC, 
                t.id ASC";
        return $this->query($sql, [$userId, $targetDate])->fetchAll();
    }

    public function getOverdueTasks($userId) {
        $today = date('Y-m-d');
        $sql = "SELECT * FROM {$this->table} 
                WHERE user_id = ? AND target_date < ? AND status NOT IN ('done', 'skipped') AND deleted_at IS NULL
                ORDER BY target_date ASC";
        return $this->query($sql, [$userId, $today])->fetchAll();
    }

    // ─────────────────────────────────────────────────────────────
    // INTELLIGENT PRIORITY ENGINE
    // ─────────────────────────────────────────────────────────────
    public function autoPrioritizeTasks($userId, $targetDate) {
        $today = date('Y-m-d');
        // Upgrade priority to 'high' if due_date is today or passed for pending tasks on this date
        $sql = "UPDATE {$this->table} 
                SET priority = 'high' 
                WHERE user_id = ? AND target_date = ? AND status = 'pending' AND deleted_at IS NULL 
                AND due_date IS NOT NULL AND due_date <= ?";
        $this->query($sql, [$userId, $targetDate, $today]);
    }

    // ─────────────────────────────────────────────────────────────
    // TASK CRUD & 2-WAY SYNC
    // ─────────────────────────────────────────────────────────────
    public function addTask($userId, $data) {
        $eventId = null;
        if (!empty($data['add_to_calendar'])) {
            $eventDate = !empty($data['due_date']) ? $data['due_date'] : $data['target_date'];
            // Sync Category color if possible
            $color = '#3b82f6';
            if (!empty($data['category'])) {
                try {
                    $catRow = $this->query("SELECT border_color FROM calendar_categories WHERE user_id=? AND (id=? OR system_key=?) LIMIT 1", [$userId, $data['category'], $data['category']])->fetch();
                    if ($catRow) $color = $catRow->border_color;
                } catch (\Exception $e) {}
            }
            
            $sqlEvent = "INSERT INTO calendar_events (user_id, title, description, category, event_date, color_hex, recurrence_type, status, event_type) VALUES (?, ?, ?, ?, ?, ?, 'none', 'active', 'event')";
            $this->query($sqlEvent, [
                $userId,
                $data['title'],
                $data['description'] ?? null,
                $data['category'] ?? 'other',
                $eventDate,
                $color
            ]);
            $eventId = $this->db->lastInsertId();
        }

        // Subtasks support ready via parent_id if supplied
        $sql = "INSERT INTO {$this->table} (user_id, title, description, category, priority, estimated_time, energy_level, target_date, due_date, status, skill_id, event_id, parent_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?)";
        $res = $this->query($sql, [
            $userId, 
            $data['title'], 
            $data['description'] ?? null, 
            $data['category'] ?? 'other', 
            $data['priority'] ?? 'medium', 
            $data['estimated_time'] ?? 0, 
            $data['energy_level'] ?? 'medium', 
            $data['target_date'],
            !empty($data['due_date']) ? $data['due_date'] : null,
            $data['skill_id'] ?? null,
            $eventId,
            $data['parent_id'] ?? null
        ]);
        $this->logAction($userId, 'created', "إضافة مهمة جديدة: {$data['title']}");
        return $res;
    }

    public function updateTaskStatus($id, $userId, $status) {
        $task = $this->getTaskById($id, $userId);
        if (!$task) return false;
        
        $sql = "UPDATE {$this->table} SET status = ? WHERE id = ? AND user_id = ? AND deleted_at IS NULL";
        $res = $this->query($sql, [$status, $id, $userId]);
        
        // 2-Way Sync: Calendar Event (Is_completed logic)
        if (!empty($task->event_id)) {
            $isCompleted = ($status === 'done') ? 1 : 0;
            // Also cross-sync archive if skipped
            $evtStatus = ($status === 'skipped') ? 'archived' : 'active';
            $this->query("UPDATE calendar_events SET is_completed = ?, status = ? WHERE id = ? AND user_id = ?", [$isCompleted, $evtStatus, $task->event_id, $userId]);
        }
        
        $this->logAction($userId, 'updated', "تحديث حالة المهمة رقم {$id} إلى {$status}");
        return $res;
    }

    public function rescheduleTask($id, $userId, $newDate) {
        $task = $this->getTaskById($id, $userId);
        if (!$task) return false;

        $sql = "UPDATE {$this->table} SET target_date = ? WHERE id = ? AND user_id = ? AND deleted_at IS NULL";
        $res = $this->query($sql, [$newDate, $id, $userId]);
        
        // 2-Way Sync: Move calendar event target day
        if (!empty($task->event_id)) {
            $this->query("UPDATE calendar_events SET event_date = ? WHERE id = ? AND user_id = ?", [$newDate, $task->event_id, $userId]);
        }
        
        return $res;
    }

    public function toggleDailyFocus($id, $userId, $isFocus) {
        return $this->query("UPDATE {$this->table} SET is_daily_focus = ? WHERE id = ? AND user_id = ? AND deleted_at IS NULL", [$isFocus, $id, $userId]);
    }

    public function getTaskById($id, $userId) {
        return $this->query("SELECT * FROM {$this->table} WHERE id = ? AND user_id = ? AND deleted_at IS NULL", [$id, $userId])->fetch();
    }

    public function softDeleteTask($id, $userId) {
        $task = $this->getTaskById($id, $userId);
        $res = $this->query("UPDATE {$this->table} SET deleted_at = CURRENT_TIMESTAMP WHERE id = ? AND user_id = ?", [$id, $userId]);
        
        if ($task && !empty($task->event_id)) {
            $this->query("UPDATE calendar_events SET deleted_at = CURRENT_TIMESTAMP WHERE id = ? AND user_id = ?", [$task->event_id, $userId]);
        }
        
        $this->logAction($userId, 'deleted', "حذف مهمة رقم {$id}");
        return $res;
    }

    // ─────────────────────────────────────────────────────────────
    // MOMENTUM SCORE & INTELLIGENCE
    // ─────────────────────────────────────────────────────────────
    public function getSubtasks($taskId, $userId) {
        try {
            return $this->query("SELECT * FROM {$this->table} WHERE parent_id = ? AND user_id = ? AND deleted_at IS NULL ORDER BY id ASC", [$taskId, $userId])->fetchAll();
        } catch (\Exception $e) {
            return []; // Fallback if schema unapplied
        }
    }

    public function calculateMomentumScore($userId, $date) {
        $tasks = $this->getDashboardTasks($userId, $date);
        if (empty($tasks)) return ['score'=>0, 'label'=>'لا توجد بيانات'];
        
        $totalWeight = 0;
        $earnedWeight = 0;
        foreach ($tasks as $t) {
            // Focus tasks are worth 3, high 2, mediums 1, low 0.5
            $w = $t->is_daily_focus ? 3 : ($t->priority == 'high' ? 2 : ($t->priority == 'medium' ? 1 : 0.5));
            $totalWeight += $w;
            if ($t->status == 'done') {
                $earnedWeight += $w;
            }
        }
        
        $score = $totalWeight > 0 ? round(($earnedWeight / $totalWeight) * 100) : 0;
        
        $label = 'متأخر';
        if ($score >= 90) $label = 'ممتاز وملهم 🚀';
        else if ($score >= 75) $label = 'زخم عالي 🔥';
        else if ($score >= 50) $label = 'أداء جيد 👍';
        else if ($score > 0) $label = 'بطيء 🐢';
        
        return ['score' => $score, 'label' => $label];
    }

}
