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

class TodoController extends \Core\Controller {

    public function index() {
        $model = $this->model('Todo/Models/TodoModel');
        
        $targetDate = isset($_GET['date']) ? sanitize_input($_GET['date']) : date('Y-m-d');
        if (!preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $targetDate)) {
            $targetDate = date('Y-m-d');
        }

        // INTELLIGENCE ENGINE: Auto Prioritize
        $model->autoPrioritizeTasks($this->userId, $targetDate);

        // Fetch unified categories
        $customCategories = $model->getCategories($this->userId);

        $allTasks = $model->getDashboardTasks($this->userId, $targetDate);
        $overdueTasks = $model->getOverdueTasks($this->userId);
        
        $momentum = $model->calculateMomentumScore($this->userId, $targetDate);

        $focusTasks = [];
        $regularTasks = [];
        
        $totalSystemTasks = 0;
        $completedSystemTasks = 0;
        
        $todayStr = date('Y-m-d');

        foreach ($allTasks as $task) {
            $task->is_overdue = ($task->target_date < $todayStr && !in_array($task->status, ['done', 'skipped']));
            // If the model schema upgrade failed, we catch it gracefully
            if (isset($task->parent_id) && $task->parent_id > 0) continue; // Skip subtasks from main view

            // Done focus tasks go to regular (completed section), not focus zone
            if ($task->is_daily_focus && $task->status !== 'done') {
                $focusTasks[] = $task;
            } else {
                $regularTasks[] = $task;
            }
            
            $totalSystemTasks++;
            if ($task->status === 'done') {
                $completedSystemTasks++;
            }
        }

        $completionPercentage = $totalSystemTasks > 0 ? round(($completedSystemTasks / $totalSystemTasks) * 100) : 0;

        $this->view('Todo/Views/dashboard', [
            'title' => "To-Do Intelligence",
            'targetDate' => $targetDate,
            'focusTasks' => $focusTasks,
            'regularTasks' => $regularTasks,
            'overdueTasks' => $overdueTasks,
            'customCategories' => $customCategories,
            'momentumScore' => $momentum,
            'totalTasks' => $totalSystemTasks,
            'completedTasks' => $completedSystemTasks,
            'completionPercentage' => $completionPercentage
        ]);
    }

    public function focus() {
        $model = $this->model('Todo/Models/TodoModel');
        $todayStr = date('Y-m-d');
        $allTasks = $model->getDashboardTasks($this->userId, $todayStr);
        $focusTasks = array_filter($allTasks, fn($t) => $t->is_daily_focus && $t->status !== 'done');
        
        $this->view('Todo/Views/focus', [
            'title' => "Zen Mode - OTIS",
            'focusTasks' => array_values($focusTasks)
        ], false);
    }

    public function storeTask() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token'] ?? '');
            $model = $this->model('Todo/Models/TodoModel');
            
            $targetDate = get_secure_post('target_date');
            if (empty($targetDate)) $targetDate = date('Y-m-d');

            $data = [
                'title' => get_secure_post('title'),
                'description' => get_secure_post('description'),
                'category' => get_secure_post('category'),
                'priority' => get_secure_post('priority') ?: 'medium',
                'estimated_time' => (int)get_secure_post('estimated_time'),
                'energy_level' => get_secure_post('energy_level') ?: 'medium',
                'target_date' => $targetDate,
                'due_date' => get_secure_post('due_date'),
                'parent_id' => get_secure_post('parent_id') ?: null,
                'add_to_calendar' => isset($_POST['add_to_calendar']) ? 1 : 0
            ];
            
            $model->addTask($this->userId, $data);
            
            set_flash_message('todo', 'تمت الإضافة بنجاح أيتها القوة الدافعة!', 'success');
            redirect("/todo/index?date={$targetDate}");
        }
    }

    // AJAX Endpoint
    public function updateStatus() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = json_decode(file_get_contents('php://input'), true);
            verify_csrf_token($data['csrf_token'] ?? ''); // Security

            $taskId = $data['task_id'] ?? null;
            $status = $data['status'] ?? null;
            $targetDate = $data['target_date'] ?? date('Y-m-d');
            
            if($taskId && $status) {
                $model = $this->model('Todo/Models/TodoModel');
                $model->updateTaskStatus($taskId, $this->userId, $status);
                
                // Recalculate momentum
                $allTasks = $model->getDashboardTasks($this->userId, $targetDate);
                $momentum = $model->calculateMomentumScore($this->userId, $targetDate);
                
                $total = count($allTasks);
                $done = count(array_filter($allTasks, fn($t) => $t->status === 'done'));
                $pct = $total > 0 ? round(($done / $total) * 100) : 0;
                
                echo json_encode(['success' => true, 'total' => $total, 'done' => $done, 'percentage' => $pct, 'momentum' => $momentum]);
            } else {
                echo json_encode(['success' => false, 'message' => 'بيانات مفقودة']);
            }
            exit;
        }
    }

    // AJAX Endpoint
    public function toggleFocus() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = json_decode(file_get_contents('php://input'), true);
            verify_csrf_token($data['csrf_token'] ?? ''); // Security

            $taskId = $data['task_id'] ?? null;
            $isFocus = $data['is_focus'] ?? 0;
            
            if($taskId) {
                $model = $this->model('Todo/Models/TodoModel');
                $model->toggleDailyFocus($taskId, $this->userId, $isFocus);
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'message' => 'بيانات مفقودة']);
            }
            exit;
        }
    }

    // AJAX Endpoint
    public function reschedule() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = json_decode(file_get_contents('php://input'), true);
            verify_csrf_token($data['csrf_token'] ?? ''); // Security

            $taskId = $data['task_id'] ?? null;
            $newDate = $data['new_date'] ?? null;
            
            if($taskId && $newDate) {
                $model = $this->model('Todo/Models/TodoModel');
                $model->rescheduleTask($taskId, $this->userId, $newDate);
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'message' => 'بيانات مفقودة']);
            }
            exit;
        }
    }

    // AJAX Endpoint
    public function delete() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = json_decode(file_get_contents('php://input'), true);
            verify_csrf_token($data['csrf_token'] ?? ''); // Security

            $taskId = $data['task_id'] ?? null;
            
            if($taskId) {
                $model = $this->model('Todo/Models/TodoModel');
                $model->softDeleteTask($taskId, $this->userId);
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'message' => 'بيانات مفقودة']);
            }
            exit;
        }
    }

    // AJAX Endpoint
    public function saveFocusSession() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = json_decode(file_get_contents('php://input'), true);
            $taskName = $data['task_name'] ?? 'جلسة عامة';
            $duration = $data['duration'] ?? 25;
            
            $db = \Core\Database::getInstance();
            $db->query("INSERT INTO focus_sessions (user_id, task_name, duration_minutes) VALUES (?, ?, ?)", [$this->userId, $taskName, $duration]);
            
            // Reward XP
            require_once __DIR__ . '/../../../../core/Services/GamificationEngine.php';
            \Core\Services\GamificationEngine::getInstance()->onEvent('task_completed', $this->userId);
            
            echo json_encode(['success' => true]);
            exit;
        }
    }

    // AJAX Endpoint — Edit Task Fields
    public function updateTask() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = json_decode(file_get_contents('php://input'), true);
            verify_csrf_token($data['csrf_token'] ?? '');

            $taskId = (int)($data['task_id'] ?? 0);
            $title  = trim($data['title'] ?? '');

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

            $model = $this->model('Todo/Models/TodoModel');
            $model->updateTaskFields($taskId, $this->userId, [
                'title'          => $title,
                'category'       => $data['category']       ?? null,
                'priority'       => $data['priority']       ?? null,
                'estimated_time' => isset($data['estimated_time']) ? (int)$data['estimated_time'] : null,
                'description'    => $data['description']    ?? null,
            ]);

            echo json_encode(['success' => true]);
            exit;
        }
    }

    // AJAX Endpoint — Update Category Name/Color
    public function updateCategory() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $data = json_decode(file_get_contents('php://input'), true);
            verify_csrf_token($data['csrf_token'] ?? '');

            $catId = (int)($data['cat_id'] ?? 0);
            $name  = trim($data['name'] ?? '');

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

            $model = $this->model('Todo/Models/TodoModel');
            $model->updateCategoryName($catId, $this->userId, $name);

            echo json_encode(['success' => true]);
            exit;
        }
    }

}
