<?php
// app/controllers/CalendarController.php

$appRoot = __DIR__ . '/..';
require_once $appRoot . '/models/Task.php';

class CalendarController {
    private $pdo;
    private $taskModel;

    public function __construct($pdo) {
        $this->pdo = $pdo;
        $this->taskModel = new Task($pdo);
    }

    public function index() {
        // 1. Determine Month & Year (Default to current)
        $month = isset($_GET['month']) ? (int)$_GET['month'] : date('m');
        $year = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');

        // 2. Navigation Logic (Next/Prev Month)
        $prevMonth = $month - 1;
        $prevYear = $year;
        if ($prevMonth < 1) { $prevMonth = 12; $prevYear--; }

        $nextMonth = $month + 1;
        $nextYear = $year;
        if ($nextMonth > 12) { $nextMonth = 1; $nextYear++; }

        // 3. Calendar Math
        $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
        $firstDayName = date('l', mktime(0, 0, 0, $month, 1, $year)); // e.g., "Monday"
        $dayOffset = date('N', mktime(0, 0, 0, $month, 1, $year)) - 1; // 0 (Mon) to 6 (Sun)

        // 4. Fetch Tasks
        $allTasks = $this->taskModel->getAll();
        
        // Group tasks by Date (e.g., "2023-10-25" => [Task1, Task2])
        $calendarTasks = [];
        foreach ($allTasks as $task) {
            $dateKey = date('Y-m-d', strtotime($task['due_date']));
            $calendarTasks[$dateKey][] = $task;
        }

        $pageTitle = "Content Calendar";
        $viewsPath = __DIR__ . '/../views';
        
        require_once $viewsPath . '/layouts/header.php';
        require_once $viewsPath . '/calendar/index.php';
        require_once $viewsPath . '/layouts/footer.php';
    }
}
?>