<?php
include "config.php";

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $id = mysqli_real_escape_string($con, $_POST['id']);
    $sp_name = mysqli_real_escape_string($con, $_POST['name']);
    $sp_address = mysqli_real_escape_string($con, $_POST['address']);
    $sp_tel = mysqli_real_escape_string($con, $_POST['telephone']);
    $sp_number = mysqli_real_escape_string($con, $_POST['number']);
    $sp_email = mysqli_real_escape_string($con, $_POST['email']);

    // Check for duplicate email but allow current record
    $check_query = "SELECT * FROM spoffice WHERE sp_email = '$sp_email' AND id != '$id'";
    $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 {
        $update_query = "UPDATE spoffice SET 
                            sp_name = '$sp_name',
                            sp_address = '$sp_address',
                            sp_tel = '$sp_tel',
                            sp_number = '$sp_number',
                            sp_email = '$sp_email'
                         WHERE id = '$id'";

        if (mysqli_query($con, $update_query)) {
            echo '<script>window.location.href = "sp_office.php";</script>';
            exit();
        } else {
            echo "Error updating record: " . mysqli_error($con);
        }
    }
}
?>