<?php
session_start();
if ($_SESSION["admin"] != true) {
    header("location:login.php");
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Judicial Judgments</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 80%;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            color: #333;
        }
        form {
            margin-bottom: 20px;
            padding: 10px;
            border: 1px solid #ddd;
            background-color: #fafafa;
        }
        label {
            display: block;
            margin-bottom: 6px;
            font-weight: bold;
        }
        input[type="text"],
        input[type="date"],
        input[type="file"],
        select {
            width: 100%;
            padding: 8px;
            margin-bottom: 12px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px 20px;
            text-align: center;
            font-size: 16px;
            cursor: pointer;
            margin-top: 10px;
            border-radius: 4px;
        }
        button:hover {
            background-color: #45a049;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 12px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        #progressContainer {
            display: none;
            margin-bottom: 10px;
        }
        progress {
            width: 100%;
        }
        .actions {
            display: flex;
            gap: 10px;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container">
    <h1>Insert or Update Judicial Judgment</h1>
    <form id="judgmentForm" method="post" action="manage_judgments.php" enctype="multipart/form-data">
        <label for="officerName">Officer Name:</label>
        <input type="text" id="officerName" name="officerName" required><br>

        <label for="caseNumber">Case Number:</label>
        <input type="text" id="caseNumber" name="caseNumber" required><br>

        <label for="caseType">Case Type:</label>
        <input type="text" id="caseType" name="caseType" required><br>

        <label for="judgmentDate">Judgment Date:</label>
        <input type="date" id="judgmentDate" name="judgmentDate" required><br>

        <label for="courtName">Court Name:</label>
        <select id="courtName" name="courtID" required></select><br>

        <label for="judgmentFile">Upload Judgment (PDF):</label>
        <input type="file" id="judgmentFile" name="judgmentFile" required><br>

        <!-- Progress Bar -->
        <div id="progressContainer">
            <progress id="uploadProgress" value="0" max="100"></progress>
            <span id="progressText">0%</span>
        </div>

        <input type="hidden" id="judgmentID" name="judgmentID">
        <button type="submit">Save</button>
    </form>

    <h1>All Judicial Judgments</h1>
    <table id="judgmentsTable">
        <thead>
        <tr>
            <th>ID</th>
            <th>Officer Name</th>
            <th>Case Number</th>
            <th>Case Type</th>
            <th>Judgment Date</th>
            <th>Court ID</th>
            <th>Judgment Text</th>
            <th>Actions</th>
        </tr>
        </thead>
        <tbody>
        <!-- Rows will be dynamically added here -->
        </tbody>
    </table>
</div>

<script>
    $(document).ready(function () {
        // Fetch and populate court names
        $.ajax({
            url: 'manage_judgments.php?fetchCourts=true',
            method: 'GET',
            dataType: 'json',
            success: function (data) {
                if (data.success) {
                    data.courts.forEach(function (court) {
                        $('#courtName').append('<option value="' + court.ID + '">' + court.court_name + '</option>');
                    });
                } else {
                    console.error("Error fetching courts: " + data.message);
                }
            },
            error: function (xhr, status, error) {
                console.error("Error fetching courts: " + error);
            }
        });

        // Fetch and populate judgments
        function fetchJudgments(searchQuery = '') {
            $.ajax({
                url: 'manage_judgments.php',
                method: 'GET',
                data: { searchQuery: searchQuery },
                dataType: 'json',
                success: function (data) {
                    $('#judgmentsTable tbody').empty();
                    data.forEach(function (judgment) {
                        $('#judgmentsTable tbody').append('<tr>' +
                            '<td>' + judgment.ID + '</td>' +
                            '<td>' + judgment.OfficerName + '</td>' +
                            '<td>' + judgment.CaseNumber + '</td>' +
                            '<td>' + judgment.CaseType + '</td>' +
                            '<td>' + judgment.JudgmentDate + '</td>' +
                            '<td>' + judgment.court_id + '</td>' +
                            '<td><a href="' + judgment.JudgmentText + '" target="_blank">View</a></td>' +
                            '<td class="actions">' +
                            '<button class="edit" data-id="' + judgment.ID + '">Edit</button>' +
                            '<button class="delete" data-id="' + judgment.ID + '">Delete</button>' +
                            '</td>' +
                            '</tr>');
                    });
                },
                error: function () {
                    alert('Error fetching judgments.');
                }
            });
        }

        // Load judgments on page load
        fetchJudgments();

        // Handle delete action
        $(document).on('click', '.delete', function () {
            const judgmentID = $(this).data('id');

            if (confirm('Are you sure you want to delete this judgment?')) {
                $.ajax({
                    url: 'manage_judgments.php',
                    method: 'POST',
                    data: { deleteID: judgmentID },
                    success: function (response) {
                        const res = JSON.parse(response);
                        if (res.success) {
                            alert('Judgment deleted successfully.');
                            location.reload();
                        } else {
                            alert('Error: ' + res.message);
                        }
                    },
                    error: function () {
                        alert('Error occurred while deleting judgment.');
                    }
                });
            }
        });

        // Handle edit action
        $(document).on('click', '.edit', function () {
            const judgmentID = $(this).data('id');

            $.ajax({
                url: 'manage_judgments.php',
                method: 'GET',
                data: { editID: judgmentID },
                dataType: 'json',
                success: function (data) {
                    if (data.success) {
                        $('#officerName').val(data.judgment.OfficerName);
                        $('#caseNumber').val(data.judgment.CaseNumber);
                        $('#caseType').val(data.judgment.CaseType);
                        $('#judgmentDate').val(data.judgment.JudgmentDate);
                        $('#courtName').val(data.judgment.court_id);
                        $('#judgmentID').val(data.judgment.ID);
                        $('html, body').animate({ scrollTop: $('#judgmentForm').offset().top }, 500);
                    } else {
                        alert('Error: ' + data.message);
                    }
                },
                error: function () {
                    alert('Error occurred while fetching judgment details.');
                }
            });
        });

        // Submit form with progress bar
        $('#judgmentForm').submit(function (e) {
            e.preventDefault();
            var formData = new FormData(this);

            $('#progressContainer').show();
            $('#uploadProgress').val(0);
            $('#progressText').text('0%');

            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'manage_judgments.php', true);

            xhr.upload.addEventListener('progress', function (e) {
                if (e.lengthComputable) {
                    var percentComplete = Math.round((e.loaded / e.total) * 100);
                    $('#uploadProgress').val(percentComplete);
                    $('#progressText').text(percentComplete + '%');
                }
            });

            xhr.onload = function () {
                if (xhr.status === 200) {
                    var response = JSON.parse(xhr.responseText);
                    if (response.success) {
                        alert('Judgment saved successfully.');
                        location.reload();
                    } else {
                        alert('Error: ' + response.message);
                    }
                } else {
                    alert('Error occurred while uploading.');
                }
            };

            xhr.onerror = function () {
                alert('An error occurred during submission.');
            };

            xhr.send(formData);
        });
    });
</script>




</body>
</html>
