<?php
session_start();
if (!isset($_SESSION['AccAdminID'])) {
    header('Location: login.html');
    exit();
}

include("connection.php");
$AccID = $_SESSION['AccAdminID'];

// Fetching the user's name
$sql = "SELECT Admin_Name FROM admin WHERE Admin_ID = '$AccID'";
$result = mysqli_query($conn, $sql);
$user = mysqli_fetch_assoc($result);
$userName = $user['Admin_Name'];

// Function to generate a unique Event ID
function generateUniqueId($conn) {
    do {
        // Generate a random Event ID (you can customize this format)
        $EventID = 'EVE' . rand(10000, 99999);

        // Check if this Event ID already exists in the database
        $checkQuery = "SELECT Event_ID FROM event WHERE Event_ID = '$EventID'";
        $result = mysqli_query($conn, $checkQuery);
    } while (mysqli_num_rows($result) > 0); // Repeat until a unique ID is found

    return $EventID;
}

// Handle form submission for posting events
if (isset($_POST['submit'])) {
    // Capture values from HTML form
    $Location = $_POST['Location'];
    $Description = $_POST['description'];
    $Date = $_POST['date'];

    $AdminID = $AccID;
    // Generate a unique Event ID
    $EventID = generateUniqueId($conn);

    // Prepare SQL query
    $sql = "INSERT INTO event (Event_ID, Admin_ID, Location, Description, Dates) VALUES ('$EventID', '$AdminID', '$Location', '$Description', '$Date')";

    // Execute the query
    $column = mysqli_query($conn, $sql) or die ("Error: " . mysqli_error($conn));

    if ($column != 0) {
        header('Location: postEvents.php');
        exit();
    }
}

// Handle event deletion
if (isset($_GET['delete'])) {
    $eventIdToDelete = $_GET['delete'];
    $deleteSql = "DELETE FROM event WHERE Event_ID = '$eventIdToDelete'";
    mysqli_query($conn, $deleteSql) or die("Error: " . mysqli_error($conn));
    header('Location: postEvents.php');
    exit();
}

// Fetch event data
$sql = "SELECT * FROM event";
$data = mysqli_query($conn, $sql);
$events = [];

if (mysqli_num_rows($data) > 0) {
    while ($row = mysqli_fetch_assoc($data)) {
        $events[] = $row;
    }

    // Custom sort function to sort events by date
    usort($events, function($a, $b) {
        $dateA = strtotime($a['Dates']);
        $dateB = strtotime($b['Dates']);
        return $dateA - $dateB;
    });
}
$uniqueEventID = generateUniqueId($conn);
mysqli_close($conn); // Data security purposes

?>

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="style2.css">
    <link rel="stylesheet" href="event.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <title>Event | UITM BAZAAR</title>
</head>
<body>
    <aside class="sidebar">
      <div class="logo">
        <img src="pic/profiles.png" alt="logo">
        <h2><?php echo $userName; ?>'s</h2>
      </div>
      <ul class="links">
        <h4>Main Menu</h4>
        <li>
          <span class="material-symbols-outlined"><img src="pic/home.png"></span>
          <a href="adminmenu.php">Main Menu</a>
        </li>
        <hr>
        <h4>Advanced</h4>
        <li>
          <span class="material-symbols-outlined"><img src="pic/admin.png"></span>
          <a href="newAdmin.php">New Admin Acc</a>
        </li>
        <hr>
        <h4>Account</h4>
        <li>
          <span class="material-symbols-outlined"><img src="pic/profile2.png"></span>
          <a href="adminProfile.php">Profile</a>
        </li>
        <hr>
        <h4>Sign Out</h4>
        <li class="logout-link">
          <span class="material-symbols-outlined"><i class="fa-solid fa-right-from-bracket"></i></span>
          <a href="logoutAdmin.php">Logout</a>
        </li>
      </ul>
    </aside>
    <header class="header">
        <a href="adminmenu.php" class="logo">
        <span><?php echo $userName; ?>'s</span></a>
        <i class="fa-solid fa-bars" id="menu-icon"></i>
        <nav class="navbar">      
            <a href="report.php">Report</a> 
            <a href="renterList.php">Renter List</a>  
            <a href="viewFeedback.php">Feedback</a>
            <a href="approval.php">Order</a>
            <a href="postEvents.php">Events</a>
        </nav>    
    </header>

    <section>
        <div class="leftBox">
            <div class="content">
                <h1>Post a New Event</h1>
                <form id="eventForm" method="POST" action="postEvents.php">
                    <p>
                        <label for="Eventid">Event ID : </label>
                        <input type="text" name="Eventid" id="Eventid" value="<?php echo $uniqueEventID; ?>" required readonly>
                    </p>
                    <p>
                        <label for="Location">Location : </label>
                        <input type="text" name="Location" id="Location" required>
                    </p>
                    <p>
                        <label for="description">Description : </label>
                        <textarea id="description" name="description" required></textarea>
                    </p>
                    <p>
                        <label for="date">Date : </label>
                        <input type="date" id="date" name="date" required>
                    </p>
                    <p>
                        <button type="submit" name="submit">Post Event</button>
                    </p>
                </form>
            </div>
        </div>

        <div class="events">
            <ul>
                <?php foreach ($events as $event): ?>
                    <li>
                        <div class="time">
                            <h2><?php echo $event['Dates']; ?></h2>
                        </div>
                        <div class="details">
                            <h3><?php echo $event['Location']; ?></h3>
                            <p><?php echo $event['Description']; ?></p>
                            <a href="postEvents.php?delete=<?php echo $event['Event_ID']; ?>" class="delete-button" onclick="return confirm('Are you sure you want to delete this event?')">Delete</a>
                        </div>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
    </section>
    <footer class="footer" id="footer">
        <p class="copyright">
            NextGen Techne © | All Rights Reserved
        </p>
    </footer>
</body>
</html>