<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Projects/TaskManager.php';
require_once __DIR__ . '/../src/Permissions/PermissionManager.php';
require_once __DIR__ . '/navigation.php';
require_once __DIR__ . '/components/headers/page-header.php';

AuthManager::requireAuth();

$user = AuthManager::getCurrentUser();

// Get workspace
$workspaceParam = $_GET['workspace'] ?? null;
$pdo = getPDO();
$company = null;

if ($workspaceParam) {
    $stmt = $pdo->prepare('
        SELECT c.* FROM companies c
        JOIN user_company_access uca ON c.id = uca.company_id
        WHERE uca.user_id = ? AND c.subdomain = ?
    ');
    $stmt->execute([$user['id'], $workspaceParam]);
    $company = $stmt->fetch(PDO::FETCH_ASSOC);
}

if (!$company && isset($_SESSION['current_company_id'])) {
    $stmt = $pdo->prepare('SELECT * FROM companies WHERE id = ?');
    $stmt->execute([$_SESSION['current_company_id']]);
    $company = $stmt->fetch(PDO::FETCH_ASSOC);
}

if (!$company) {
    $stmt = $pdo->prepare('
        SELECT c.* FROM companies c
        JOIN user_company_access uca ON c.id = uca.company_id
        WHERE uca.user_id = ?
        LIMIT 1
    ');
    $stmt->execute([$user['id']]);
    $company = $stmt->fetch(PDO::FETCH_ASSOC);
}

if (!$company) {
    header('Location: /workspace-plans.php');
    exit;
}

$_SESSION['current_company_id'] = $company['id'];
$_SESSION['current_company'] = $company;

$companyId = (int)$company['id'];
$userId = (int)$user['id'];

$workspaceSlugValue = $company['username'] ?? ($company['subdomain'] ?? ($companyId ? (string) $companyId : ''));
$workspaceQuery = $workspaceSlugValue !== '' ? '?workspace=' . urlencode((string) $workspaceSlugValue) : '';
$workspaceQueryAmp = $workspaceSlugValue !== '' ? '&workspace=' . urlencode((string) $workspaceSlugValue) : '';

$currentTheme = $_GET['theme'] ?? ($_SESSION['theme_preference'] ?? 'dark');
$currentTheme = in_array($currentTheme, ['dark', 'light'], true) ? $currentTheme : 'dark';
$workspaceDisplayName = $company['name'] ?? 'Workspace';

// Get view mode
$view = $_GET['view'] ?? 'month';
if (!in_array($view, ['day', 'week', 'month'], true)) {
    $view = 'month';
}

// Get current date
$currentDate = $_GET['date'] ?? date('Y-m-d');
$date = new DateTime($currentDate);

// Calculate date ranges based on view
switch ($view) {
    case 'day':
        $startDate = $date->format('Y-m-d');
        $endDate = $date->format('Y-m-d');
        break;
    case 'week':
        $date->modify('monday this week');
        $startDate = $date->format('Y-m-d');
        $date->modify('+6 days');
        $endDate = $date->format('Y-m-d');
        $date->modify('-6 days');
        break;
    case 'month':
    default:
        $date->modify('first day of this month');
        $startDate = $date->format('Y-m-d');
        $date->modify('last day of this month');
        $endDate = $date->format('Y-m-d');
        $date->modify('first day of this month');
        break;
}

// Get tasks for date range
$tasks = TaskManager::getTasksForCalendar($companyId, $startDate, $endDate);

// Group tasks by date
$tasksByDate = [];
foreach ($tasks as $task) {
    $taskDate = date('Y-m-d', strtotime($task['due_date']));
    if (!isset($tasksByDate[$taskDate])) {
        $tasksByDate[$taskDate] = [];
    }
    $tasksByDate[$taskDate][] = $task;
}

$pageTitle = 'Calendar';
?>
<!DOCTYPE html>
<html lang="en" data-theme="<?= htmlspecialchars($currentTheme) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($pageTitle) ?> · <?= htmlspecialchars($workspaceDisplayName) ?></title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script>
        (function() {
            var saved = localStorage.getItem('theme') || '<?= $currentTheme ?>';
            document.documentElement.setAttribute('data-theme', saved);
        })();
    </script>
</head>
<body class="projects-page projects-calendar-page">
<?php require_once __DIR__ . '/navigation.php'; renderNavigationNew('Projects', $currentTheme); ?>

<div class="main-container">
    <?php
    $actions = [
        [
            'label' => 'Back to projects',
            'url' => '/projects.php',
            'type' => 'secondary',
            'icon' => 'M10 19l-7-7m0 0l7-7m-7 7h18',
            'append_workspace' => true,
        ],
    ];
    renderPageHeader(
        breadcrumbs: [
            ['label' => 'Home', 'url' => '/index.php', 'icon' => 'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6'],
            ['label' => 'Projects', 'url' => '/projects.php', 'append_workspace' => true],
        ],
        currentPage: 'Calendar',
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

    <div class="dash-container">
        <div class="dash-section">
            <section class="card" style="margin-bottom: 0;">
                <p class="section-title">Projects</p>
                <h2 class="card-title" style="margin-top: 6px;">Project calendar</h2>
                <p class="card-subtitle">View tasks by due date.</p>
            </section>
        </div>

        <div class="dash-section">
            <div class="card" style="margin-bottom: 0;">
                <div class="card-actions" style="justify-content: space-between;">
                    <div class="card-actions">
                        <?php
                        $prevDate = clone $date;
                        $nextDate = clone $date;

                        switch ($view) {
                            case 'day':
                                $prevDate->modify('-1 day');
                                $nextDate->modify('+1 day');
                                break;
                            case 'week':
                                $prevDate->modify('-1 week');
                                $nextDate->modify('+1 week');
                                break;
                            case 'month':
                            default:
                                $prevDate->modify('-1 month');
                                $nextDate->modify('+1 month');
                                break;
                        }
                        ?>

                        <a class="btn-secondary" href="?<?= ltrim($workspaceQueryAmp, '&') ?>&view=<?= htmlspecialchars($view) ?>&date=<?= $prevDate->format('Y-m-d') ?>">
                            <i class="fas fa-chevron-left"></i>
                            <span>Prev</span>
                        </a>
                        <a class="btn-primary" href="?<?= ltrim($workspaceQueryAmp, '&') ?>&view=<?= htmlspecialchars($view) ?>">Today</a>
                        <a class="btn-secondary" href="?<?= ltrim($workspaceQueryAmp, '&') ?>&view=<?= htmlspecialchars($view) ?>&date=<?= $nextDate->format('Y-m-d') ?>">
                            <span>Next</span>
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    </div>

                    <div class="card-actions">
                        <span class="status-chip">
                            <?php
                            switch ($view) {
                                case 'day':
                                    echo $date->format('F j, Y');
                                    break;
                                case 'week':
                                    $weekEnd = clone $date;
                                    $weekEnd->modify('+6 days');
                                    echo $date->format('M j') . ' - ' . $weekEnd->format('M j, Y');
                                    break;
                                case 'month':
                                default:
                                    echo $date->format('F Y');
                                    break;
                            }
                            ?>
                        </span>

                        <a class="status-chip <?= $view === 'day' ? 'active' : 'inactive' ?>" href="?<?= ltrim($workspaceQueryAmp, '&') ?>&view=day&date=<?= htmlspecialchars($currentDate) ?>">Day</a>
                        <a class="status-chip <?= $view === 'week' ? 'active' : 'inactive' ?>" href="?<?= ltrim($workspaceQueryAmp, '&') ?>&view=week&date=<?= htmlspecialchars($currentDate) ?>">Week</a>
                        <a class="status-chip <?= $view === 'month' ? 'active' : 'inactive' ?>" href="?<?= ltrim($workspaceQueryAmp, '&') ?>&view=month&date=<?= htmlspecialchars($currentDate) ?>">Month</a>
                    </div>
                </div>
            </div>
        </div>

        <div class="dash-section">
            <div class="card" style="padding: 0; overflow: hidden;">

        <!-- Calendar View -->
        <?php if ($view === 'month'): ?>
            <!-- Month View -->
            <div class="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
                <!-- Day Headers -->
                <div class="grid grid-cols-7 border-b border-slate-200">
                    <?php foreach (['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] as $day): ?>
                        <div class="p-4 text-center text-sm font-semibold text-slate-600 border-r border-slate-200 last:border-r-0">
                            <?= $day ?>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <!-- Calendar Grid -->
                <div class="grid grid-cols-7">
                    <?php
                    $firstDay = clone $date;
                    $firstDay->modify('first day of this month');
                    $dayOfWeek = (int)$firstDay->format('w');
                    
                    // Add empty cells for days before month starts
                    for ($i = 0; $i < $dayOfWeek; $i++) {
                        echo '<div class="min-h-[120px] p-2 border-r border-b border-slate-200 bg-slate-50"></div>';
                    }
                    
                    // Add days of month
                    $lastDay = clone $date;
                    $lastDay->modify('last day of this month');
                    $daysInMonth = (int)$lastDay->format('d');
                    
                    for ($day = 1; $day <= $daysInMonth; $day++) {
                        $currentDay = clone $date;
                        $currentDay->setDate((int)$date->format('Y'), (int)$date->format('m'), $day);
                        $dateKey = $currentDay->format('Y-m-d');
                        $isToday = $dateKey === date('Y-m-d');
                        $dayTasks = $tasksByDate[$dateKey] ?? [];
                        ?>
                        <div class="min-h-[120px] p-2 border-r border-b border-slate-200 <?= $isToday ? 'bg-blue-50' : '' ?>">
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-sm font-semibold <?= $isToday ? 'text-blue-600' : 'text-slate-900' ?>">
                                    <?= $day ?>
                                </span>
                                <?php if (!empty($dayTasks)): ?>
                                    <span class="text-xs bg-slate-200 text-slate-700 px-2 py-0.5 rounded-full">
                                        <?= count($dayTasks) ?>
                                    </span>
                                <?php endif; ?>
                            </div>
                            <div class="space-y-1">
                                <?php foreach (array_slice($dayTasks, 0, 3) as $task): ?>
                                    <a href="/task.php?id=<?= $task['id'] ?>&project_id=<?= $task['project_id'] ?>&workspace=<?= urlencode($company['subdomain']) ?>"
                                       class="block text-xs p-1.5 rounded truncate hover:bg-white"
                                       style="background-color: <?= htmlspecialchars($task['status_color'] ?? '#64748B') ?>20; color: <?= htmlspecialchars($task['status_color'] ?? '#64748B') ?>">
                                        <?= htmlspecialchars($task['title']) ?>
                                    </a>
                                <?php endforeach; ?>
                                <?php if (count($dayTasks) > 3): ?>
                                    <p class="text-xs text-slate-500 pl-1.5">+<?= count($dayTasks) - 3 ?> more</p>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php
                    }
                    ?>
                </div>
            </div>
            
        <?php elseif ($view === 'week'): ?>
            <!-- Week View -->
            <div class="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
                <div class="grid grid-cols-7">
                    <?php
                    $weekDate = clone $date;
                    for ($i = 0; $i < 7; $i++) {
                        $dateKey = $weekDate->format('Y-m-d');
                        $isToday = $dateKey === date('Y-m-d');
                        $dayTasks = $tasksByDate[$dateKey] ?? [];
                        ?>
                        <div class="border-r border-slate-200 last:border-r-0">
                            <div class="p-4 border-b border-slate-200 <?= $isToday ? 'bg-blue-50' : '' ?>">
                                <div class="text-center">
                                    <p class="text-sm font-semibold text-slate-600"><?= $weekDate->format('D') ?></p>
                                    <p class="text-2xl font-bold <?= $isToday ? 'text-blue-600' : 'text-slate-900' ?>">
                                        <?= $weekDate->format('j') ?>
                                    </p>
                                </div>
                            </div>
                            <div class="p-4 space-y-2 min-h-[400px]">
                                <?php foreach ($dayTasks as $task): ?>
                                    <a href="/task.php?id=<?= $task['id'] ?>&project_id=<?= $task['project_id'] ?>&workspace=<?= urlencode($company['subdomain']) ?>"
                                       class="block p-3 rounded-lg border hover:shadow-md transition-shadow"
                                       style="border-color: <?= htmlspecialchars($task['status_color'] ?? '#64748B') ?>; background-color: <?= htmlspecialchars($task['status_color'] ?? '#64748B') ?>10">
                                        <p class="text-sm font-medium text-slate-900 mb-1"><?= htmlspecialchars($task['title']) ?></p>
                                        <p class="text-xs text-slate-600"><?= htmlspecialchars($task['project_name']) ?></p>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php
                        $weekDate->modify('+1 day');
                    }
                    ?>
                </div>
            </div>
            
        <?php else: ?>
            <!-- Day View -->
            <div class="bg-white rounded-xl border border-slate-200 shadow-sm p-6">
                <h2 class="text-xl font-bold text-slate-900 mb-4">
                    Tasks for <?= $date->format('l, F j, Y') ?>
                </h2>
                
                <?php
                $dateKey = $date->format('Y-m-d');
                $dayTasks = $tasksByDate[$dateKey] ?? [];
                ?>
                
                <?php if (empty($dayTasks)): ?>
                    <p class="text-slate-500 text-center py-12">No tasks scheduled for this day</p>
                <?php else: ?>
                    <div class="space-y-3">
                        <?php foreach ($dayTasks as $task): ?>
                            <a href="/task.php?id=<?= $task['id'] ?>&project_id=<?= $task['project_id'] ?>&workspace=<?= urlencode($company['subdomain']) ?>"
                               class="block p-4 rounded-lg border border-slate-200 hover:shadow-md transition-shadow">
                                <div class="flex items-start justify-between">
                                    <div class="flex-1">
                                        <h3 class="font-semibold text-slate-900 mb-1"><?= htmlspecialchars($task['title']) ?></h3>
                                        <p class="text-sm text-slate-600 mb-2"><?= htmlspecialchars($task['project_name']) ?></p>
                                        <div class="flex items-center gap-2">
                                            <span class="inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium" 
                                                  style="background-color: <?= htmlspecialchars($task['status_color'] ?? '#64748B') ?>20; color: <?= htmlspecialchars($task['status_color'] ?? '#64748B') ?>">
                                                <?= htmlspecialchars($task['status_name'] ?? 'No status') ?>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>
            </div>
        </div>
    </div>
</div>
</body>
</html>
