<?php
// ============================================================
//  admin/calendar.php — Tasks + SA public holidays calendar
// ============================================================
//
//  Month-view calendar showing:
//    - All tasks visible to the user (with due dates)
//    - South African public holidays
//    - Weekends (tinted)
//
//  Filter behaviour mirrors tasks.php tabs:
//    scope=mine     → tasks assigned to me + ones I created
//    scope=all      → all tasks (super admin only)
//
//  Tasks without a due date don't show on the calendar — they
//  still appear in the tasks list page.
// ============================================================

$page_title = 'Calendar';
require __DIR__ . '/_guard.php';
require_once __DIR__ . '/../includes/calendar.php';

$me       = auth_admin_user();
$is_super = ($me['role'] === 'super_admin');

// Year/month from URL
$year  = (int)($_GET['y'] ?? date('Y'));
$month = (int)($_GET['m'] ?? date('n'));
if ($year < 2000 || $year > 2100) $year = (int)date('Y');
if ($month < 1 || $month > 12)    $month = (int)date('n');

// Scope toggle
$scope = $_GET['scope'] ?? 'mine';
if (!$is_super && $scope === 'all') $scope = 'mine';

// Compute month bounds (extended by ±7 days so we catch out-of-month
// days that show in the leading/trailing rows of the grid)
$first_of_month = sprintf('%04d-%02d-01', $year, $month);
$range_start = date('Y-m-d', strtotime("-7 days", strtotime($first_of_month)));
$range_end   = date('Y-m-d', strtotime("+7 days", strtotime("last day of $first_of_month")));

// Load tasks in scope
$where  = ['t.due_date IS NOT NULL', 't.due_date BETWEEN :s AND :e'];
$params = ['s' => $range_start, 'e' => $range_end];

switch ($scope) {
    case 'all':
        // No further restriction (super only)
        break;
    case 'mine':
    default:
        $where[] = '(t.assigned_to = :me1 OR (t.assigned_to IS NULL AND t.created_by = :me2))';
        $params['me1'] = $me['id'];
        $params['me2'] = $me['id'];
        break;
}

$tasks = db_all(
    "SELECT t.id, t.title, t.status, t.priority, t.due_date,
            t.assigned_to, t.created_by
       FROM admin_tasks t
      WHERE " . implode(' AND ', $where) . "
      ORDER BY FIELD(t.priority,'urgent','high','normal','low'), t.due_date, t.id",
    $params
);

// Build events array indexed by date
$events = [];
$today  = date('Y-m-d');
foreach ($tasks as $t) {
    $cls = 'task-' . $t['status'];
    if ($t['status'] === 'open' || $t['status'] === 'in_progress') {
        if ($t['due_date'] < $today) {
            $cls = 'task-overdue';
        }
    }
    $events[$t['due_date']][] = [
        'label' => $t['title'],
        'url'   => 'task-edit.php?id=' . (int)$t['id'],
        'class' => $cls,
    ];
}

// Counts for scope toggle
$mine_total = (int)db_value(
    "SELECT COUNT(*) FROM admin_tasks
      WHERE due_date IS NOT NULL
        AND due_date BETWEEN :s AND :e
        AND (assigned_to = :me1 OR (assigned_to IS NULL AND created_by = :me2))",
    ['s' => $range_start, 'e' => $range_end, 'me1' => $me['id'], 'me2' => $me['id']]
);
$all_total = (int)db_value(
    "SELECT COUNT(*) FROM admin_tasks
      WHERE due_date IS NOT NULL AND due_date BETWEEN :s AND :e",
    ['s' => $range_start, 'e' => $range_end]
);
?>

<style>
<?= calendar_css() ?>

/* Page-specific layout */
.cal-page-bar{
    display:flex;justify-content:space-between;align-items:center;
    margin-bottom:1rem;flex-wrap:wrap;gap:1rem;
}
.cal-scope{display:flex;gap:.4rem;}
.cal-scope a{
    padding:.4rem .9rem;border-radius:999px;border:1px solid var(--line);
    background:#fff;color:var(--ink);text-decoration:none;font-size:.85rem;
}
.cal-scope a.on{background:var(--brand-primary);color:#fff;border-color:var(--brand-primary);}
.cal-scope .ct{font-size:.7rem;background:rgba(0,0,0,.1);padding:.05em .45em;border-radius:999px;margin-left:.3rem;}
.cal-scope a.on .ct{background:rgba(255,255,255,.25);}

.cal-legend{
    margin-top:1rem;padding:.75rem 1rem;background:var(--surface-alt);
    border-radius:6px;font-size:.78rem;color:var(--ink-muted);
    display:flex;gap:1rem;flex-wrap:wrap;align-items:center;
}
.cal-legend-key{display:inline-flex;align-items:center;gap:.4rem;}
.cal-legend-pill{
    display:inline-block;width:14px;height:14px;border-radius:3px;
}
</style>

<section class="section"><div class="container">

<div class="cal-page-bar">
    <h1 style="margin:0;">Calendar</h1>

    <div class="cal-scope">
        <a href="?scope=mine&y=<?= $year ?>&m=<?= $month ?>"
           class="<?= $scope==='mine'?'on':'' ?>">
            My tasks <span class="ct"><?= $mine_total ?></span>
        </a>
        <?php if ($is_super): ?>
            <a href="?scope=all&y=<?= $year ?>&m=<?= $month ?>"
               class="<?= $scope==='all'?'on':'' ?>">
                All tasks <span class="ct"><?= $all_total ?></span>
            </a>
        <?php endif; ?>
    </div>
</div>

<?= calendar_render($year, $month, $events, ['base_url' => 'calendar.php?scope=' . urlencode($scope)]) ?>

<div class="cal-legend">
    <span class="cal-legend-key">
        <span class="cal-legend-pill" style="background:#dbeafe;"></span> Open
    </span>
    <span class="cal-legend-key">
        <span class="cal-legend-pill" style="background:#fef3c7;"></span> In progress
    </span>
    <span class="cal-legend-key">
        <span class="cal-legend-pill" style="background:#dcfce7;"></span> Done
    </span>
    <span class="cal-legend-key">
        <span class="cal-legend-pill" style="background:#fee2e2;"></span> Overdue
    </span>
    <span class="cal-legend-key">
        <span class="cal-legend-pill" style="background:#fed7aa;"></span> SA public holiday
    </span>
    <span class="cal-legend-key">
        <span class="cal-legend-pill" style="background:#f9f7f1;border:1px solid #e5e7eb;"></span> Weekend
    </span>
</div>

<p style="margin-top:1rem;font-size:.82rem;color:var(--ink-muted);">
    Tasks without a due date don't appear on the calendar.
    <a href="tasks.php">View all tasks →</a>
</p>

</div></section>

<?php require __DIR__ . '/_footer.php'; ?>