<?php
include("connection.php");

// Origin add form submission handling
if (isset($_POST['add'])) {
    $origin_name = $_POST['origin_name'];
    $currentDateTime = date('Y-m-d H:i:s');
    
    // Check if origin_name already exists in the database
    $check_sql = "SELECT * FROM origin WHERE origin_name = '$origin_name'";
    $check_result = mysqli_query($conn, $check_sql);
    
    if (mysqli_num_rows($check_result) > 0) {
        header("Location: add_origin.php?error=Origin Name Already Exists!!!");
        exit();
    }

    // Insert new origin into the database
    $insert_sql = "INSERT INTO origin (origin_name, date_time) VALUES ('$origin_name', '$currentDateTime')";
    $insert_result = mysqli_query($conn, $insert_sql);

    if ($insert_result) {
        header("Location: add_origin.php?success=Origin Added Successfully!!!");
        exit();
    } else {
        header("Location: add_origin.php?error=Failed insertion!!!");
        exit();
    }
}

// Origin status update form submission handling
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $itemId = $_POST['item_id'];
    
    if (isset($_POST['activate'])) {
        $status = 1;
    } elseif (isset($_POST['block'])) {
        $status = 0;
    }
    
    $updateQuery = "UPDATE origin SET status = $status WHERE id = $itemId";
    $updateResult = mysqli_query($conn, $updateQuery);
    
    if ($updateResult) {
        header('Location: add_origin.php?success=Status Updated Successfully!!!');
        exit();
    } else {
        header('Location: add_origin.php?error=Failed to Update Status!!!');
        exit();
    }
}
?>
