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

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

$user_id = $_SESSION['user_id'];
$search = $_GET['search'] ?? '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['title'])) {

    $title          = $_POST['title'];
    $description    = $_POST['description'] ?? '';
    $start_datetime = $_POST['start_datetime'];
    $end_datetime   = $_POST['end_datetime'];

    if (empty($end_datetime)) {
        $end_datetime = $start_datetime;
    }

    $calendar_id = $_POST['calendar_id'];
    $color       = $_POST['color'];

    $owner_check = $pdo->prepare("SELECT id FROM calendars WHERE id = ? AND user_id = ?");
    $owner_check->execute([$calendar_id, $user_id]);
    $is_owner = $owner_check->fetch();

    if (!$is_owner) {
        $access_check = $pdo->prepare("
            SELECT ca.can_edit 
            FROM calendar_access ca
            WHERE ca.calendar_id = ? AND ca.user_id = ? AND ca.can_edit = 1
        ");
        $access_check->execute([$calendar_id, $user_id]);
        $has_edit_access = $access_check->fetch();

        if (!$has_edit_access) {
            header("Location: tasks.php?error=no_permission");
            exit();
        }
    }

    $stmt = $pdo->prepare("
        INSERT INTO tasks 
        (user_id, title, description, start_datetime, end_datetime, calendar_id, color) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([$user_id, $title, $description, $start_datetime, $end_datetime, $calendar_id, $color]);

    $task_id = $pdo->lastInsertId();

    $participants_stmt = $pdo->prepare("
        SELECT c.user_id
        FROM calendars c
        WHERE c.id = ?

        UNION

        SELECT ca.user_id
        FROM calendar_access ca
        WHERE ca.calendar_id = ?
    ");
    $participants_stmt->execute([$calendar_id, $calendar_id]);
    $participants = $participants_stmt->fetchAll(PDO::FETCH_COLUMN);

    $start_time = new DateTime($start_datetime);

    foreach ($participants as $participant_id) {

        $prefs_stmt = $pdo->prepare("
            SELECT *
            FROM user_notification_preferences
            WHERE user_id = ?
        ");
        $prefs_stmt->execute([$participant_id]);
        $prefs_data = $prefs_stmt->fetch(PDO::FETCH_ASSOC);

        if (!$prefs_data) {
            continue;
        }

        if ($prefs_data['reminder_1h']) {
            $reminder_time = clone $start_time;
            $reminder_time->modify('-1 hour');

            $pdo->prepare("
                INSERT INTO reminders (task_id, user_id, reminder_time)
                VALUES (?, ?, ?)
            ")->execute([
                $task_id,
                $participant_id,
                $reminder_time->format('Y-m-d H:i:s')
            ]);
        }

        if ($prefs_data['reminder_6h']) {
            $reminder_time = clone $start_time;
            $reminder_time->modify('-6 hours');

            $pdo->prepare("
                INSERT INTO reminders (task_id, user_id, reminder_time)
                VALUES (?, ?, ?)
            ")->execute([
                $task_id,
                $participant_id,
                $reminder_time->format('Y-m-d H:i:s')
            ]);
        }

        if ($prefs_data['reminder_12h']) {
            $reminder_time = clone $start_time;
            $reminder_time->modify('-12 hours');

            $pdo->prepare("
                INSERT INTO reminders (task_id, user_id, reminder_time)
                VALUES (?, ?, ?)
            ")->execute([
                $task_id,
                $participant_id,
                $reminder_time->format('Y-m-d H:i:s')
            ]);
        }

        if ($prefs_data['reminder_24h']) {
            $reminder_time = clone $start_time;
            $reminder_time->modify('-24 hours');

            $pdo->prepare("
                INSERT INTO reminders (task_id, user_id, reminder_time)
                VALUES (?, ?, ?)
            ")->execute([
                $task_id,
                $participant_id,
                $reminder_time->format('Y-m-d H:i:s')
            ]);
        }
    }

    header("Location: tasks.php?added=1");
    exit();
}

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

    UNION

    SELECT DISTINCT c.id, c.name
    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_data = $calendars_stmt->fetchAll(PDO::FETCH_ASSOC);

$tasks = $pdo->prepare("
    SELECT 
        t.id, t.title, t.description, t.start_datetime, t.end_datetime, t.color,
        c.name AS calendar_name
    FROM tasks t
    LEFT JOIN calendars c ON t.calendar_id = c.id
    WHERE t.calendar_id IN (
        SELECT id FROM calendars WHERE user_id = ?
        UNION
        SELECT calendar_id FROM calendar_access WHERE user_id = ?
    )
    AND (
        t.title LIKE ?
        OR t.description LIKE ?
        OR c.name LIKE ?
    )
    ORDER BY t.start_datetime ASC
");

$search_param = '%' . $search . '%';
$tasks->execute([$user_id, $user_id, $search_param, $search_param, $search_param]);
$task_list = $tasks->fetchAll(PDO::FETCH_ASSOC);

$reminders_stmt = $pdo->prepare("
    SELECT 
        r.id, r.reminder_time, r.is_sent,
        t.title, t.start_datetime, t.color
    FROM reminders r
    JOIN tasks t ON r.task_id = t.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
    ORDER BY r.reminder_time ASC
    LIMIT 10
");
$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>All Tasks - Work Planner</title>
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="../css/tasks.css">
</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>

<main>
<h2>All Tasks</h2>

<?php if (isset($_GET['added'])): ?>
    <div class="message success">Task added successfully!</div>
<?php endif; ?>

<?php if (isset($_GET['error']) && $_GET['error'] == 'no_permission'): ?>
    <div class="message error">You don't have permission to add tasks to this calendar.</div>
<?php endif; ?>

<div class="tasks-container">

    <div class="tasks-left">
        <div class="section-card">
            <h3>Add New Task</h3>

            <form method="POST" class="task-form">

                <div class="form-group">
                    <label for="title">Task Title</label>
                    <input type="text" name="title" id="title" required>
                </div>

                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea name="description" id="description" rows="3"></textarea>
                </div>

                <div class="form-group">
                    <label for="start_datetime">Start Time</label>
                    <input type="datetime-local" name="start_datetime" id="start_datetime" required>
                </div>

                <div class="form-group">
                    <label for="end_datetime">End Time</label>
                    <input type="datetime-local" name="end_datetime" id="end_datetime">
                </div>

                <div class="form-group">
                    <label for="calendar_id">Select Calendar</label>
                    <select name="calendar_id" id="calendar_id" required>
                        <?php foreach ($calendars_data as $row): ?>
                            <option value="<?= htmlspecialchars($row['id']) ?>">
                                <?= htmlspecialchars($row['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label for="color">Task Color</label>
                    <select name="color" id="color" required class="color-select">
                        <option value="#1E90FF">🔵 Work</option>
                        <option value="#FF4500">🔴 Urgent</option>
                        <option value="#32CD32">🟢 Personal</option>
                        <option value="#FFD700">🟡 Pending</option>
                        <option value="#8A2BE2">🟣 Project</option>
                        <option value="#2F4F4F">⚫ Other</option>
                    </select>
                </div>

                <button type="submit" class="btn-add-task">Add Task</button>
            </form>
        </div>
    </div>

    <div class="tasks-right">
        <div class="section-card reminders-section">
            <h3>Reminders</h3>
            <p class="hint">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' : '');
                            } else {
                                $time_until = $diff->h . ' hour' . ($diff->h > 1 ? 's' : '');
                            }
                        } else {
                            $time_until = 'Now';
                        }
                        ?>

                        <div class="reminder-item" style="border-left-color: <?= htmlspecialchars($reminder['color']) ?>;">
                            <div class="reminder-icon">⏰</div>

                            <div class="reminder-content">
                                <strong><?= htmlspecialchars($reminder['title']) ?></strong>

                                <div class="reminder-time">
                                    Task 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>
            <?php else: ?>
                <div class="no-reminders">
                    <p>No upcoming reminders</p>
                    <small>Reminders are created automatically based on your preferences</small>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="all-tasks-section">
<h3>All Tasks</h3>

<form method="GET" class="task-search-form">
    <input 
        type="text" 
        name="search" 
        placeholder="Search tasks..." 
        value="<?= htmlspecialchars($search) ?>"
    >

    <button type="submit">Search</button>

    <?php if (!empty($search)): ?>
        <a href="tasks.php" class="btn-clear-search">Clear</a>
    <?php endif; ?>
</form>

<?php if (count($task_list) > 0): ?>

<div class="tasks-grid">
<?php foreach ($task_list as $task): ?>
    <div class="task-card" style="border-left-color: <?= htmlspecialchars($task['color']) ?>;">

        <div class="task-header">
            <strong><?= htmlspecialchars($task['title']) ?></strong>
            <span class="calendar-badge">
                <?= htmlspecialchars($task['calendar_name'] ?? 'No Calendar') ?>
            </span>
        </div>

        <?php if (!empty($task['description'])): ?>
            <div class="task-description">
                <?= nl2br(htmlspecialchars($task['description'])) ?>
            </div>
        <?php endif; ?>

        <div class="task-time">
            <span><?= date('M d, Y - H:i', strtotime($task['start_datetime'])) ?></span>
            <?php if ($task['end_datetime']): ?>
                <span>→ <?= date('H:i', strtotime($task['end_datetime'])) ?></span>
            <?php endif; ?>
        </div>

        <div class="task-actions">
            <a href="tasks_edit.php?task_id=<?= htmlspecialchars($task['id']) ?>" class="btn-edit">Edit</a>
            <a href="task_delete.php?task_id=<?= htmlspecialchars($task['id']) ?>"
               class="btn-delete"
               onclick="return confirm('Are you sure you want to delete this task?');">
                Delete
            </a>
        </div>
    </div>
<?php endforeach; ?>
</div>

<?php else: ?>
    <div class="no-tasks">
        <?php if (!empty($search)): ?>
            <p>No tasks found for "<?= htmlspecialchars($search) ?>".</p>
        <?php else: ?>
            <p>No tasks yet. Create your first task above!</p>
        <?php endif; ?>
    </div>
<?php endif; ?>
</div>

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