<?php
session_start();
require 'db_connection.php';

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    header("Location: add_activity.php");
    exit();
}

// -------------------- INPUT CLEANING --------------------
$activity_name  = trim($_POST['activity_name'] ?? '');
$description    = trim($_POST['description'] ?? '');
$activity_date  = trim($_POST['activity_date'] ?? '');

// -------------------- VALIDATION --------------------
if (empty($activity_name) || empty($description) || empty($activity_date)) {
    $_SESSION['message'] = "All fields are required.";
    $_SESSION['message_type'] = "danger";
    header("Location: add_activity.php");
    exit();
}

// Ensure valid datetime
$date_timestamp = strtotime($activity_date);
if (!$date_timestamp) {
    $_SESSION['message'] = "Invalid date format.";
    $_SESSION['message_type'] = "danger";
    header("Location: add_activity.php");
    exit();
}

// Optional: ensure future date
if ($date_timestamp <= time()) {
    $_SESSION['message'] = "Activity date must be in the future.";
    $_SESSION['message_type'] = "danger";
    header("Location: add_activity.php");
    exit();
}

// -------------------- INSERT --------------------
$sql = "INSERT INTO upcoming_activities (activity_name, description, activity_date)
        VALUES (?, ?, ?)";

$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $activity_name, $description, $activity_date);

if ($stmt->execute()) {
    $_SESSION['message'] = "Activity added successfully!";
    $_SESSION['message_type'] = "success";
} else {
    $_SESSION['message'] = "Database error occurred.";
    $_SESSION['message_type'] = "danger";
}

$stmt->close();
$conn->close();

// -------------------- REDIRECT --------------------
header("Location: add_activity.php");
exit();