<?php
include('../connection.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);

$type = isset($_GET['type']) ? $_GET['type'] : '';

if ($type == 'designations') {
    $sql = "SELECT DISTINCT current_designation FROM civil_court_officials";
    $result = $conn->query($sql);
    $options = "";

    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $options .= "<option value='{$row['current_designation']}'>{$row['current_designation']}</option>";
        }
    } elseif ($result === false) {
        echo "Error: " . $conn->error; // Error handling for the query
    }
    echo $options;

} elseif ($type == 'officials') {
    $sql = "SELECT ID, official_name, current_designation FROM civil_court_officials";
    $result = $conn->query($sql);
    $options = "";

    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $options .= "<option value='{$row['ID']}'>{$row['official_name']} ({$row['current_designation']})</option>";
        }
    } elseif ($result === false) {
        echo "Error: " . $conn->error; // Error handling for the query
    }
    echo $options;

} elseif ($type == 'data') {
    $sql = "SELECT ID, official_name, appointment_date, initial_designation, current_designation, PersonalNumber, date_of_birth, address, contact_number FROM civil_court_officials WHERE 1";
    $result = $conn->query($sql);
    $tableRows = "";

    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $tableRows .= "<tr>
                <td>{$row['official_name']}</td>
                <td>{$row['appointment_date']}</td>
                <td>{$row['initial_designation']}</td>
                <td>{$row['current_designation']}</td>
                <td>{$row['date_of_birth']}</td>
                <td>{$row['PersonalNumber']}</td>
                <td>{$row['address']}</td>
                <td>{$row['contact_number']}</td>
                <td><button class='update-btn' data-id='{$row['ID']}'>Update</button></td>
            </tr>";
        }
    } elseif ($result === false) {
        echo "Error: " . $conn->error; // Error handling for the query
    }
    echo $tableRows;

} elseif ($type == 'singleData') {
    // Fetch data for a specific official to populate the update form
    $id = isset($_GET['id']) ? $_GET['id'] : '';
    $sql = "SELECT * FROM civil_court_officials WHERE ID = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result && $result->num_rows > 0) {
        $official = $result->fetch_assoc();
        echo json_encode($official); // Return official data as JSON
    } else {
        echo json_encode(["error" => "Official not found"]);
    }
    $stmt->close();
}
$conn->close();
?>
