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

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

$user_id = $_SESSION['user_id'];

if (!isset($_GET['task_id'])) {
    header("Location: tasks.php");
    exit();
}

$task_id = $_GET['task_id'];

$stmt = $pdo->prepare("SELECT * FROM tasks WHERE id = ? AND user_id = ?");
$stmt->execute([$task_id, $user_id]);
$task = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$task) {
    header("Location: tasks.php");
    exit();
}

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

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

    if (!$access_check->fetch()) {
        header("Location: tasks.php?error=no_permission");
        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 = ? AND ca.can_edit = 1

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

$allowed_colors = [
    '#1E90FF' => '🔵 Work',
    '#FF4500' => '🔴 Urgent',
    '#32CD32' => '🟢 Personal',
    '#FFD700' => '🟡 Pending',
    '#8A2BE2' => '🟣 Project',
    '#2F4F4F' => '⚫ Other'
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title']);
    $description = trim($_POST['description'] ?? '');
    $start_datetime = $_POST['start_datetime'];
    $end_datetime = $_POST['end_datetime'];
    $calendar_id = $_POST['calendar_id'];
    $color = $_POST['color'];

    if (!array_key_exists($color, $allowed_colors)) {
        $error = "Invalid color selected!";
    } elseif ($title && $start_datetime && $end_datetime && $calendar_id) {

        $calendar_permission = $pdo->prepare("
            SELECT id FROM calendars WHERE id = ? AND user_id = ?

            UNION

            SELECT calendar_id FROM calendar_access
            WHERE calendar_id = ? AND user_id = ? AND can_edit = 1
        ");
        $calendar_permission->execute([$calendar_id, $user_id, $calendar_id, $user_id]);

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

        $update_stmt = $pdo->prepare("
            UPDATE tasks 
            SET title = ?, description = ?, start_datetime = ?, end_datetime = ?, calendar_id = ?, color = ?
            WHERE id = ? AND user_id = ?
        ");
        $update_stmt->execute([
            $title,
            $description,
            $start_datetime,
            $end_datetime,
            $calendar_id,
            $color,
            $task_id,
            $user_id
        ]);

        header("Location: tasks.php?updated=1");
        exit();
    } else {
        $error = "Please fill in all required fields!";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit Task</title>
<link rel="stylesheet" href="../css/calendar.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>

<div class="edit-container">
    <h2>Edit Task</h2>

    <?php if (isset($error)): ?>
        <p class="error"><?= htmlspecialchars($error) ?></p>
    <?php endif; ?>

    <form method="POST">

        <label for="title">Title*</label>
        <input type="text" id="title" name="title" value="<?= htmlspecialchars($task['title']) ?>" required>

        <label for="description">Description</label>
        <textarea id="description" name="description"><?= htmlspecialchars($task['description']) ?></textarea>

        <label for="start_datetime">Start Date/Time*</label>
        <input type="datetime-local" id="start_datetime" name="start_datetime"
               value="<?= date('Y-m-d\TH:i', strtotime($task['start_datetime'])) ?>" required>

        <label for="end_datetime">End Date/Time*</label>
        <input type="datetime-local" id="end_datetime" name="end_datetime"
               value="<?= date('Y-m-d\TH:i', strtotime($task['end_datetime'])) ?>" required>

        <label for="calendar_id">Calendar*</label>
        <select id="calendar_id" name="calendar_id" required>
            <?php foreach ($calendars as $calendar): ?>
                <option value="<?= $calendar['id'] ?>" <?= $calendar['id'] == $task['calendar_id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($calendar['name']) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <label for="color">Task Color*</label>
        <select id="color" name="color" required>
            <?php foreach ($allowed_colors as $hex => $label): ?>
                <option value="<?= $hex ?>" <?= $task['color'] == $hex ? 'selected' : '' ?>>
                    <?= $label ?>
                </option>
            <?php endforeach; ?>
        </select>

        <button type="submit">Save Changes</button>
    </form>

    <a class="cancel-link" href="tasks.php">Cancel</a>
</div>

</body>
</html>