<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Courts, Offices, and Officers</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <h2>Add Presiding Officer</h2>
    <form id="addOfficerForm" enctype="multipart/form-data">
        <label for="officerName">Officer Name:</label>
        <input type="text" id="officerName" name="officerName" required>
        <label for="officerCourtId">Court:</label>
        <select id="officerCourtId" name="officerCourtId" required></select>
        <label for="officerStatus">Status:</label>
        <select id="officerStatus" name="officerStatus" required>
            <option value="1">Present</option>
            <option value="0">Transferred</option>
        </select>
        <label for="transferIn">Transfer In Date:</label>
        <input type="date" id="transferIn" name="transferIn" required>
        <label for="transferOut">Transfer Out Date:</label>
        <input type="date" id="transferOut" name="transferOut">
        <label for="officerImage">Officer Image:</label>
        <input type="file" id="officerImage" name="officerImage" accept="image/*">
        <button type="submit">Add Officer</button>
    </form>
    <div id="officerResponseMessage"></div>
 
    <h2>Existing Officers</h2>
    <table id="officersTable">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Court</th>
                <th>Status</th>
                <th>Transfer In</th>
                <th>Transfer Out</th>
                <th>Image</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

    <h2>Add Court</h2>
    <form id="addCourtForm">
        <label for="courtName">Court Name:</label>
        <input type="text" id="courtName" name="courtName" required>
        <select name="courtstatus" id="courtstatus" required>
            <option value="1">Active</option>
            <option value="0">De-Active</option>
        </select>
        <button type="submit">Add Court</button>
    </form>
    <div id="courtResponseMessage"></div>

    <h2>Existing Courts</h2>
    <table id="courtsTable">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

    <div id="updateOfficerModal" style="display:none;">
        <div style="background-color: #fff; padding: 20px; border-radius: 5px; width: 300px; margin: auto; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);">
            <h2>Update Officer</h2>
            <form id="updateOfficerForm" enctype="multipart/form-data">
                <input type="hidden" id="updateOfficerId" name="id">
                <label for="updateOfficerName">Officer Name:</label>
                <input type="text" id="updateOfficerName" name="officerName" required>
                <label for="updateOfficerCourtId">Court:</label>
                <select id="updateOfficerCourtId" name="courtId" required></select>
                <label for="updateOfficerStatus">Status:</label>
                <select id="updateOfficerStatus" name="officerStatus" required>
                    <option value="1">Present</option>
                    <option value="0">Transferred</option>
                </select>
                <label for="updateTransferIn">Transfer In Date:</label>
                <input type="date" id="updateTransferIn" name="transferIn" required>
                <label for="updateTransferOut">Transfer Out Date:</label>
                <input type="date" id="updateTransferOut" name="transferOut">
                <!-- File input for updating officer image -->
                <label for="updateOfficerImage">Officer Image:</label>
                <input type="file" id="updateOfficerImage" name="officerImage" accept="image/*">
                <button type="submit">Update Officer</button>
            </form>
            <button onclick="closeModal()">Cancel</button>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script type="text/javascript">
$(document).ready(function() {
    fetchCourts();
    fetchOfficers();

    $("#addCourtForm").submit(function(event) {
        event.preventDefault();
        var courtName = $("#courtName").val();
        var courtstatus = $("#courtstatus").val();
        $.post('manage_office.php', { 
            action: 'addCourt', 
            courtName: courtName, 
            courtstatus: courtstatus 
        }, function(response) {
            $("#courtResponseMessage").text(response);
            fetchCourts();
        }).fail(function(xhr, status, error) {
            $("#courtResponseMessage").text("Error: " + error);
        });
    });

    $("#addOfficerForm").submit(function(event) {
        event.preventDefault();
        var formData = new FormData(this);
        formData.append('action', 'addOfficer');
        
        $.ajax({
            url: 'manage_office.php',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function(response) {
                $("#officerResponseMessage").text(response);
                fetchOfficers();
                $("#addOfficerForm")[0].reset();
            },
            error: function(xhr, status, error) {
                $("#officerResponseMessage").text("Upload failed: " + error);
            }
        });
    });

    $("#updateOfficerForm").submit(function(event) {
        event.preventDefault();
        var formData = new FormData(this);
        formData.append('action', 'updateOfficer');
        
        // Debug: Log form data before sending
        console.log("FormData contents:");
        for (var pair of formData.entries()) {
            console.log(pair[0] + ': ' + pair[1]);
        }

        $.ajax({
            url: 'manage_office.php',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function(response) {
                try {
                    var result = JSON.parse(response);
                    if (result.success) {
                        alert(result.message);
                        fetchOfficers();
                        closeModal();
                    } else {
                        alert("Error: " + result.message);
                    }
                } catch (e) {
                    alert("Update successful! " + response);
                    fetchOfficers();
                    closeModal();
                }
            },
            error: function(xhr, status, error) {
                alert("Update failed: " + error);
                console.error("Update error:", error);
            }
        });
    });
});

function fetchCourts() {
    $.get('manage_office.php', { action: 'getCourts' }, function(data) {
        try {
            var courts = JSON.parse(data);
            $("#officerCourtId").empty();
            $("#updateOfficerCourtId").empty();
            var tableContent = '';
            
            courts.forEach(function(court) {
                $("#officerCourtId").append(new Option(court.court_name, court.ID));
                $("#updateOfficerCourtId").append(new Option(court.court_name, court.ID));
                tableContent += `<tr>
                    <td>${court.ID}</td>
                    <td>${court.court_name}</td>
                    <td>
                        <button onclick="deleteItem('court', ${court.ID})">Delete</button>
                    </td>
                </tr>`;
            });
            $("#courtsTable tbody").html(tableContent);
        } catch (e) {
            console.error("Error parsing courts data:", e);
        }
    }).fail(function(xhr, status, error) {
        console.error("Failed to fetch courts:", error);
    });
}

function fetchOfficers() {
    $.get('manage_office.php', { action: 'getOfficers' }, function(data) {
        try {
            var officers = JSON.parse(data);
            var tableContent = '';
            
            officers.forEach(function(officer) {
                var status = officer.officer_status == 1 ? 'Present' : 'Transferred';
                var transferOut = officer.transfer_out ? officer.transfer_out : 'N/A';
                var officerImage = officer.pic_path ? 
                    `<img src="${officer.pic_path}" alt="Officer Image" width="50" height="50">` : 
                    'No Image';
                
                tableContent += `<tr>
                    <td>${officer.ID}</td>
                    <td>${officer.officer_name}</td>
                    <td>${officer.court_name || officer.court_id}</td>
                    <td>${status}</td>
                    <td>${officer.transfer_in}</td>
                    <td>${transferOut}</td>
                    <td>${officerImage}</td>
                    <td>
                        <button onclick="openModal(
                            ${officer.ID}, 
                            '${escapeHtml(officer.officer_name)}', 
                            ${officer.court_id}, 
                            ${officer.officer_status}, 
                            '${officer.transfer_in}', 
                            '${officer.transfer_out || ''}',
                            '${officer.pic_path || ''}'
                        )">Update</button>
                        <button onclick="deleteOfficer(${officer.ID})">Delete</button>
                    </td>
                </tr>`;
            });
            $("#officersTable tbody").html(tableContent);
        } catch (e) {
            console.error("Error parsing officers data:", e);
        }
    }).fail(function(xhr, status, error) {
        console.error("Failed to fetch officers:", error);
    });
}

function openModal(id, name, courtId, status, transferIn, transferOut, currentImage = '') {
    $("#updateOfficerId").val(id);
    $("#updateOfficerName").val(name);
    $("#updateOfficerCourtId").val(courtId);
    $("#updateOfficerStatus").val(status);
    $("#updateTransferIn").val(transferIn);
    $("#updateTransferOut").val(transferOut);
    
    // Display current image if exists
    if (currentImage) {
        $("#currentOfficerImage").html(`<img src="${currentImage}" width="100"><br>
            <small>Current Image</small>`);
    } else {
        $("#currentOfficerImage").html("No current image");
    }
    
    $("#updateOfficerModal").show();
}

function closeModal() {
    $("#updateOfficerModal").hide();
    $("#currentOfficerImage").empty();
    $("#updateOfficerForm")[0].reset();
}

function deleteItem(type, id) {
    if (confirm(`Are you sure you want to delete this ${type}?`)) {
        $.post('manage_office.php', { 
            action: `delete${capitalizeFirstLetter(type)}`, 
            id: id 
        }, function(response) {
            alert(response);
            fetchCourts();
            fetchOfficers();
        }).fail(function(xhr, status, error) {
            alert("Delete failed: " + error);
        });
    }
}

function deleteOfficer(id) {
    deleteItem('officer', id);
}

function capitalizeFirstLetter(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}
</script>
</body>
</html>