<?php 
    require_once('connection.php');

    if ($_SERVER['REQUEST_METHOD'] != 'POST') {
        echo "<script> alert('Error: No data to save.'); location.replace('./') </script>";
        $conn->close();
        exit;
    }

    // Sanitize the input data to prevent SQL injection
    $title = mysqli_real_escape_string($conn, $_POST['title']);
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    $start_datetime = mysqli_real_escape_string($conn, $_POST['start_datetime']);
    $end_datetime = mysqli_real_escape_string($conn, $_POST['end_datetime']);

    // Check if an ID is provided for updating an existing event
    $id = isset($_POST['id']) ? (int)$_POST['id'] : null;

    // Prepare the SQL query for either INSERT or UPDATE based on whether an ID is provided
    if (empty($id)) {
        $sql = "INSERT INTO `calendar_event_master` (`title`, `description`, `start_datetime`, `end_datetime`) 
                VALUES ('$title', '$description', '$start_datetime', '$end_datetime')";
    } else {
        $sql = "UPDATE `calendar_event_master` SET `title` = '$title', `description` = '$description', 
                `start_datetime` = '$start_datetime', `end_datetime` = '$end_datetime' WHERE `id` = $id";
    }

    $save = $conn->query($sql);

    if ($save) {
        header("Location: add_event.php?success=Schedule Successfully Saved.");
        // echo "<script> alert('Schedule Successfully Saved.'); location.replace('./') </script>";
    } else {
        header("Location: add_event.php?error=An Error occurred.");
       
    }
    
    $conn->close();
?>
