<?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

            if ($task->is_daily_focus) {
                $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 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;
        }
    }

}
