<?php
session_start();
include 'database/db.php';


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

$user_id = $_SESSION['user_id'];

/*Iegūstam visus lietotāja kalendārus*/
$own_calendars_stmt = $pdo->prepare("
    SELECT * FROM calendars WHERE user_id = ? ORDER BY name ASC
");
$own_calendars_stmt->execute([$user_id]);
$own_calendars = $own_calendars_stmt->fetchAll(PDO::FETCH_ASSOC);

$shared_calendars_stmt = $pdo->prepare("
    SELECT c.*, u.name AS owner_name
    FROM calendars c
    JOIN calendar_access ca ON c.id = ca.calendar_id
    JOIN users u ON c.user_id = u.id
    WHERE ca.user_id = ?
    ORDER BY c.name ASC
");
$shared_calendars_stmt->execute([$user_id]);
$shared_calendars = $shared_calendars_stmt->fetchAll(PDO::FETCH_ASSOC);

/*Iegūstam draugus, kuriem ir pieeja kalendāriem*/

$friends_stmt = $pdo->prepare("
    SELECT 
        f.id,
        u.name AS friend_name,
        f.can_edit,
        f.calendar_id
    FROM friends f
    LEFT JOIN users u ON f.friend_id = u.id
    WHERE f.user_id = ?
");
$friends_stmt->execute([$user_id]);
$friends = $friends_stmt->fetchAll(PDO::FETCH_ASSOC);

/*Iegūstam tuvākos atgādinājumus
 * - tikai nākamajām 7 dienām
 * - max 8 ieraksti*/


$reminders_stmt = $pdo->prepare("
    SELECT 
        r.id,
        r.reminder_time,
        r.is_sent,
        t.title,
        t.start_datetime,
        t.color,
        c.name AS calendar_name
    FROM reminders r
    JOIN tasks t ON r.task_id = t.id
    LEFT JOIN calendars c ON t.calendar_id = c.id
    WHERE 
        r.user_id = ?
        AND r.reminder_time >= NOW()
        AND r.reminder_time <= DATE_ADD(NOW(), INTERVAL 7 DAY)
    GROUP BY r.task_id          -- <-- tikai 1 reminder uz task
    ORDER BY r.reminder_time ASC
    LIMIT 8
");
$reminders_stmt->execute([$user_id]);
$upcoming_reminders = $reminders_stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard - Work Planner</title>

<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/modal.css">
<link rel="stylesheet" href="css/dashboard.css">

</head>
<body>

<!-- NAVIGĀCIJA -->
<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>

<main>
<h2>Dashboard</h2>

<div class="dashboard-grid">

    <div class="dashboard-left">
        <!-- KALENDĀRU SARAKSTS -->
        <div class="calendar-list">

            <h3>Your Calendars</h3>
            <a href="calendar/calendar_create.php" class="add-calendar-btn">
                + Add New Calendar
            </a>

            <?php if ($own_calendars): ?>
                <ul>
                    <?php foreach ($own_calendars as $cal): ?>
                        <li>
                            <strong><?= htmlspecialchars($cal['name']) ?></strong>
                            <div class="item-actions">
                                <a href="#" onclick="openEditModal(<?= $cal['id'] ?>); return false;">Edit</a>
                                <a href="calendar/calendar_delete.php?calendar_id=<?= $cal['id'] ?>"
                                   class="delete-link"
                                   onclick="return confirm('Are you sure you want to delete this calendar?');">
                                    Delete
                                </a>
                            </div>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php else: ?>
                <p class="empty-text">No calendars yet. Create your first calendar!</p>
            <?php endif; ?>

            <h3 style="margin-top: 24px;">Shared Calendars</h3>

            <?php if ($shared_calendars): ?>
                <ul>
                    <?php foreach ($shared_calendars as $cal): ?>
                        <li>
                            <strong><?= htmlspecialchars($cal['name']) ?></strong>
                            <span class="owner-badge">by <?= htmlspecialchars($cal['owner_name']) ?></span>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php else: ?>
                <p class="empty-text">No shared calendars yet.</p>
            <?php endif; ?>

        </div>
    </div>

    <div class="dashboard-right">
        <!-- ATGĀDINĀJUMI -->
        <div class="reminders-section">
            <h3>Reminders</h3>
            <p class="hint">Your reminders for the next 7 days</p>

            <?php if (count($upcoming_reminders) > 0): ?>
                <div class="reminders-list">
                    <?php foreach ($upcoming_reminders as $reminder): ?>
                        <?php
                        $reminder_dt = new DateTime($reminder['reminder_time']);
                        $task_dt     = new DateTime($reminder['start_datetime']);
                        $now         = new DateTime();
                        $diff        = $now->diff($reminder_dt);

                        if ($reminder_dt > $now) {
                            if ($diff->days > 0) {
                                $time_until = $diff->days . ' day' . ($diff->days > 1 ? 's' : '');
                            } elseif ($diff->h > 0) {
                                $time_until = $diff->h . ' hour' . ($diff->h > 1 ? 's' : '');
                            } else {
                                $time_until = $diff->i . ' min';
                            }
                        } else {
                            $time_until = 'Now';
                        }
                        ?>
                        <div class="reminder-card"
                             style="border-left-color: <?= htmlspecialchars($reminder['color']) ?>;">
                            <div class="reminder-icon">⏰</div>
                            <div class="reminder-content">
                                <strong><?= htmlspecialchars($reminder['title']) ?></strong>
                                <div class="reminder-calendar">
                                    <?= htmlspecialchars($reminder['calendar_name'] ?? 'No Calendar') ?>
                                </div>
                                <div class="reminder-time">
                                    Reminder in:
                                    <span class="time-badge"><?= $time_until ?></span>
                                </div>
                                <div class="reminder-details">
                                    Task starts: <?= $task_dt->format('M d, Y - H:i') ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <a href="tasks/tasks.php" class="view-all-link">
                    View All Tasks →
                </a>

            <?php else: ?>
                <div class="no-reminders">
                    <p>No upcoming reminders</p>
                    <small>Reminders are created automatically when you add tasks</small>
                    <a href="tasks/tasks.php" class="btn-add-task-link">
                        + Add Your First Task
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </div>

</div>
</main>

<!-- KALENDĀRA REDIĢĒŠANAS MODĀLIS -->
<div id="editModal" class="modal">
    <div class="modal-content">

        <div class="modal-header">
            <h2>Edit Calendar</h2>
            <button class="close-btn" onclick="closeEditModal()">&times;</button>
        </div>

        <!-- Ziņojumi (success / error) -->
        <div id="modalMessage" class="message"></div>

        <form id="editCalendarForm">
            <input type="hidden" id="calendar_id" name="calendar_id">

            <div class="form-group">
                <label for="calendar_name">Calendar Name</label>
                <input type="text" id="calendar_name" name="name" required>
            </div>

            <div class="section-divider"></div>

            <!-- TABI -->
            <div class="tabs">
                <button type="button" class="tab active" onclick="switchTab('shared')">
                    Currently Shared (0)
                </button>
                <button type="button" class="tab" onclick="switchTab('friends')">
                    Add Friends
                </button>
                <button type="button" class="tab" onclick="switchTab('teams')">
                    Add Teams
                </button>
            </div>

            <!-- Pašreizējās pieejas -->
            <div id="tab-shared" class="tab-content active">
                <div class="section-title">People with Access</div>
                <div id="sharedList"></div>
            </div>

            <!-- Draugu pievienošana -->
            <div id="tab-friends" class="tab-content">
                <div class="section-title">Available Friends</div>
                <div id="availableFriendsList"></div>
            </div>

            <!-- Komandu pievienošana -->
            <div id="tab-teams" class="tab-content">
                <div class="section-title">Your Teams</div>
                <div id="availableTeamsList"></div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn-cancel" onclick="closeEditModal()">
                    Close
                </button>
                <button type="submit" class="btn-save">
                    Save Calendar
                </button>
            </div>
        </form>
    </div>
</div>

<script src="js/dashboard.js"></script>
</body>
</html>