<?php
// data_owner/manage_permissions.php
session_start();
require_once '../config.php';
require_once '../includes/auth.php';
require_once '../classes/DataSource.php'; // For permission methods

// Ensure only Data Owners can access this page
redirect_if_not_role('Data Owner');

$data_source_manager = new DataSource($pdo);
$user_id = $_SESSION['user_id'];
$owner_person_id = $_SESSION['person_id'];

$action = $_GET['action'] ?? 'list';
$permission_id = $_GET['id'] ?? null;

// Handle form submissions for updating permission status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action_type']) && $_POST['action_type'] === 'update_permission') {
    $permission_id_to_update = filter_var($_POST['permission_id'], FILTER_SANITIZE_NUMBER_INT);
    $new_status = trim($_POST['new_status']);
    $notes = trim($_POST['notes'] ?? '');

    // Basic validation
    if (empty($permission_id_to_update) || !in_array($new_status, ['Approved', 'Rejected', 'Revoked'])) {
        set_message("Invalid request to update permission.", "danger");
        header("Location: manage_permissions.php");
        exit();
    }

    // You might want to add a check here to ensure the data owner is indeed the owner of the data source
    // related to this permission_id, to prevent tampering.
    // This would involve fetching the permission request and then checking the data source's fkisp_id_of.

    if ($data_source_manager->updatePermissionStatus($permission_id_to_update, $new_status, $user_id, $notes)) {
        set_message("Permission request updated successfully!", "success");
    } else {
        set_message("Failed to update permission request.", "danger");
    }
    header("Location: manage_permissions.php");
    exit();
}

$pending_requests = $data_source_manager->getPermissionRequestsForOwner($owner_person_id, 'Pending');
$all_requests = $data_source_manager->getPermissionRequestsForOwner($owner_person_id); // All statuses
?>
<!DOCTYPE html>
<html lang="en">
<!-- Header -->
<?php
// Include header file for admin pages
include_once("../includes/header_owner.php");
?>
<body>
    <div class="wrapper">
        <!-- Sidebar -->
        <?php
        // Include header file for admin pages
        include_once("../includes/nav_owner.php");
        ?>

        <!-- Page 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="#"> Permissions</a>
                    <div class="d-flex">
                        <span class="navbar-text me-3">
                            Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>!
                        </span>
                    </div>
                </div>
            </nav>

            <?php if (isset($_SESSION['message'])): ?>
                <div class="alert alert-<?= $_SESSION['message_type'] ?> alert-dismissible fade show rounded" role="alert">
                    <?= $_SESSION['message'] ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php
                unset($_SESSION['message']);
                unset($_SESSION['message_type']);
                ?>
            <?php endif; ?>

            <h3 class="mb-3">Pending Requests</h3>
            <div class="card shadow-sm rounded mb-4">
                <div class="card-body">
                    <?php if (!empty($pending_requests)): ?>
                        <div class="table-responsive">
                            <table class="table table-hover table-striped">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Data Source</th>
                                        <th>Requested By</th>
                                        <th>Permission Type</th>
                                        <th>Requested Date</th>
                                        <th>Notes</th>
                                        <th>Proof</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($pending_requests as $req): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($req['pkdspsdsp_id']) ?></td>
                                            <td><?= htmlspecialchars($req['dspsds_title_en']) ?></td>
                                            <td><?= htmlspecialchars($req['isp_firstname_en'] . ' ' . $req['isp_lastname_en']) ?></td>
                                            <td><span class="badge bg-info"><?= htmlspecialchars($req['dspsdsp_permission']) ?></span></td>
                                            <td><?= date('Y-m-d H:i', strtotime($req['dspsdsp_reg_datetime'])) ?></td>
                                            <td>
                                                <?php
                                                    $notes = $req['dspsdsp_notes'] ?? '';
                                                    echo $notes !== ''
                                                        ? nl2br(htmlspecialchars($notes))
                                                        : '<span class="text-muted">—</span>';
                                                ?>
                                            </td>
                                            <td>
                                                <?php if (!empty($req['dspsdsp_proof_path'])): ?>
                                                    <?php
                                                        $proofPath = $req['dspsdsp_proof_path'];
                                                        $isExternal = preg_match('/^https?:\\/\\//i', $proofPath) === 1;
                                                        $cleanPath = ltrim($proofPath, '/');
                                                        $linkTarget = $isExternal ? $proofPath : '../uploads/' . $cleanPath;
                                                    ?>
                                                    <a href="<?= 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>
                                                <form action="manage_permissions.php" method="POST" class="d-inline">
                                                    <input type="hidden" name="action_type" value="update_permission">
                                                    <input type="hidden" name="permission_id" value="<?= htmlspecialchars($req['pkdspsdsp_id']) ?>">
                                                    <input type="hidden" name="new_status" value="Approved">
                                                    <button type="submit" class="btn btn-sm btn-success rounded me-1" title="Approve">
                                                        <i class="fas fa-check"></i>
                                                    </button>
                                                </form>
                                                <form action="manage_permissions.php" method="POST" class="d-inline">
                                                    <input type="hidden" name="action_type" value="update_permission">
                                                    <input type="hidden" name="permission_id" value="<?= htmlspecialchars($req['pkdspsdsp_id']) ?>">
                                                    <input type="hidden" name="new_status" value="Rejected">
                                                    <button type="submit" class="btn btn-sm btn-danger rounded" title="Reject">
                                                        <i class="fas fa-times"></i>
                                                    </button>
                                                </form>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-info rounded mb-0">No pending permission requests.</div>
                    <?php endif; ?>
                </div>
            </div>

            <h3 class="mb-3 mt-5">All Permission Requests</h3>
            <div class="card shadow-sm rounded">
                <div class="card-body">
                    <?php if (!empty($all_requests)): ?>
                        <div class="table-responsive">
                            <table class="table table-hover table-striped">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Data Source</th>
                                        <th>Requested By</th>
                                        <th>Permission Type</th>
                                        <th>Status</th>
                                        <th>Requested Date</th>
                                        <th>Notes</th>
                                        <th>Proof</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($all_requests as $req): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($req['pkdspsdsp_id']) ?></td>
                                            <td><?= htmlspecialchars($req['dspsds_title_en']) ?></td>
                                            <td><?= htmlspecialchars($req['isp_firstname_en'] . ' ' . $req['isp_lastname_en']) ?></td>
                                            <td><span class="badge bg-info"><?= htmlspecialchars($req['dspsdsp_permission']) ?></span></td>
                                            <td>
                                                <span class="badge <?= ($req['dspsdsp_status'] == 'Approved' ? 'bg-success' : ($req['dspsdsp_status'] == 'Pending' ? 'bg-warning' : 'bg-danger')) ?>">
                                                    <?= htmlspecialchars($req['dspsdsp_status']) ?>
                                                </span>
                                            </td>
                                            <td><?= date('Y-m-d H:i', strtotime($req['dspsdsp_reg_datetime'])) ?></td>
                                            <td>
                                                <?php
                                                    $notes = $req['dspsdsp_notes'] ?? '';
                                                    echo $notes !== ''
                                                        ? nl2br(htmlspecialchars($notes))
                                                        : '<span class="text-muted">—</span>';
                                                ?>
                                            </td>
                                            <td>
                                                <?php if (!empty($req['dspsdsp_proof_path'])): ?>
                                                    <?php
                                                        $proofPath = $req['dspsdsp_proof_path'];
                                                        $isExternal = preg_match('/^https?:\\/\\//i', $proofPath) === 1;
                                                        $cleanPath = ltrim($proofPath, '/');
                                                        $linkTarget = $isExternal ? $proofPath : '../uploads/' . $cleanPath;
                                                    ?>
                                                    <a href="<?= 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>
                                                <?php if ($req['dspsdsp_status'] == 'Approved'): ?>
                                                    <form action="manage_permissions.php" method="POST" class="d-inline">
                                                        <input type="hidden" name="action_type" value="update_permission">
                                                        <input type="hidden" name="permission_id" value="<?= htmlspecialchars($req['pkdspsdsp_id']) ?>">
                                                        <input type="hidden" name="new_status" value="Revoked">
                                                        <button type="submit" class="btn btn-sm btn-secondary rounded" title="Revoke" onclick="return confirm('Are you sure you want to revoke this permission?');">
                                                            <i class="fas fa-ban"></i> Revoke
                                                        </button>
                                                    </form>
                                                <?php else: ?>
                                                    <span class="text-muted">No action</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-info rounded mb-0">No permission requests found.</div>
                    <?php endif; ?>
                </div>
            </div>

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