<?php
class TaskController extends Controller{
    
    public function index() {
        session_start();
    
        if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
            header("Location: " . BASE_URL . "/LoginController/logout");
            exit;
        }
    
        $taskModel = $this->model('Task');
    
        $status = $_GET['status'] ?? null;

        if ($status && in_array($status, ['pending', 'completed', 'overdue'])) {
            $tasks = $taskModel->getTasksByDerivedStatus($status);
        } else {
            $tasks = $taskModel->getAllTasks();
        }
    
        $stats = $taskModel->getTaskCountsByStatus();
    
        $this->view('tasks/index', [
            'tasks' => $tasks,
            'statusFilter' => $status,
            'stats' => $stats
        ]);
    }



    public function contact($contactId)
    {
        session_start();
        if (!isset($_SESSION['user_id'])) {
            header("Location: " . BASE_URL . "/LoginController/index");
            exit;
        }

        $taskModel = $this->model('Task');
        $contactModel = $this->model('Contact');

        $contact = $contactModel->getContactById($contactId);
        $tasks = $taskModel->getTasksByContactId($contactId);

        $this->view('tasks/contact', [
            'contact' => $contact,
            'tasks' => $tasks
        ]);
    }

    public function add($contactId)
    {
        session_start();
        if (!isset($_SESSION['user_id'])) {
            header("Location: " . BASE_URL . "/LoginController/index");
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $taskModel = $this->model('Task');
            $data = [
                'contact_id' => $contactId,
                'user_id' => $_SESSION['user_id'],
                'title' => trim($_POST['title']),
                'due_date' => $_POST['due_date'],
                'status' => $_POST['status'] ?? 'pending'
            ];

            $taskModel->addTask($data);
            header("Location: " . BASE_URL . "/TaskController/contact/$contactId");
            exit;
        }
    }

    public function edit($id)
    {
        session_start();
        if (!isset($_SESSION['user_id'])) {
            header("Location: " . BASE_URL . "/LoginController/index");
            exit;
        }

        $taskModel = $this->model('Task');
        $task = $taskModel->getTaskById($id);

        if (!$task || $_SESSION['user_id'] != $task['user_id']) {
            header("Location: " . BASE_URL . "/TaskController/contact/" . $task['contact_id']);
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $updatedData = [
                'title' => trim($_POST['title']),
                'due_date' => $_POST['due_date'],
                'status' => $_POST['status']
            ];

            $taskModel->updateTask($id, $_SESSION['user_id'], $updatedData);
            header("Location: " . BASE_URL . "/TaskController/contact/" . $task['contact_id']);
            exit;
        }

        $this->view('tasks/edit', ['task' => $task]);
    }

    public function delete($id)
    {
        session_start();
        if (!isset($_SESSION['user_id'])) {
            header("Location: " . BASE_URL . "/LoginController/index");
            exit;
        }

        $taskModel = $this->model('Task');
        $task = $taskModel->getTaskById($id);

        if ($task && $_SESSION['user_id'] == $task['user_id']) {
            $taskModel->deleteTask($id, $_SESSION['user_id']);
        }

        header("Location: " . BASE_URL . "/TaskController/contact/" . $task['contact_id']);
        exit;
    }
    
    public function reminders($filter = null) {
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header("Location: " . BASE_URL . "/LoginController/index");
        exit;
    }

    $userId = $_SESSION['user_id'];
    $taskModel = $this->model('Task');

    switch ($filter) {
        case 'pending':
            $tasks = $taskModel->getTasksByStatus($userId, 'pending');
            $title = "Pending Tasks";
            break;
        case 'today':
            $tasks = $taskModel->getTasksDueToday($userId);
            $title = "Tasks Due Today";
            break;
        case 'week':
            $tasks = $taskModel->getTasksDueThisWeek($userId);
            $title = "Tasks Due This Week";
            break;
        default:
            $tasks = [];
            $title = "Task Reminders";
    }

    $this->view('tasks/reminders', [
        'tasks' => $tasks,
        'title' => $title
    ]);
}

    public function adminEdit($id)
{
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header("Location: " . BASE_URL . "/LoginController/index");
        exit;
    }

    $taskModel = $this->model('Task');
    $task = $taskModel->getTaskById($id);

    // ✅ Only allow if admin or task owner
    if (!$task || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_id'] != $task['user_id'])) {
        header("Location: " . BASE_URL . "/TaskController/index");
        exit;
    }

    // ✅ Handle form submission
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $updatedData = [
            'title' => trim($_POST['title']),
            'due_date' => $_POST['due_date'],
            'status' => $_POST['status']
        ];

        $taskModel->adminUpdateTask($id, $_SESSION['user_id'], $updatedData);
        header("Location: " . BASE_URL . "/TaskController/adminedit/$id");
        exit;
    }

    // ✅ Get all logs
    $logs = $taskModel->getLogsByTaskId($id);

    // ✅ Pagination logic
    $logsPerPage = 10;
    $totalLogs = count($logs);
    $totalPages = ceil($totalLogs / $logsPerPage);
    $currentPage = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
    $currentPage = min($currentPage, $totalPages);
    $startIndex = ($currentPage - 1) * $logsPerPage;
    $paginatedLogs = array_slice($logs, $startIndex, $logsPerPage);
    
    $reminderLogs = $taskModel->getReminderLogsByTask($id);

    // ✅ Pass paginated logs + pagination info to view
    $this->view('tasks/adminedit', [
        'task' => $task,
        'logs' => $paginatedLogs,
        'currentPage' => $currentPage,
        'totalPages' => $totalPages,
        'reminderLogs' => $reminderLogs
    ]);
}




}
