<?php
include "config.php";

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $sp_name = mysqli_real_escape_string($con, $_POST['sp_name']);
    $sp_address = mysqli_real_escape_string($con, $_POST['sp_address']);
    $sp_tel = mysqli_real_escape_string($con, $_POST['sp_tel']);
    $sp_number = mysqli_real_escape_string($con, $_POST['sp_number']);
    $sp_email = mysqli_real_escape_string($con, $_POST['sp_email']);
    $time_stamp = date('Y-m-d H:i:s');

    // Check for duplicate email
    $check_query = "SELECT * FROM spoffice WHERE sp_email = '$sp_email'";
    $check_result = mysqli_query($con, $check_query);

    if (mysqli_num_rows($check_result) > 0) {
        echo "<script>alert('Error: Email already exists!'); window.history.back();</script>";
    } else {
        $query = "INSERT INTO spoffice (sp_name, sp_address, sp_tel, sp_number, sp_email)
                  VALUES ('$sp_name', '$sp_address', '$sp_tel', '$sp_number', '$sp_email')";
        
        if (mysqli_query($con, $query)) {
            echo '<script>window.location.href = "sp_office.php";</script>';
            
        } else {
            echo "Error: " . mysqli_error($con);
        }
    }
}
?>