<?php
session_start();

if ($_SESSION["admin"] != true) {
    header("location:login.php");
    exit;
}

include '../connection.php';

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {
    case 'addEvent':
        $eventType = $_POST['uploadType'];
        $eventTitle = $_POST['eventTitle'];
        $eventDate = $_POST['eventDate'];
        $eventPlace = $_POST['eventPlace'];
        $eventDetails = $_POST['eventDetails'];
        addEvent($eventType, $eventTitle, $eventDate, $eventPlace, $eventDetails);
        break;
    case 'getEvents':
        getEvents();
        break;
    case 'deleteEvent':
        $id = $_POST['id'];
        deleteEvent($id);
        break;
    default:
        echo "Invalid action!";
}

function addEvent($eventType, $eventTitle, $eventDate, $eventPlace, $eventDetails) {
    global $conn;

    $newImageName = null;

    if ($eventType === 'event') {
        if (!handleImageUpload($newImageName)) {
            return;
        }
    }

    $insertQuery = "INSERT INTO events (event_type, event_title, event_date, event_place, event_details, event_pic) VALUES (?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($insertQuery);
    $stmt->bind_param("ssssss", $eventType, $eventTitle, $eventDate, $eventPlace, $eventDetails, $newImageName);

    if ($stmt->execute()) {
        echo "Event added successfully.";
    } else {
        echo "Error adding event: " . $stmt->error;
    }
    $stmt->close();
}

function getEvents() {
    global $conn;
    $query = "SELECT ID, event_title, event_date, event_place, event_details, event_type, event_pic FROM events";
    $result = $conn->query($query);

    $events = [];
    while ($row = $result->fetch_assoc()) {
        $events[] = $row;
    }
    echo json_encode($events);
}

function deleteEvent($id) {
    global $conn;

    $selectQuery = "SELECT event_type, event_pic FROM events WHERE ID = ?";
    $stmt = $conn->prepare($selectQuery);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $event = $result->fetch_assoc();
    $stmt->close();

    if ($event && $event['event_type'] === 'event' && !empty($event['event_pic'])) {
        $imagePath = '../uploads/Events/' . $event['event_pic'];

        if (file_exists($imagePath)) {
            unlink($imagePath);
        }
    }

    $deleteQuery = "DELETE FROM events WHERE ID = ?";
    $stmt = $conn->prepare($deleteQuery);
    $stmt->bind_param("i", $id);

    if ($stmt->execute()) {
        echo "Event deleted successfully.";
    } else {
        echo "Error deleting event: " . $stmt->error;
    }
    $stmt->close();
}

function handleImageUpload(&$newImageName) {
    $imageFile = $_FILES['eventImage'];
    $imageName = basename($imageFile['name']);
    $imageTmpName = $imageFile['tmp_name'];
    $imageType = strtolower(pathinfo($imageName, PATHINFO_EXTENSION));

    if ($imageType !== 'jpg' && $imageType !== 'png') {
        echo "Only JPG and PNG images are allowed.";
        return false;
    }

    $uploadDir = '../uploads/Events';
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    $newImageName = uniqid() . '.' . $imageType;
    $imagePath = $uploadDir . '/' . $newImageName;

    return move_uploaded_file($imageTmpName, $imagePath);
}
?>
