<?php
session_start();
require_once('mysqli_connect.php');

// ---- Must be logged in ----
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = (int) $_SESSION['user_id'];
$role = $_SESSION['role'] ?? '';

if ($role !== 'admin' && $role !== 'super_admin') {
    die("Access denied.");
}

$errors = [];
$success = "";
$teams = [];
$allEvents = [];
$editEvent = null;

function h($s) {
    return htmlspecialchars((string) $s, ENT_QUOTES, 'UTF-8');
}

// ---- Load teams ----
if ($role === 'super_admin') {
    $q = "SELECT team_id, team_name, sport, season
          FROM teams
          ORDER BY team_name ASC";
} /*else {
    $q = "SELECT team_id, team_name, sport, season
          FROM teams
          WHERE coach_id = $user_id
          ORDER BY team_name ASC";
}*/

//else Anthony
else {
    $q = "SELECT teams.team_id, teams.team_name, teams.sport, teams.season, rostered_coaches.user_id
          FROM teams
          INNER JOIN rostered_coaches
          ON rostered_coaches.team_id = teams.team_id
          WHERE rostered_coaches.user_id = $user_id
          ORDER BY team_name ASC";
}

$r = mysqli_query($dbc, $q);

if ($r) {
    while ($row = mysqli_fetch_assoc($r)) {
        $teams[] = $row;
    }
}

// ---- Load event for editing ----
if (isset($_GET['edit_event_id'])) {
    $edit_event_id = (int) $_GET['edit_event_id'];

    $q = "SELECT *
          FROM events
          WHERE event_id = $edit_event_id
          LIMIT 1";

    $r = mysqli_query($dbc, $q);

    if ($r && mysqli_num_rows($r) === 1) {
        $editEvent = mysqli_fetch_assoc($r);
    }
}

// ---- Handle Add/Edit Event ----
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $event_id = (int) ($_POST['event_id'] ?? 0);
    $team_id = (int) ($_POST['team_id'] ?? 0);
    $title = trim($_POST['title'] ?? '');
    $event_type = trim($_POST['event_type'] ?? '');
    $event_date = trim($_POST['event_date'] ?? '');
    $event_location = trim($_POST['event_location'] ?? '');
    $notes = trim($_POST['notes'] ?? '');

    if ($team_id <= 0) {
        $errors[] = "Please select a team.";
    }

    if ($team_id > 0) {
        if ($role === 'super_admin') {
            $checkQ = "SELECT team_id
                       FROM teams
                       WHERE team_id = $team_id
                       LIMIT 1";
        } else {
            $checkQ = "SELECT team_id
                       FROM rostered_coaches
                       WHERE team_id = $team_id
                         AND user_id = $user_id
                       LIMIT 1";
        }

        $checkR = mysqli_query($dbc, $checkQ);

        if (!$checkR || mysqli_num_rows($checkR) !== 1) {
            $errors[] = "Invalid team selection.";
        }
    }

    if ($title === '') {
        $errors[] = "Event title is required.";
    }

    if ($event_type === '') {
        $errors[] = "Event type is required.";
    }

    if ($event_date === '') {
        $errors[] = "Event date is required.";
    }

    if ($event_location === '') {
        $errors[] = "Event location is required.";
    }

    if (empty($errors)) {
        if ($event_id > 0) {
            // ---- Update existing event ----
            $q = "UPDATE events
                  SET team_id = $team_id,
                      title = '" . mysqli_real_escape_string($dbc, $title) . "',
                      event_type = '" . mysqli_real_escape_string($dbc, $event_type) . "',
                      event_date = '" . mysqli_real_escape_string($dbc, $event_date) . "',
                      event_location = '" . mysqli_real_escape_string($dbc, $event_location) . "',
                      notes = '" . mysqli_real_escape_string($dbc, $notes) . "'
                  WHERE event_id = $event_id";

            if (mysqli_query($dbc, $q)) {
                $success = "Event updated successfully!";
                $editEvent = null;
            } else {
                $errors[] = "Could not update event.";
            }

        } else {
            // ---- Insert new event ----
            $q = "INSERT INTO events (team_id, title, event_type, event_date, event_location, notes)
                  VALUES (
                      $team_id,
                      '" . mysqli_real_escape_string($dbc, $title) . "',
                      '" . mysqli_real_escape_string($dbc, $event_type) . "',
                      '" . mysqli_real_escape_string($dbc, $event_date) . "',
                      '" . mysqli_real_escape_string($dbc, $event_location) . "',
                      '" . mysqli_real_escape_string($dbc, $notes) . "'
                  )";

            if (mysqli_query($dbc, $q)) {
                $success = "Event added successfully!";
            } else {
                $errors[] = "Could not add event.";
            }
        }
    }
}

// ---- Load Events ----
if ($role === 'super_admin') {
    $q = "SELECT e.event_id, e.event_date, e.event_location, t.team_name, e.title, e.event_type, e.notes
          FROM events e
          JOIN teams t ON e.team_id = t.team_id
          WHERE e.event_date >= CURDATE()
          ORDER BY e.event_date ASC";

    $r = mysqli_query($dbc, $q);

    if ($r) {
        while ($row = mysqli_fetch_assoc($r)) {
            $allEvents[] = $row;
        }
    }

} /*else {
    $eventQ = "SELECT e.event_date, t.team_name, e.title, e.event_type, e.notes
               FROM events e
               JOIN teams t ON e.team_id = t.team_id
               WHERE t.coach_id = $user_id
                 AND e.event_date >= CURDATE()
               ORDER BY e.event_date ASC";
}*/

//else eventQ Anthony
else {
    $allEvents = [];
    $q = "SELECT team_id
          FROM rostered_coaches
          WHERE user_id = $user_id";
    $r = mysqli_query($dbc, $q);

    //$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
    if ($r) {
        while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
            //echo $row['team_id'];

            $team_id = (int)$row['team_id'];

            $q2 = "SELECT events.event_id, events.title, events.event_type, events.event_date, events.event_location, events.notes, teams.team_name
                   FROM events
                   INNER JOIN teams 
                   ON events.team_id = teams.team_id
                   WHERE events.team_id = $team_id
                   AND event_date >= CURDATE()
                   ORDER BY event_date ASC";

            $r2 = mysqli_query($dbc, $q2);

            if ($r2) {
                while($row2 = mysqli_fetch_array($r2, MYSQLI_ASSOC)){
                    //echo $row2['team_name'];
                    $allEvents[]= $row2;
                }
            }
        }
    }

    if ($r && isset($r2) && $r2) {
        while ($row2 = mysqli_fetch_assoc($r2)) {
            $allEvents[] = $row2;
        }
    }
}
?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Add Event • Sideline</title>
    <link rel="icon" type="image/x-icon" href="images/sideline_logo.ico">

    <style>
        :root {
            --bg: #f6f7fb;
            --card: #fff;
            --text: #0f172a;
            --muted: #64748b;
            --line: #e5e7eb;
            --dark: #111827;
        }

        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            font-family: system-ui, Segoe UI, Arial, sans-serif;
            background: var(--bg);
            color: var(--text);
        }

        .topbar {
            display: flex;
            justify-content: space-between;
            padding: 14px 18px;
            background: linear-gradient(to right, #251F47, #111827, #2B784A);
            color: #fff;
        }

        .nav a {
            background: #fff;
            padding: 8px 10px;
            border-radius: 12px;
            margin-left: 8px;
            text-decoration: none;
        }

        .brand a {
            text-decoration: none; 
            color: inherit
        }

        .container {
            max-width: 1400px;
            margin: 30px auto;
            padding: 0 16px;
        }

        .grid {
            display: grid;
            grid-template-columns: repeat(12, 1fr);
            gap: 20px;
        }

        .col-8 {
            grid-column: span 8;
        }

        .col-4 {
            grid-column: span 4;
        }

        .card {
            background: #fff;
            border: 1px solid var(--line);
            border-radius: 16px;
            padding: 20px;
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        .tableWrap {
            width: 100%;
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th,
        td {
            padding: 10px;
            border-bottom: 1px solid var(--line);
        }

        th {
            text-align: left;
            background: #f8fafc;
            color: var(--muted);
        }

        input,
        select {
            width: 100%;
            padding: 10px;
            border: 1px solid var(--line);
            border-radius: 12px;
            margin-bottom: 10px;
        }

        .btn {
            background: var(--dark);
            color: #fff;
            padding: 10px;
            border: none;
            border-radius: 12px;
            margin-top: 10px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }

        .btn.small {
            padding: 6px 10px;
            margin-top: 0;
            font-size: .9rem;
        }

        @media (max-width: 900px) {
            .col-8,
            .col-4 {
                grid-column: span 12;
            }
        }
    </style>
</head>

<body>

    <!-- Header Bar -->
    <header class="topbar">
        <div class="brand">
            <a href="coach_dashboard.php">Sideline <span style="opacity:.8;font-weight:600">Add Event</span></a>
        </div>
        <div class="nav">
            <a href="logout.php">Logout</a>
        </div>
    </header>

    <main class="container">

        <?php if (!empty($errors)): ?>
            <div style="color:red">
                <?php foreach ($errors as $e): ?>
                    <p><?= h($e) ?></p>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div style="color:green"><?= h($success) ?></div>
        <?php endif; ?>

        <section class="grid">

            <!-- Events Left -->
            <div class="card col-8">
                <h3>All Upcoming Events</h3>

                <?php if (empty($allEvents)): ?>
                    <p>No upcoming events</p>
                <?php else: ?>
                    <div class="tableWrap">
                        <table>
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Team</th>
                                    <th>Event</th>
                                    <th>Type</th>
                                    <th>Location</th>
                                    <th>Notes</th>
                                    <th>Edit</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($allEvents as $event): ?>
                                    <tr>
                                        <td><?= h($event['event_date']) ?></td>
                                        <td><?= h($event['team_name']) ?></td>
                                        <td><?= h($event['title']) ?></td>
                                        <td><?= h($event['event_type']) ?></td>
                                        <td><?= h($event['event_location'] ?? '') ?></td>
                                        <td><?= !empty($event['notes']) ? h($event['notes']) : '—' ?></td>
                                        <td>
                                            <a class="btn small" href="add_event.php?edit_event_id=<?= (int)$event['event_id'] ?>">
                                                Edit
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Add event Right -->
            <div class="card col-4">
                <h3><?= $editEvent ? 'Edit Event' : 'Add Event' ?></h3>

                <form method="post">
                    <?php if ($editEvent): ?>
                        <input type="hidden" name="event_id" value="<?= (int)$editEvent['event_id'] ?>">
                    <?php endif; ?>

                    <label>Team</label>
                    <select name="team_id" required>
                        <option value="">Select Team</option>
                        <?php foreach ($teams as $t): ?>
                            <option value="<?= (int)$t['team_id'] ?>"
                                <?= ($editEvent && (int)$editEvent['team_id'] === (int)$t['team_id']) ? 'selected' : '' ?>>
                                <?= h($t['team_name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <label>Title</label>
                    <input name="title" required value="<?= h($editEvent['title'] ?? '') ?>">

                    <label>Type</label>
                    <input name="event_type" required value="<?= h($editEvent['event_type'] ?? '') ?>">

                    <label>Date</label>
                    <input type="date" name="event_date" required value="<?= h($editEvent['event_date'] ?? '') ?>">
                    
                    <label>Location</label>
                    <input name="event_location" required value="<?= h($editEvent['event_location'] ?? '') ?>">

                    <label>Notes</label>
                    <input name="notes" value="<?= h($editEvent['notes'] ?? '') ?>">

                    <button class="btn"><?= $editEvent ? 'Update Event' : 'Add Event' ?></button>

                    <?php if ($editEvent): ?>
                        <a class="btn" href="add_event.php">Cancel Edit</a>
                    <?php endif; ?>
                </form>
            </div>

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