<?php
// Sāk sesiju
session_start();

// Pieslēgums datubāzei
include '../database/db.php';

// Pārbauda autorizāciju
if (!isset($_SESSION['user_id'])) {
    header("Location: ../users/login.php");
    exit();
}

$user_id = $_SESSION['user_id'];


$calendars_stmt = $pdo->prepare("
    SELECT DISTINCT c.id, c.name, c.user_id
    FROM calendars c
    WHERE c.user_id = ?

    UNION

    SELECT DISTINCT c.id, c.name, c.user_id
    FROM calendars c
    JOIN calendar_access ca ON c.id = ca.calendar_id
    WHERE ca.user_id = ?

    ORDER BY name ASC
");
$calendars_stmt->execute([$user_id, $user_id]);
$calendars = $calendars_stmt->fetchAll(PDO::FETCH_ASSOC);


// Nosaka aktīvo kalendāru
if (isset($_GET['calendar_id'])) {
    $current_calendar_id = $_GET['calendar_id'];
} elseif (!empty($calendars)) {
    $current_calendar_id = $calendars[0]['id'];
} else {
    $current_calendar_id = null;
}

// Ja nav norādīts skats, pāradresē uz šī mēneša skatu
if (!isset($_GET['view'])) {
    $today = new DateTime();
    $year = $today->format('Y');
    $month = $today->format('m');

    header(
        "Location: calendar.php?view=month&year=$year&month=$month" .
        ($current_calendar_id ? "&calendar_id=$current_calendar_id" : "")
    );
    exit();
}

// Iegūst uzdevumus izvēlētajam kalendāram
$tasks_stmt = $pdo->prepare("
    SELECT * FROM tasks 
    WHERE calendar_id = ?
    ORDER BY start_datetime ASC
");
$tasks_stmt->execute([$current_calendar_id]);
$task_list = $tasks_stmt->fetchAll(PDO::FETCH_ASSOC);

// Sagatavo datumus, kuros ir uzdevumi (kalendāra izcelšanai)
$highlightedDates = [];
foreach ($task_list as $task) {
    $start = new DateTime($task['start_datetime']);
    $end = new DateTime($task['end_datetime']);
    if ($end < $start) $end = clone $start;

    while ($start <= $end) {
        $highlightedDates[] = $start->format('Y-m-d');
        $start->modify('+1 day');
    }
}
$highlightedDates = array_unique($highlightedDates);

// Inicializē skatu un datumu
$view = $_GET['view'];
$current_date = new DateTime();

if (isset($_GET['year'])) $current_date->setDate($_GET['year'], $current_date->format('m'), 1);
if (isset($_GET['month'])) $current_date->setDate($current_date->format('Y'), $_GET['month'], 1);
if (isset($_GET['day'])) $current_date->setDate($current_date->format('Y'), $current_date->format('m'), $_GET['day']);
if (isset($_GET['year_change'])) $current_date->setDate($_GET['year_change'], $current_date->format('m'), 1);

// Atrod pašreizējā kalendāra nosaukumu
$current_calendar_name = 'No Calendar';
foreach ($calendars as $cal) {
    if ($cal['id'] == $current_calendar_id) {
        $current_calendar_name = $cal['name'];
        break;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calendar</title>
<link rel="stylesheet" href="../css/calendar.css">
<script src="../js/calendar.js"></script>
</head>
<body>
<nav>
    <ul>
        <li><a href="../dashboard.php">Dashboard</a></li>
        <li><a href="../calendar/calendar.php">Calendar</a></li>
        <li><a href="../tasks/tasks.php">All Tasks</a></li>
        <li><a href="../teams/teams.php">Teams</a></li>
        <li><a href="../friends/add_friend.php">Friends</a></li>
        <li><a href="../profile/profile.php">Profile</a></li>
        <li><a href="../users/logout.php">Logout</a></li>
    </ul>
</nav>

<div class="container">
    <main class="content">
        <header>
            <h2>Calendar</h2>
        </header>

        <!-- Skata pogas + Kalendāra atlasītājs + Atgriezties šodienas skatā -->
        <div class="view-buttons">
            <a href="calendar.php?view=year&year=<?= $current_date->format('Y') ?>&calendar_id=<?= $current_calendar_id ?>">Year View</a>
            <a href="calendar.php?view=month&year=<?= $current_date->format('Y') ?>&month=<?= $current_date->format('m') ?>&calendar_id=<?= $current_calendar_id ?>">Month View</a>
            <a href="calendar.php?view=day&year=<?= $current_date->format('Y') ?>&month=<?= $current_date->format('m') ?>&day=<?= $current_date->format('d') ?>&calendar_id=<?= $current_calendar_id ?>">Day View</a>

            <?php if (!empty($calendars)): ?>
            <div class="calendar-selector">
                <label for="calendar-select">Calendar:</label>
                <select id="calendar-select" onchange="changeCalendar(this.value)">
                    <?php foreach ($calendars as $cal): ?>
                        <option value="<?= $cal['id'] ?>" <?= ($cal['id'] == $current_calendar_id) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($cal['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>

            <?php 
            $today = new DateTime();
            ?>
            <a href="calendar.php?view=day&year=<?= $today->format('Y') ?>&month=<?= $today->format('m') ?>&day=<?= $today->format('d') ?>&calendar_id=<?= $current_calendar_id ?>" class="today-btn">Return to Today</a>
        </div>

        <!-- Gada skats -->
        <?php if ($view == 'year'): ?>
            <div class="month-nav">
                <form method="get" action="calendar.php">
                    <input type="hidden" name="view" value="year">
                    <input type="hidden" name="calendar_id" value="<?= $current_calendar_id ?>">
                    <button type="submit" name="year_change" value="<?= $current_date->format('Y') - 1 ?>">←</button>
                    <span><?= $current_date->format('Y') ?></span>
                    <button type="submit" name="year_change" value="<?= $current_date->format('Y') + 1 ?>">→</button>
                </form>
            </div>
            <div class="year-grid">
                <?php for ($month = 1; $month <= 12; $month++): ?>
                    <?php $current_date->setDate($current_date->format('Y'), $month, 1); ?>
                    <a href="calendar.php?view=month&year=<?= $current_date->format('Y') ?>&month=<?= $month ?>&calendar_id=<?= $current_calendar_id ?>" class="month-card">
                        <?= $current_date->format('F') ?>
                    </a>
                <?php endfor; ?>
            </div>
        <?php endif; ?>

        <!-- Mēneša skats -->
        <?php if ($view == 'month'): ?>
            <div class="month-nav">
                <form method="get" action="calendar.php">
                    <input type="hidden" name="view" value="month">
                    <input type="hidden" name="year" value="<?= $current_date->format('Y') ?>">
                    <input type="hidden" name="calendar_id" value="<?= $current_calendar_id ?>">
                    <button type="submit" name="month" value="<?= $current_date->format('m') - 1 ?>">←</button>
                    <span><?= $current_date->format('F Y') ?></span>
                    <button type="submit" name="month" value="<?= $current_date->format('m') + 1 ?>">→</button>
                </form>
            </div>
            <?php
            $days_in_month = $current_date->format('t');
            $start_day = $current_date->format('w');
            $start_day = ($start_day == 0) ? 6 : $start_day - 1;
            ?>
            <div class="calendar">
                <div class="calendar-header">Mon</div>
                <div class="calendar-header">Tue</div>
                <div class="calendar-header">Wed</div>
                <div class="calendar-header">Thu</div>
                <div class="calendar-header">Fri</div>
                <div class="calendar-header">Sat</div>
                <div class="calendar-header">Sun</div>
                <?php for ($i = 0; $i < $start_day; $i++): ?>
                    <div class="empty"></div>
                <?php endfor; ?>
                <?php for ($day = 1; $day <= $days_in_month; $day++):
                    $year = $current_date->format('Y');
                    $month = $current_date->format('m');
                    $day_str = str_pad($day, 2, '0', STR_PAD_LEFT);
                    $full_date = "$year-$month-$day_str";

                    $tasks_for_day = array_filter($task_list, function($task) use ($full_date) {
                        $start = date('Y-m-d', strtotime($task['start_datetime']));
                        $end = date('Y-m-d', strtotime($task['end_datetime']));
                        return ($full_date >= $start && $full_date <= $end);
                    });
                ?>
                    <div>
                        <a href="calendar.php?view=day&year=<?= $year ?>&month=<?= $month ?>&day=<?= $day ?>&calendar_id=<?= $current_calendar_id ?>">
                            <?= $day ?>
                        </a>
                        <?php if (!empty($tasks_for_day)): ?>
                            <div class="task-strips">
                                <?php foreach ($tasks_for_day as $task): ?>
                                    <a href="calendar.php?view=day&year=<?= $year ?>&month=<?= $month ?>&day=<?= $day ?>&calendar_id=<?= $current_calendar_id ?>#task-<?= $task['id'] ?>" 
                                       style="background-color: <?= htmlspecialchars($task['color']) ?>;" 
                                       title="<?= htmlspecialchars($task['title']) ?>"></a>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endfor; ?>
            </div>
        <?php endif; ?>

        <!-- Dienas skats -->
        <?php if ($view == 'day'): ?>
            <div class="month-nav">
                <form method="get" action="calendar.php">
                    <input type="hidden" name="view" value="day">
                    <input type="hidden" name="year" value="<?= $current_date->format('Y') ?>">
                    <input type="hidden" name="month" value="<?= $current_date->format('m') ?>">
                    <input type="hidden" name="calendar_id" value="<?= $current_calendar_id ?>">
                    <button type="submit" name="day" value="<?= $current_date->format('d') - 1 ?>">←</button>
                    <span><?= $current_date->format('l, F j, Y') ?></span>
                    <button type="submit" name="day" value="<?= $current_date->format('d') + 1 ?>">→</button>
                </form>
            </div>
            <div class="day-content">
                <?php 
                $current_day_str = $current_date->format('Y-m-d');
                $has_tasks = false;
                foreach ($task_list as $task):
                    $task_start_date = date('Y-m-d', strtotime($task['start_datetime']));
                    $task_end_date = date('Y-m-d', strtotime($task['end_datetime']));
                    if ($current_day_str >= $task_start_date && $current_day_str <= $task_end_date):
                        $has_tasks = true;
                ?>
                    <div class="task-item" style="border-left-color: <?= htmlspecialchars($task['color']) ?>;">
                        <strong><?= htmlspecialchars($task['title']) ?></strong><br>
                        <?= date('H:i', strtotime($task['start_datetime'])) ?> - <?= date('H:i', strtotime($task['end_datetime'])) ?><br>
                        <em><?= nl2br(htmlspecialchars($task['description'])) ?></em>
                        <a href="calendar_edit.php?task_id=<?= $task['id'] ?>" class="edit-btn">Edit</a>
                    </div>
                <?php 
                    endif; 
                endforeach; 
                if (!$has_tasks):
                ?>
                    <p class="no-tasks">No tasks for this day</p>
                <?php endif; ?>
            </div>
        <?php endif; ?>

    </main>
</div>
</body>
</html>