<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Causelist</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        table, th, td {
            border: 1px solid #ccc;
        }
        th, td {
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f4f4f4;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .button {
            padding: 10px 20px;
            color: #fff;
            background-color: #007BFF;
            border: none;
            cursor: pointer;
            margin-top: 10px;
        }
        .button:hover {
            background-color: #0056b3;
        }
        progress {
            width: 100%;
        }
        input[type="text"],
        input[type="date"],
        input[type="file"],
        select {
            width: 100%;
            padding: 10px;
            margin-top: 5px;
            margin-bottom: 15px;
            box-sizing: border-box;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        input[type="text"]:focus,
        input[type="date"]:focus,
        input[type="file"]:focus,
        select:focus {
            outline: none;
            border-color: #007BFF;
            box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
        }
    </style>
</head>
<body>
    <h1>Manage Causelist</h1>

    <!-- Form for uploading causelists -->
    <div class="form-group">
        <form id="uploadForm" enctype="multipart/form-data">
            <label for="court_id">Court:</label>
            <select id="court_id" name="court_id" required>
                <option value="">Loading courts...</option>
            </select>

            <label for="causelist_date">Causelist Date:</label>
            <input type="date" id="causelist_date" name="causelist_date" required>

            <label for="file_link">Upload File (PDF only):</label>
            <input type="file" id="file_link" name="file_link" accept=".pdf" required>

            <button type="submit" class="button">Upload</button>
        </form>
        <div style="margin-top: 10px;">
            <progress id="uploadProgress" value="0" max="100"></progress>
            <p id="uploadStatus"></p>
        </div>
    </div>

    <!-- Table displaying uploaded causelists -->
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Court ID</th>
                <th>Causelist Date</th>
                <th>File Link</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody id="causelistTable">
            <!-- Rows will be populated dynamically -->
        </tbody>
    </table>

    <script>
        // Load court data dynamically
        fetch('manage_causelist.php?action=fetchCourts')
            .then(response => response.json())
            .then(data => {
                const courtSelect = document.getElementById('court_id');
                courtSelect.innerHTML = '<option value="">Select Court</option>';
                data.forEach(court => {
                    courtSelect.innerHTML += `<option value="${court.ID}">${court.court_name}</option>`;
                });
            })
            .catch(error => console.error('Error loading courts:', error));

        // Load causelist data dynamically
        function loadCauselists() {
            fetch('manage_causelist.php?action=fetchCauselists')
                .then(response => response.json())
                .then(data => {
                    const tableBody = document.getElementById('causelistTable');
                    tableBody.innerHTML = '';
                    data.forEach(causelist => {
                        const row = `
                            <tr>
                                <td>${causelist.ID}</td>
                                <td>${causelist.court_name}</td>
                                <td>${causelist.causelist_date}</td>
                                <td><a href="${causelist.file_link}" target="_blank">View File</a></td>
                                <td><button class="button" onclick="deleteCauselist(${causelist.ID})">Delete</button></td>
                            </tr>
                        `;
                        tableBody.innerHTML += row;
                    });
                })
                .catch(error => console.error('Error fetching causelists:', error));
        }

        // Delete causelist
        function deleteCauselist(id) {
            if (confirm('Are you sure you want to delete this causelist?')) {
                fetch(`manage_causelist.php?action=delete&id=${id}`)
                    .then(response => response.json())
                    .then(result => {
                        if (result.success) {
                            alert('Causelist deleted successfully.');
                            loadCauselists();
                        } else {
                            alert('Error deleting causelist: ' + result.error);
                        }
                    })
                    .catch(error => console.error('Error deleting causelist:', error));
            }
        }

        // Handle form submission with progress bar and validation
        document.getElementById('uploadForm').addEventListener('submit', function (event) {
            event.preventDefault();

            const fileInput = document.getElementById('file_link');
            const file = fileInput.files[0];

            // Validate file type (ensure it's a PDF)
            if (file && file.type !== 'application/pdf') {
                alert('Invalid file type. Only PDF files are allowed.');
                return;
            }

            const form = document.getElementById('uploadForm');
            const formData = new FormData(form);
            const progressBar = document.getElementById('uploadProgress');
            const uploadStatus = document.getElementById('uploadStatus');

            const xhr = new XMLHttpRequest();

            // Update progress bar
            xhr.upload.addEventListener('progress', function (e) {
                if (e.lengthComputable) {
                    const percentComplete = (e.loaded / e.total) * 100;
                    progressBar.value = percentComplete;
                }
            });

            // Handle response
            xhr.addEventListener('load', function () {
                const response = JSON.parse(xhr.responseText);
                if (response.success) {
                    uploadStatus.textContent = response.message;
                    progressBar.value = 0; // Reset progress bar
                    loadCauselists(); // Reload table
                } else {
                    uploadStatus.textContent = 'Error: ' + response.message;
                }
            });

            // Handle error
            xhr.addEventListener('error', function () {
                uploadStatus.textContent = 'Failed to upload file.';
            });

            // Send AJAX request
            xhr.open('POST', 'manage_causelist.php', true);
            xhr.send(formData);
        });

        // Load causelists on page load
        loadCauselists();
    </script>
</body>
</html>
