<?php
/**
 * Received Reports Page
 * GHAMECC Choir Management Platform
 */

// Include authentication functions
require_once '../includes/auth.php';

// Include database functions
require_once '../config/database.php';

// Require login
requireLogin();

// Get user information and role
$userId = $_SESSION['user_id'] ?? null;
$userInfo = fetchRow("SELECT u.*, r.role_key, r.name as role_name 
                     FROM users u 
                     JOIN roles r ON u.role_id = r.id 
                     WHERE u.id = ?", [$userId]);

// Log user info for debugging
logInfo("User attempting to access reports/received.php", [
    'user_id' => $userId,
    'role' => $userInfo['role_key'] ?? 'unknown',
    'session_society_id' => $_SESSION['society_id'] ?? 'not set',
    'session_circuit_id' => $_SESSION['circuit_id'] ?? 'not set',
    'session_diocese_id' => $_SESSION['diocese_id'] ?? 'not set'
]);

// Determine which reports the user can receive based on their role
$receivableReports = [];
$userLevel = '';
$userEntityId = 0;
$userEntityName = 'Unknown Entity';
$receivedReports = [];

// Get user's associated entity (society, circuit, diocese)
if (in_array($userInfo['role_key'] ?? '', ['choirmaster', 'society_secretary', 'society_treasurer'])) {
    $userLevel = 'society';
    
    // First check if user has society_id directly in the session
    if (isset($_SESSION['society_id']) && !empty($_SESSION['society_id'])) {
        $societyId = $_SESSION['society_id'];
        $userEntity = fetchRow("SELECT s.*, c.name as circuit_name, c.id as circuit_id, d.name as diocese_name, d.id as diocese_id 
                              FROM societies s
                              JOIN circuits c ON s.circuit_id = c.id 
                              JOIN dioceses d ON c.diocese_id = d.id 
                              WHERE s.id = ?", [$societyId]);
        
        logInfo("Retrieved society from session", [
            'society_id' => $societyId,
            'found_entity' => !empty($userEntity) ? 'yes' : 'no'
        ]);
    } else {
        // Check if society_id is in the user record
        $userSocietyId = $userInfo['society_id'] ?? null;
        
        if ($userSocietyId) {
            // Store in session for future use
            $_SESSION['society_id'] = $userSocietyId;
            
            $userEntity = fetchRow("SELECT s.*, c.name as circuit_name, c.id as circuit_id, d.name as diocese_name, d.id as diocese_id 
                                  FROM societies s
                                  JOIN circuits c ON s.circuit_id = c.id 
                                  JOIN dioceses d ON c.diocese_id = d.id 
                                  WHERE s.id = ?", [$userSocietyId]);
            
            logInfo("Retrieved society from user record", [
                'society_id' => $userSocietyId,
                'found_entity' => !empty($userEntity) ? 'yes' : 'no'
            ]);
        } else {
            // Fallback to checking via member association
            $memberQuery = "SELECT m.* FROM users u JOIN members m ON u.member_id = m.id WHERE u.id = ?";
            $memberInfo = fetchRow($memberQuery, [$userId]);
            
            logInfo("Retrieved member info for society lookup", [
                'user_id' => $userId,
                'member_id' => $memberInfo['id'] ?? 'not found',
                'society_id' => $memberInfo['society_id'] ?? 'not set'
            ]);
            
            if ($memberInfo && isset($memberInfo['society_id'])) {
                // Store society_id in session for future use
                $_SESSION['society_id'] = $memberInfo['society_id'];
                
                // Update user record with society_id
                executeQuery("UPDATE users SET society_id = ? WHERE id = ?", [$memberInfo['society_id'], $userId]);
                
                $userEntity = fetchRow("SELECT s.*, c.name as circuit_name, c.id as circuit_id, d.name as diocese_name, d.id as diocese_id 
                                      FROM societies s
                                      JOIN circuits c ON s.circuit_id = c.id 
                                      JOIN dioceses d ON c.diocese_id = d.id 
                                      WHERE s.id = ?", [$memberInfo['society_id']]);
                
                logInfo("Retrieved society from member association", [
                    'society_id' => $memberInfo['society_id'],
                    'found_entity' => !empty($userEntity) ? 'yes' : 'no'
                ]);
            } else {
                logError("Failed to find society for user", [
                    'user_id' => $userId,
                    'role' => $userInfo['role_key'] ?? 'unknown'
                ]);
            }
        }
    }
    
    if ($userEntity) {
        $userEntityId = $userEntity['id'];
        $userEntityName = $userEntity['name'];
        // Society users can receive reports from members of their society
        $receivableReports = [
            'member_reports' => [
                'title' => 'Member Reports',
                'query' => "SELECT r.*, u.full_name as submitted_by_name, rt.name as report_type_name
                          FROM reports r 
                          JOIN users u ON r.submitted_by = u.id
                          JOIN report_types rt ON r.report_type_id = rt.id
                          JOIN members m ON u.member_id = m.id
                          WHERE m.society_id = ? AND r.target_id = ? AND r.target_type = 'society'
                          ORDER BY r.created_at DESC",
                'params' => [$userEntityId, $userEntityId]
            ]
        ];
        $receivedReports = fetchRows($receivableReports['member_reports']['query'], $receivableReports['member_reports']['params']);
    }
} elseif (in_array($userInfo['role_key'] ?? '', ['circuit_chairman', 'circuit_secretary', 'circuit_dom', 'circuit_treasurer'])) {
    $userLevel = 'circuit';
    
    // First check if user has circuit_id directly in the session
    if (isset($_SESSION['circuit_id']) && !empty($_SESSION['circuit_id'])) {
        $circuitId = $_SESSION['circuit_id'];
        $userEntity = fetchRow("SELECT c.*, d.name as diocese_name, d.id as diocese_id 
                              FROM circuits c 
                              JOIN dioceses d ON c.diocese_id = d.id 
                              WHERE c.id = ?", [$circuitId]);
        
        logInfo("Retrieved circuit from session", [
            'circuit_id' => $circuitId,
            'found_entity' => $userEntity ? 'yes' : 'no'
        ]);
    } else {
        // Try to get circuit from member association
        $userEntity = fetchRow("SELECT c.*, d.name as diocese_name, d.id as diocese_id 
                              FROM members m 
                              JOIN circuits c ON m.circuit_id = c.id 
                              JOIN dioceses d ON c.diocese_id = d.id 
                              WHERE m.id = (SELECT member_id FROM users WHERE id = ?)", [$userId]);
    }
    
    if ($userEntity) {
        $userEntityId = $userEntity['id'];
        $userEntityName = $userEntity['name'];
        
        // Circuit users can receive reports from societies in their circuit
        // Updated query to match actual database schema
        $receivableReports = [
            'society_reports' => [
                'query' => "SELECT r.*, u.full_name as sender_name, s.name as sender_entity_name, 
                           'society' as sender_level, rt.name as report_type_name
                           FROM reports r 
                           JOIN users u ON r.submitted_by = u.id
                           JOIN report_types rt ON r.report_type_id = rt.id
                           JOIN societies s ON r.source_id = s.id AND r.source_type = 'society'
                           WHERE s.circuit_id = ? AND r.target_type = 'circuit' AND r.target_id = ?
                           ORDER BY r.created_at DESC",
                'params' => [$userEntityId, $userEntityId]
            ]
        ];
        
        // Fetch the reports
        $receivedReports = fetchRows($receivableReports['society_reports']['query'], $receivableReports['society_reports']['params']);
    }
} elseif (in_array($userInfo['role_key'] ?? '', ['diocesan_chairman', 'diocesan_secretary', 'diocesan_dom', 'diocesan_treasurer'])) {
    $userLevel = 'diocese';
    
    // First check if user has diocese_id directly in the session
    if (isset($_SESSION['diocese_id']) && !empty($_SESSION['diocese_id'])) {
        $dioceseId = $_SESSION['diocese_id'];
        $userEntity = fetchRow("SELECT * FROM dioceses WHERE id = ?", [$dioceseId]);
        
        logInfo("Retrieved diocese from session", [
            'diocese_id' => $dioceseId,
            'found_entity' => $userEntity ? 'yes' : 'no'
        ]);
    } else {
        // Try to get diocese from member association
        $userEntity = fetchRow("SELECT d.* 
                              FROM members m 
                              JOIN dioceses d ON m.diocese_id = d.id 
                              WHERE m.id = (SELECT member_id FROM users WHERE id = ?)", [$userId]);
    }
    
    if ($userEntity) {
        $userEntityId = $userEntity['id'];
        $userEntityName = $userEntity['name'];
        
        // Diocese users can receive reports from circuits in their diocese
        // Updated query to match actual database schema
        $receivableReports = [
            'circuit_reports' => [
                'query' => "SELECT r.*, u.full_name as sender_name, c.name as sender_entity_name, 
                           'circuit' as sender_level, rt.name as report_type_name
                           FROM reports r 
                           JOIN users u ON r.submitted_by = u.id
                           JOIN report_types rt ON r.report_type_id = rt.id
                           JOIN circuits c ON r.source_id = c.id AND r.source_type = 'circuit'
                           WHERE c.diocese_id = ? AND r.target_type = 'diocese' AND r.target_id = ?
                           ORDER BY r.created_at DESC",
                'params' => [$userEntityId, $userEntityId]
            ]
        ];
        
        // Fetch the reports
        $receivedReports = fetchRows($receivableReports['circuit_reports']['query'], $receivableReports['circuit_reports']['params']);
    }
} elseif (in_array($userInfo['role_key'] ?? '', ['admin'])) {
    $userLevel = 'connexional';
    $userEntityName = 'Connexional Office';
    
    // Admin/Connexional users receive reports from all dioceses
    $receivedReports = fetchRows("SELECT r.*, 
                                u.full_name as sender_name,
                                d.name as sender_entity_name,
                                'Diocese' as sender_level
                                FROM reports r
                                JOIN users u ON r.submitted_by = u.id
                                JOIN members m ON u.member_id = m.id
                                JOIN dioceses d ON m.diocese_id = d.id
                                WHERE r.target_type = 'connexional'
                                ORDER BY r.created_at DESC");
}

// Process report actions (approve, reject)
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && isset($_POST['report_id'])) {
    $action = $_POST['action'];
    $reportId = (int)$_POST['report_id'];
    $response = escapeString($_POST['response'] ?? '');
    
    // Validate report exists and belongs to this user's entity
    $report = fetchRow("SELECT * FROM reports WHERE id = $reportId AND target_type = '$userLevel' AND target_id = $userEntityId");
    
    if ($report) {
        if ($action === 'approve') {
            // Update report status
            $updateSql = "UPDATE reports SET status = 'approved', updated_at = NOW() WHERE id = $reportId";
            if (executeQuery($updateSql)) {
                // Add response if provided
                if (!empty($response)) {
                    $responseSql = "INSERT INTO report_responses (report_id, user_id, response_text, created_at) 
                                   VALUES ($reportId, $userId, '$response', NOW())";
                    executeQuery($responseSql);
                }
                $message = "Report has been approved successfully.";
                $messageType = "success";
            } else {
                $message = "Failed to approve report. Please try again.";
                $messageType = "danger";
            }
        } elseif ($action === 'reject') {
            // Require response for rejection
            if (empty($response)) {
                $message = "Please provide a reason for rejection.";
                $messageType = "warning";
            } else {
                // Update report status
                $updateSql = "UPDATE reports SET status = 'rejected', updated_at = NOW() WHERE id = $reportId";
                if (executeQuery($updateSql)) {
                    // Add response
                    $responseSql = "INSERT INTO report_responses (report_id, user_id, response_text, created_at) 
                                   VALUES ($reportId, $userId, '$response', NOW())";
                    executeQuery($responseSql);
                    $message = "Report has been rejected.";
                    $messageType = "success";
                } else {
                    $message = "Failed to reject report. Please try again.";
                    $messageType = "danger";
                }
            }
        } elseif ($action === 'respond') {
            // Add response
            if (!empty($response)) {
                $responseSql = "INSERT INTO report_responses (report_id, user_id, response_text, created_at) 
                               VALUES ($reportId, $userId, '$response', NOW())";
                if (executeQuery($responseSql)) {
                    $message = "Response has been added successfully.";
                    $messageType = "success";
                } else {
                    $message = "Failed to add response. Please try again.";
                    $messageType = "danger";
                }
            } else {
                $message = "Response cannot be empty.";
                $messageType = "warning";
            }
        }
    } else {
        $message = "Invalid report or you don't have permission to manage this report.";
        $messageType = "danger";
    }
}

// Set base path for includes
$basePath = '..';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Received Reports - GHAMECC Choir Management</title>
    
    <?php include '../includes/favicon.php'; ?>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <!-- Custom CSS -->
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <?php include '../includes/navbar.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include '../includes/sidebar.php'; ?>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">Received Reports</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="submit.php" class="btn btn-sm btn-outline-primary me-2">
                            <i class="fas fa-plus me-1"></i> Submit New Report
                        </a>
                        <a href="sent.php" class="btn btn-sm btn-outline-secondary">
                            <i class="fas fa-paper-plane me-1"></i> View Sent Reports
                        </a>
                    </div>
                </div>
                
                <!-- Alert Messages -->
                <?php if ($message): ?>
                    <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                        <?php echo $message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                
                <?php if (empty($userLevel) || $userEntityId === 0): ?>
                    <div class="alert alert-warning" role="alert">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        Your account is not properly configured to receive reports. Please contact the administrator.
                    </div>
                <?php else: ?>
                    <div class="card shadow mb-4">
                        <div class="card-header py-3 d-flex justify-content-between align-items-center">
                            <h6 class="m-0 font-weight-bold text-primary">Reports for <?php echo htmlspecialchars($userEntityName); ?></h6>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-bordered" id="reportsTable" width="100%" cellspacing="0">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Date</th>
                                            <th>From</th>
                                            <th>Type</th>
                                            <th>Subject</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($receivedReports as $report): ?>
                                            <tr>
                                                <td><?php echo $report['id']; ?></td>
                                                <td><?php echo date('M d, Y', strtotime($report['created_at'])); ?></td>
                                                <td>
                                                    <?php echo htmlspecialchars($report['sender_name']); ?>
                                                    <div class="small text-muted"><?php echo htmlspecialchars($report['sender_entity_name'] ?? $report['sender_level']); ?></div>
                                                </td>
                                                <td>
                                                    <?php 
                                                    // Get report type from report_type_id
                                                    $reportTypeName = '';
                                                    $reportTypeQuery = "SELECT name FROM report_types WHERE id = ?";
                                                    $reportTypeResult = fetchRow($reportTypeQuery, [$report['report_type_id'] ?? 0]);
                                                    if ($reportTypeResult) {
                                                        $reportTypeName = $reportTypeResult['name'];
                                                    }
                                                    
                                                    echo htmlspecialchars($reportTypeName);
                                                    ?>
                                                </td>
                                                <td><?php echo htmlspecialchars($report['title'] ?? ''); ?></td>
                                                <td>
                                                    <?php if ($report['status'] === 'pending'): ?>
                                                        <span class="badge bg-warning">Pending</span>
                                                    <?php elseif ($report['status'] === 'approved'): ?>
                                                        <span class="badge bg-success">Approved</span>
                                                    <?php elseif ($report['status'] === 'rejected'): ?>
                                                        <span class="badge bg-danger">Rejected</span>
                                                    <?php elseif ($report['status'] === 'completed'): ?>
                                                        <span class="badge bg-info">Completed</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <button type="button" class="btn btn-sm btn-primary view-report" data-bs-toggle="modal" data-bs-target="#viewReportModal" data-report-id="<?php echo $report['id']; ?>">
                                                        <i class="fas fa-eye"></i>
                                                    </button>
                                                    
                                                    <?php if ($report['status'] === 'pending'): ?>
                                                        <button type="button" class="btn btn-sm btn-success approve-report" data-bs-toggle="modal" data-bs-target="#approveReportModal" data-report-id="<?php echo $report['id']; ?>">
                                                            <i class="fas fa-check"></i>
                                                        </button>
                                                        <button type="button" class="btn btn-sm btn-danger reject-report" data-bs-toggle="modal" data-bs-target="#rejectReportModal" data-report-id="<?php echo $report['id']; ?>">
                                                            <i class="fas fa-times"></i>
                                                        </button>
                                                    <?php else: ?>
                                                        <button type="button" class="btn btn-sm btn-info respond-report" data-bs-toggle="modal" data-bs-target="#respondReportModal" data-report-id="<?php echo $report['id']; ?>">
                                                            <i class="fas fa-reply"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </main>
        </div>
    </div>
    
    <!-- View Report Modal -->
    <div class="modal fade" id="viewReportModal" tabindex="-1" aria-labelledby="viewReportModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="viewReportModalLabel">View Report</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="reportDetails">
                        <div class="text-center">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p>Loading report details...</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Approve Report Modal -->
    <div class="modal fade" id="approveReportModal" tabindex="-1" aria-labelledby="approveReportModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="approveReportModalLabel">Approve Report</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" action="">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="approve">
                        <input type="hidden" name="report_id" id="approveReportId">
                        
                        <p>Are you sure you want to approve this report?</p>
                        
                        <div class="mb-3">
                            <label for="approveResponse" class="form-label">Response (Optional)</label>
                            <textarea class="form-control" id="approveResponse" name="response" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">Approve</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Reject Report Modal -->
    <div class="modal fade" id="rejectReportModal" tabindex="-1" aria-labelledby="rejectReportModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="rejectReportModalLabel">Reject Report</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" action="">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="reject">
                        <input type="hidden" name="report_id" id="rejectReportId">
                        
                        <div class="mb-3">
                            <label for="rejectResponse" class="form-label">Reason for Rejection *</label>
                            <textarea class="form-control" id="rejectResponse" name="response" rows="3" required></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-danger">Reject</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Respond to Report Modal -->
    <div class="modal fade" id="respondReportModal" tabindex="-1" aria-labelledby="respondReportModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="respondReportModalLabel">Respond to Report</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" action="">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="respond">
                        <input type="hidden" name="report_id" id="respondReportId">
                        
                        <div class="mb-3">
                            <label for="responseText" class="form-label">Your Response *</label>
                            <textarea class="form-control" id="responseText" name="response" rows="5" required></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Send Response</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    <!-- Custom JS -->
    <script>
        $(document).ready(function() {
            // Initialize DataTable
            $('#reportsTable').DataTable({
                order: [[0, 'desc']]
            });
            
            // Handle view report button
            $('.view-report').on('click', function() {
                const reportId = $(this).data('report-id');
                $('#reportDetails').html('<div class="text-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div><p>Loading report details...</p></div>');
                
                // Determine which AJAX handler to use based on user role
                <?php if (in_array($userInfo['role_key'], ['circuit_secretary', 'circuit_chairman', 'circuit_music_director', 'circuit_treasurer'])): ?>
                const ajaxUrl = 'ajax/get_circuit_report_details.php';
                <?php elseif (in_array($userInfo['role_key'], ['diocesan_secretary', 'diocesan_chairman', 'diocesan_music_director', 'diocesan_treasurer'])): ?>
                const ajaxUrl = 'ajax/get_diocesan_report_details.php';
                <?php else: ?>
                const ajaxUrl = 'ajax/get_report_details.php';
                <?php endif; ?>
                
                // Fetch report details via AJAX
                $.ajax({
                    url: ajaxUrl,
                    type: 'GET',
                    data: { report_id: reportId },
                    success: function(response) {
                        $('#reportDetails').html(response);
                    },
                    error: function() {
                        $('#reportDetails').html('<div class="alert alert-danger">Failed to load report details. Please try again.</div>');
                    }
                });
            });
            
            // Set report ID for action modals
            $('.approve-report').on('click', function() {
                $('#approveReportId').val($(this).data('report-id'));
            });
            
            $('.reject-report').on('click', function() {
                $('#rejectReportId').val($(this).data('report-id'));
            });
            
            $('.respond-report').on('click', function() {
                $('#respondReportId').val($(this).data('report-id'));
            });
        });
    </script>
</body>
</html>
