<?php
// Start session and include necessary files
session_start();
require_once '../config.php';
require_once '../includes/auth.php';
require_once '../classes/DataSource.php'; // Contains permission management methods

// Redirect if not logged in or not a DAC Staff
redirect_if_not_logged_in('../index.php');
redirect_if_not_role('DAC Staff', '../index.php');

// Initialize DataSource class
$dataSourceManager = new DataSource($pdo);

// --- Handle Search and Filter Parameters ---
$search_query = trim($_GET['search'] ?? '');
$filter_status = trim($_GET['status_filter'] ?? '');

// Handle form submissions for updating permission status
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action_type = $_POST['action_type'] ?? '';
    $permission_id = $_POST['permission_id'] ?? null;

    if ($action_type === 'update_permission_status' && $permission_id) {
        $new_status = trim($_POST['new_status'] ?? '');
        $notes = trim($_POST['notes'] ?? '');

        // --- SECURITY CHECK: Verify permission ID and associated data source existence ---
        try {
            $permission_details = $dataSourceManager->getPermissionRequestById($permission_id);

            if (!$permission_details) {
                set_message("Permission request not found or invalid.", "danger");
                header('Location: manage_permissions_admin.php');
                exit();
            }

            // Optional: You could add a check here to ensure the data source itself is still active
            // $dataSource = $dataSourceManager->getDataSourceById($permission_details['fkdspsds_id']);
            // if (!$dataSource) { /* handle error */ }

            if (!in_array($new_status, ['Approved', 'Pending', 'Rejected', 'Revoked'])) {
                set_message('Invalid permission status selected.', 'danger');
            } else {
                // The reg_by for permission updates is the user who is logged in (DAC Staff)
                $dataSourceManager->updatePermissionStatus(
                    (int) $permission_id,
                    $new_status,
                    (int) $_SESSION['user_id'],
                    $notes
                );
                set_message('Permission status updated successfully!', 'success');
            }
        } catch (Exception $e) {
            set_message('Error updating permission status: ' . $e->getMessage(), 'danger');
        }
    }
    // Redirect to self, preserving search/filter parameters if they exist
    $redirect_url = 'manage_permissions_admin.php';
    $query_params = [];
    if (!empty($search_query)) {
        $query_params['search'] = urlencode($search_query);
    }
    if (!empty($filter_status)) {
        $query_params['status_filter'] = urlencode($filter_status);
    }
    if (!empty($query_params)) {
        $redirect_url .= '?' . http_build_query($query_params);
    }
    header('Location: ' . $redirect_url);
    exit();
}

// Fetch all permission requests based on search and filter parameters
$allPermissions = $dataSourceManager->getAllPermissionRequests($filter_status, $search_query);

?>

<!DOCTYPE html>
<html lang="en">
<!-- Header -->
<?php
// Include header file for admin pages
include_once("../includes/header_admin.php");
?>
<body>
    <div class="wrapper">
        <!-- Sidebar -->
        <?php
        // Include header file for admin pages
        include_once("../includes/nav_admin.php");
        ?>

        <!-- Main Content -->
        <div class="main-content">
            <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4 rounded-3">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Manage All Permissions</a>
                    <div class="d-flex">
                        <span class="navbar-text me-3">
                            Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>!
                        </span>
                    </div>
                </div>
            </nav>

            <?php
            // Display session messages
            if (isset($_SESSION['message'])) {
                echo '<div class="alert alert-' . $_SESSION['message_type'] . ' alert-dismissible fade show rounded-pill" role="alert">' . htmlspecialchars($_SESSION['message']) . '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>';
                unset($_SESSION['message']);
                unset($_SESSION['message_type']);
            }
            ?>

            <div class="card mb-4">
                <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">All Data Access Requests</h5>
                    <!-- Removed the "Create Mock Data Source" button -->
                </div>
                <div class="card-body">
                    <!-- Search and Filter Form -->
                    <form action="manage_permissions_admin.php" method="GET" class="mb-4">
                        <div class="row g-3 align-items-end">
                            <div class="col-md-5">
                                <label for="searchPermissionInput" class="form-label visually-hidden">Search Permissions</label>
                                <input type="text" class="form-control rounded-pill" id="searchPermissionInput" name="search" placeholder="Search by data source, requester, owner..." value="<?= htmlspecialchars($search_query) ?>">
                            </div>
                            <div class="col-md-4">
                                <label for="statusFilter" class="form-label visually-hidden">Filter by Status</label>
                                <select class="form-select rounded-pill" id="statusFilter" name="status_filter">
                                    <option value="">All Statuses</option>
                                    <option value="Pending" <?= ($filter_status == 'Pending' ? 'selected' : '') ?>>Pending</option>
                                    <option value="Approved" <?= ($filter_status == 'Approved' ? 'selected' : '') ?>>Approved</option>
                                    <option value="Rejected" <?= ($filter_status == 'Rejected' ? 'selected' : '') ?>>Rejected</option>
                                    <option value="Revoked" <?= ($filter_status == 'Revoked' ? 'selected' : '') ?>>Revoked</option>
                                </select>
                            </div>
                            <div class="col-md-3 d-flex justify-content-end">
                                <button type="submit" class="btn btn-info rounded-pill me-2"><i class="fas fa-filter me-2"></i>Apply Filter</button>
                                <a href="manage_permissions_admin.php" class="btn btn-secondary rounded-pill"><i class="fas fa-sync-alt me-2"></i>Reset</a>
                            </div>
                        </div>
                    </form>

                    <div class="table-responsive">
                        <table class="table table-hover table-striped">
                            <thead>
                                <tr>
                                    <th>Req. ID</th>
                                    <th>Data Source</th>
                                    <th>Requester</th>
                                    <th>Data Owner</th>
                                    <th>Permission Type</th>
                                    <th>Request Notes</th>
                                    <th>Proof</th>
                                    <th>Status</th>
                                    <th>Requested On</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($allPermissions)): ?>
                                    <?php foreach ($allPermissions as $permission): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($permission['pkdspsdsp_id']); ?></td>
                                            <td><?php echo htmlspecialchars($permission['dspsds_title_en']); ?></td>
                                            <td><?php echo htmlspecialchars($permission['requester_firstname'] . ' ' . $permission['requester_lastname']); ?></td>
                                            <td><?php echo htmlspecialchars($permission['owner_firstname'] . ' ' . $permission['owner_lastname']); ?></td>
                                            <td><?php echo htmlspecialchars($permission['dspsdsp_permission']); ?></td>
                                            <td><?php echo !empty($permission['dspsdsp_notes']) ? nl2br(htmlspecialchars($permission['dspsdsp_notes'])) : '<span class="text-muted">—</span>'; ?></td>
                                            <td>
                                                <?php if (!empty($permission['dspsdsp_proof_path'])): ?>
                                                    <?php
                                                        $proofPath = $permission['dspsdsp_proof_path'];
                                                        $isExternal = preg_match('/^https?:\\/\\//i', $proofPath) === 1;
                                                        $linkTarget = $isExternal ? $proofPath : '../uploads/' . $proofPath;
                                                    ?>
                                                    <a href="<?php echo htmlspecialchars($linkTarget); ?>" class="btn btn-sm btn-outline-primary rounded-pill" target="_blank" rel="noopener">
                                                        <i class="fas fa-file-pdf me-1"></i> View
                                                    </a>
                                                <?php else: ?>
                                                    <span class="text-muted">N/A</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php
                                                    if ($permission['dspsdsp_status'] == 'Approved') echo 'success';
                                                    else if ($permission['dspsdsp_status'] == 'Pending') echo 'warning';
                                                    else if ($permission['dspsdsp_status'] == 'Rejected') echo 'danger';
                                                    else echo 'secondary';
                                                ?>">
                                                    <?php echo htmlspecialchars($permission['dspsdsp_status']); ?>
                                                </span>
                                            </td>
                                            <td><?php echo htmlspecialchars($permission['dspsdsp_reg_datetime']); ?></td>
                                            <td>
                                                <button type="button" class="btn btn-sm btn-info rounded-pill btn-action" data-bs-toggle="modal" data-bs-target="#managePermissionModal"
                                                        data-permission-id="<?php echo htmlspecialchars($permission['pkdspsdsp_id']); ?>"
                                                        data-data-source="<?php echo htmlspecialchars($permission['dspsds_title_en']); ?>"
                                                        data-requester="<?php echo htmlspecialchars($permission['requester_firstname'] . ' ' . $permission['requester_lastname']); ?>"
                                                        data-permission-type="<?php echo htmlspecialchars($permission['dspsdsp_permission']); ?>"
                                                        data-notes="<?php echo htmlspecialchars($permission['dspsdsp_notes']); ?>"
                                                        data-current-status="<?php echo htmlspecialchars($permission['dspsdsp_status']); ?>">
                                                    <i class="fas fa-cogs"></i> Manage
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="9" class="text-center">No permission requests found.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Manage Permission Modal -->
    <div class="modal fade" id="managePermissionModal" tabindex="-1" aria-labelledby="managePermissionModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content rounded shadow-lg">
                <div class="modal-header text-white rounded-top" style="background-color: #28a745;">
                    <h5 class="modal-title" id="managePermissionModalLabel">Manage Permission Request</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-4">
                    <form action="manage_permissions_admin.php" method="POST">
                        <input type="hidden" name="action_type" value="update_permission_status">
                        <input type="hidden" name="permission_id" id="modalPermissionId">

                        <div class="mb-3">
                            <label for="modalDataSource" class="form-label">Data Source</label>
                            <input type="text" class="form-control rounded-pill" id="modalDataSource" readonly>
                        </div>
                        <div class="mb-3">
                            <label for="modalRequester" class="form-label">Requester</label>
                            <input type="text" class="form-control rounded-pill" id="modalRequester" readonly>
                        </div>
                        <div class="mb-3">
                            <label for="modalPermissionType" class="form-label">Permission Type</label>
                            <input type="text" class="form-control rounded-pill" id="modalPermissionType" readonly>
                        </div>
                        <div class="mb-3">
                            <label for="modalRequestNotes" class="form-label">Requester Notes</label>
                            <textarea class="form-control rounded-3" id="modalRequestNotes" rows="3" readonly></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="newPermissionStatus" class="form-label">Update Status</label>
                            <select class="form-select rounded-pill" id="newPermissionStatus" name="new_status" required>
                                <option value="Pending">Pending</option>
                                <option value="Approved">Approved</option>
                                <option value="Rejected">Rejected</option>
                                <option value="Revoked">Revoked</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="adminNotes" class="form-label">Admin Notes (Optional)</label>
                            <textarea class="form-control rounded-3" id="adminNotes" name="notes" rows="3"></textarea>
                        </div>
                        <div class="d-grid">
                            <button type="submit" class="btn btn-primary rounded-pill">Update Permission</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        // JavaScript to populate the modal fields when "Manage" button is clicked
        var managePermissionModal = document.getElementById('managePermissionModal');
        managePermissionModal.addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget; // Button that triggered the modal
            var permissionId = button.getAttribute('data-permission-id');
            var dataSource = button.getAttribute('data-data-source');
            var requester = button.getAttribute('data-requester');
            var permissionType = button.getAttribute('data-permission-type');
            var notes = button.getAttribute('data-notes');
            var currentStatus = button.getAttribute('data-current-status');

            var modalPermissionId = managePermissionModal.querySelector('#modalPermissionId');
            var modalDataSource = managePermissionModal.querySelector('#modalDataSource');
            var modalRequester = managePermissionModal.querySelector('#modalRequester');
            var modalPermissionType = managePermissionModal.querySelector('#modalPermissionType');
            var modalRequestNotes = managePermissionModal.querySelector('#modalRequestNotes');
            var newPermissionStatusSelect = managePermissionModal.querySelector('#newPermissionStatus');

            modalPermissionId.value = permissionId;
            modalDataSource.value = dataSource;
            modalRequester.value = requester;
            modalPermissionType.value = permissionType;
            modalRequestNotes.value = notes;
            newPermissionStatusSelect.value = currentStatus; // Set default selected option to current status
            // Clear admin notes field for new entry
            managePermissionModal.querySelector('#adminNotes').value = '';
        });
    </script>

    <!-- Footer -->
    <?php
    // Include Footer file for owner pages
    include_once("../includes/footer_admin.php");
    ?>  
</body>
</html>
