<?php
// This script handles the supervisor's approval queue.
// It relies on $conn (database connection) and $_SESSION['user_id'] being available.

$status_message = '';
$supervisor_id = $_SESSION['user_id'] ?? 1; // Supervisor ID (the logged-in user)

// Helper function for consistent status badge styling
if (!function_exists('get_status_badge')) {
    function get_status_badge($status) {
        $class = 'status-badge';
        switch ($status) {
            case 'Pending':
                $class .= ' status-pending';
                break;
            case 'Approved':
                $class .= ' status-approved';
                break;
            case 'Rejected':
                $class .= ' status-rejected';
                break;
            default:
                $class .= ' status-default';
        }
        return "<span class='{$class}'>" . htmlspecialchars($status) . "</span>";
    }
}

// --- 1. Handle Approval/Rejection Action (POST) ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['report_id'], $_POST['action'])) {
    $report_id = (int)$_POST['report_id'];
    $action = $_POST['action'];
    
    $new_status = '';
    if ($action === 'Approve') {
        $new_status = 'Approved';
    } elseif ($action === 'Reject') {
        $new_status = 'Rejected';
    }

    if ($report_id > 0 && !empty($new_status)) {
        // CRITICAL UPDATE: Update status ONLY if it's currently Pending AND the supervisor ID matches.
        $sql_update = "UPDATE monthly_activities 
                       SET status = ? 
                       WHERE report_id = ? AND supervisor_user_id = ? AND status = 'Pending'";
        
        if ($stmt_update = $conn->prepare($sql_update)) {
            $stmt_update->bind_param("sii", $new_status, $report_id, $supervisor_id);
            
            if ($stmt_update->execute()) {
                if ($stmt_update->affected_rows > 0) {
                    // Success message - the report will disappear from this list on reload
                    $status_message = "<div class='alert alert-success'>Report ID {$report_id} has been **{$new_status}**. It will now be removed from this pending list.</div>";
                } else {
                    $status_message = "<div class='alert alert-warning'>Report ID {$report_id} was not updated. It may have already been processed.</div>";
                }
            } else {
                $status_message = "<div class='alert alert-error'>Error executing update: " . $stmt_update->error . "</div>";
            }
            $stmt_update->close();
        } else {
            $status_message = "<div class='alert alert-error'>Database error during preparation: " . $conn->error . "</div>";
        }
    }
}


// --- 2. Fetch ONLY Pending Reports for the Supervisor ---
$pending_reports = [];
$sql_fetch = "
    SELECT 
        ma.report_id, 
        ma.report_month, 
        ma.title, 
        ma.activity_description, 
        ma.submission_date,
        u.username AS submitter_name,
        u.user_id AS submitter_id
    FROM 
        monthly_activities ma
    JOIN 
        users u ON ma.submitted_by_user_id = u.user_id
    WHERE 
        ma.supervisor_user_id = ? 
        AND ma.status = 'Pending' /* <<< CRITICAL FILTER: ONLY SHOW PENDING */
    ORDER BY 
        ma.submission_date ASC
";

if ($stmt_fetch = $conn->prepare($sql_fetch)) {
    $stmt_fetch->bind_param("i", $supervisor_id);
    $stmt_fetch->execute();
    $result_fetch = $stmt_fetch->get_result();
    while ($row = $result_fetch->fetch_assoc()) {
        $pending_reports[] = $row;
    }
    $stmt_fetch->close();
}
// --- 3. HTML and Display ---
?>
<style>
    /* Shared Status Badge Styling (should match create_activity_report.php) */
    .status-badge {
        display: inline-block;
        padding: 5px 10px;
        border-radius: 12px;
        font-weight: bold;
        font-size: 0.85em;
        text-transform: capitalize;
        min-width: 80px;
        text-align: center;
    }
    .status-pending { background-color: #f1c40f; color: #333; } /* Yellow */
    .status-approved { background-color: #2ecc71; color: white; } /* Green */
    .status-rejected { background-color: #e74c3c; color: white; } /* Red */
    .status-default { background-color: #bdc3c7; color: #333; } /* Gray */

    /* Table Styling */
    .data-table th, .data-table td {
        padding: 12px 15px;
        border-bottom: 1px solid #ddd;
    }
    .pending-table th {
        background-color: #34495e; /* Dark blue/gray */
        color: white;
    }
    /* Action Buttons */
    .action-button {
        border: none;
        padding: 8px 12px;
        border-radius: 5px;
        font-weight: bold;
        transition: background-color 0.2s;
        cursor: pointer;
        margin: 2px;
    }
    .btn-approve { background-color: #2ecc71; color: white; }
    .btn-reject { background-color: #e74c3c; color: white; }
    .btn-view { background-color: #3498db; color: white; }

    /* Modal Styles */
    .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.4); }
    .modal-content { background-color: #fefefe; margin: 10% auto; padding: 20px; border: 1px solid #888; width: 80%; max-width: 700px; border-radius: 8px; box-shadow: 0 5px 15px rgba(0,0,0,0.3); position: relative; }
    .close { color: #aaa; float: right; font-size: 28px; font-weight: bold; line-height: 1; }
    .close:hover, .close:focus { color: #000; text-decoration: none; cursor: pointer; }
    .modal-detail-item { margin-bottom: 10px; padding: 5px; border-bottom: 1px dashed #eee; }
    .modal-detail-item strong { display: inline-block; width: 120px; color: #34495e; }
    #modal-description { white-space: pre-wrap; padding: 10px; border: 1px solid #ddd; border-radius: 4px; background-color: #f9f9f9; }
</style>

<div class="form-card">
    <h3><i class="fas fa-clipboard-list"></i> Activity Reports Pending Your Approval (<?php echo count($pending_reports); ?>)</h3>
    <?php echo $status_message; ?>

    <?php if (!empty($pending_reports)): ?>
        <table class="data-table pending-table" style="width: 100%; border-collapse: collapse;">
            <thead>
                <tr>
                    <th style="width: 5%;">ID</th>
                    <th style="width: 15%;">Date</th>
                    <th style="width: 25%;">Title</th>
                    <th style="width: 20%;">Submitted By</th>
                    <th style="width: 15%;">Submitted On</th>
                    <th style="width: 20%; text-align: center;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($pending_reports as $report): 
                    $report_data_json = json_encode([
                        'id' => $report['report_id'],
                        'date' => $report['report_month'],
                        'title' => $report['title'],
                        'submitter' => $report['submitter_name'],
                        'submission_date' => substr($report['submission_date'], 0, 16),
                        'description' => $report['description'] 
                    ]);
                ?>
                    <tr id="report-row-<?php echo $report['report_id']; ?>">
                        <td><?php echo htmlspecialchars($report['report_id']); ?></td>
                        <td><?php echo htmlspecialchars($report['report_month']); ?></td>
                        <td><?php echo htmlspecialchars($report['title']); ?></td>
                        <td><?php echo htmlspecialchars($report['submitter_name']); ?></td> 
                        <td><?php echo htmlspecialchars(substr($report['submission_date'], 0, 16)); ?></td>
                        <td style="text-align: center;">
                            <button type="button" 
                                onclick='showReportModal(<?php echo $report_data_json; ?>)'
                                class="action-button btn-view">
                                <i class="fas fa-eye"></i> View
                            </button>
                            
                            <form method="POST" style="display: inline-block; margin: 0;">
                                <input type="hidden" name="report_id" value="<?php echo $report['report_id']; ?>">
                                <input type="hidden" name="action" value="Approve">
                                <button type="submit" class="action-button btn-approve">
                                    <i class="fas fa-check-circle"></i> Approve
                                </button>
                            </form>

                            <form method="POST" style="display: inline-block; margin: 0;">
                                <input type="hidden" name="report_id" value="<?php echo $report['report_id']; ?>">
                                <input type="hidden" name="action" value="Reject">
                                <button type="submit" class="action-button btn-reject">
                                    <i class="fas fa-times-circle"></i> Reject
                                </button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php else: ?>
        <p class="alert alert-info">You currently have **no activity reports** pending your approval.</p>
    <?php endif; ?>
</div>

<!-- The Report Details Modal Structure and Script remain the same -->
<div id="reportModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeReportModal()">&times;</span>
        <h3 id="modal-title" style="border-bottom: 2px solid #3498db; padding-bottom: 10px;">Report Details</h3>
        <div class="modal-detail-item">
            <strong>Report ID:</strong> <span id="modal-id"></span>
        </div>
        <div class="modal-detail-item">
            <strong>Submitted By:</strong> <span id="modal-submitter"></span>
        </div>
        <div class="modal-detail-item">
            <strong>Date:</strong> <span id="modal-date"></span>
        </div>
        <div class="modal-detail-item">
            <strong>Submission Time:</strong> <span id="modal-submitted-on"></span>
        </div>
        <h4 style="margin-top: 20px; color: #34495e;">Activity Description:</h4>
        <div id="modal-description"></div>
        <div style="text-align: right; margin-top: 20px;">
            <button type="button" onclick="closeReportModal()" class="action-button btn-view" style="background-color: #bdc3c7;">
                Close
            </button>
        </div>
    </div>
</div>

<script>
    const modal = document.getElementById('reportModal');
    const modalTitle = document.getElementById('modal-title');
    const modalId = document.getElementById('modal-id');
    const modalSubmitter = document.getElementById('modal-submitter');
    const modalDate = document.getElementById('modal-date');
    const modalSubmittedOn = document.getElementById('modal-submitted-on');
    const modalDescription = document.getElementById('modal-description');
    
    function showReportModal(reportData) {
        modalTitle.textContent = 'Report Details: ' + reportData.title;
        modalId.textContent = reportData.id;
        modalSubmitter.textContent = reportData.submitter;
        modalDate.textContent = reportData.date;
        modalSubmittedOn.textContent = reportData.submission_date;
        modalDescription.textContent = reportData.description;
        modal.style.display = 'block';
    }

    function closeReportModal() {
        modal.style.display = 'none';
    }

    window.onclick = function(event) {
        if (event.target == modal) {
            closeReportModal();
        }
    }
</script>
