<?php
include('../connection.php'); // Include the database connection

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Get the form data
    $id = isset($_POST['update_id']) ? $_POST['update_id'] : ''; // ID for update (empty for new)
    $official_name = $_POST['official_name'];
    $appointment_date = $_POST['appointment_date'];
    $intial_designation = $_POST['intial_designation'];
    $current_designation = $_POST['current_designation'];
    $date_of_birth = $_POST['date_of_birth'];
    $address = $_POST['address'];
    $contact_number = $_POST['contact_number'];
    $PersonalNumber = $_POST['PersonalNumber']; // Personal Number to identify unique records

    // Check for duplicates, excluding the current ID if updating
    if (empty($id)) {
        $check_sql = "SELECT * FROM civil_court_officials WHERE PersonalNumber = ? ";
        $check_stmt = $conn->prepare($check_sql);
        $check_stmt->bind_param('s', $PersonalNumber);
        $check_stmt->execute();
        $result = $check_stmt->get_result();

        if ($result->num_rows > 0) {
            echo "Duplicate entry found for Personal Number: " . $PersonalNumber;
            exit; // Stop if duplicate found
        }
    }

    // Insert or Update Record
    if (empty($id)) {
        // Insert the new record
        $sql = "INSERT INTO civil_court_officials (official_name, appointment_date, initial_designation, current_designation, PersonalNumber, date_of_birth, address, contact_number) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('ssssssss', $official_name, $appointment_date, $intial_designation, $current_designation, $PersonalNumber, $date_of_birth, $address, $contact_number);

        if ($stmt->execute()) {
            echo "Record inserted successfully!";
        } else {
            echo "Error inserting record: " . $stmt->error;
        }
    } else {
        // Update existing record
        $sql = "UPDATE civil_court_officials SET official_name = ?, appointment_date = ?, initial_designation = ?, current_designation = ?, PersonalNumber = ?, date_of_birth = ?, address = ?, contact_number = ? WHERE ID = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('ssssssssi', $official_name, $appointment_date, $intial_designation, $current_designation,  $PersonalNumber,$date_of_birth, $address, $contact_number, $id);

        if ($stmt->execute()) {
            echo "Record updated successfully!";
        } else {
            echo "Error updating record: " . $stmt->error;
        }
    }
}
?>
