<?php
/**
 * Fraud Reports Management Page
 * For Admin, Payment Admin, Village Chairman, Land Officer
 */

define('APP_RUNNING', true);
require_once 'db_connect.php';
require_once 'includes/auth.php';

initSecureSession();

if(!isAuthenticated() || !validateSession()) {
    header('Location: login');
    exit;
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role'] ?? 'user';

// Only allow admin, payment_admin, village_chairman, land_officer
$allowed_roles = ['admin', 'payment_admin', 'village_chairman', 'land_officer'];
if (!in_array($user_role, $allowed_roles)) {
    header('Location: dashboard');
    exit;
}

// Check if table exists
$tableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'land_fraud_reports'");
if (mysqli_num_rows($tableCheck) == 0) {
    mysqli_query($conn, "CREATE TABLE land_fraud_reports (
        id INT AUTO_INCREMENT PRIMARY KEY,
        land_id INT NOT NULL,
        reporter_name VARCHAR(255),
        reporter_phone VARCHAR(50) NOT NULL,
        report_details TEXT NOT NULL,
        status ENUM('pending', 'investigating', 'resolved', 'dismissed') DEFAULT 'pending',
        admin_notes TEXT,
        handled_by INT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_land_id (land_id),
        INDEX idx_status (status)
    )");
}

// Handle status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $report_id = intval($_POST['report_id'] ?? 0);

    if ($action === 'update_status' && $report_id > 0) {
        $new_status = mysqli_real_escape_string($conn, $_POST['status'] ?? '');
        $admin_notes = mysqli_real_escape_string($conn, $_POST['admin_notes'] ?? '');

        if (in_array($new_status, ['pending', 'investigating', 'resolved', 'dismissed'])) {
            mysqli_query($conn, "UPDATE land_fraud_reports SET status = '$new_status', admin_notes = '$admin_notes', handled_by = $user_id WHERE id = $report_id");

            // Get report details for notification
            $reportQuery = mysqli_query($conn, "SELECT fr.*, l.user_id as owner_id, l.land_name, l.village_id
                                                FROM land_fraud_reports fr
                                                JOIN lands l ON fr.land_id = l.id
                                                WHERE fr.id = $report_id");
            if ($reportRow = mysqli_fetch_assoc($reportQuery)) {
                $landName = $reportRow['land_name'] ?? 'Land #' . $reportRow['land_id'];
                $ownerId = $reportRow['owner_id'];
                $villageId = intval($reportRow['village_id'] ?? 0);

                // Notify land owner about status change
                $statusLabels = [
                    'pending' => 'Inasubiri / Pending',
                    'investigating' => 'Inachunguzwa / Investigating',
                    'resolved' => 'Imekamilika / Resolved',
                    'dismissed' => 'Imekataliwa / Dismissed'
                ];
                $statusLabel = $statusLabels[$new_status] ?? $new_status;

                $notifTitle = "Hali ya Ripoti Imebadilika / Report Status Updated";
                $notifMessage = "Ripoti ya shaka kuhusu ardhi yako \"{$landName}\" imefikia hali: {$statusLabel}. ";
                if ($new_status === 'resolved') {
                    $notifMessage .= "Uchunguzi umekamilika. / Investigation completed.";
                } elseif ($new_status === 'dismissed') {
                    $notifMessage .= "Ripoti haikuwa na msingi. / Report was unfounded.";
                } elseif ($new_status === 'investigating') {
                    $notifMessage .= "Tunachunguza suala hili. / We are investigating this matter.";
                }
                $notifTitle = mysqli_real_escape_string($conn, $notifTitle);
                $notifMessage = mysqli_real_escape_string($conn, $notifMessage);

                mysqli_query($conn, "INSERT INTO cbc_notifications (user_id, notification_type, title, message, land_id, metadata, created_at)
                                     VALUES ($ownerId, 'fraud_report_update', '$notifTitle', '$notifMessage', {$reportRow['land_id']}, '{\"report_id\": $report_id, \"status\": \"$new_status\"}', NOW())");

                // If forwarded to village, notify village officials
                if ($new_status === 'investigating' && $villageId > 0) {
                    $officialQuery = mysqli_query($conn, "SELECT id FROM users WHERE village_id = $villageId AND role IN ('village_chairman', 'land_officer') AND status = 'active'");
                    while ($official = mysqli_fetch_assoc($officialQuery)) {
                        $officialTitle = "Ripoti ya Mgogoro Inachunguzwa / Dispute Being Investigated";
                        $officialMessage = "Ripoti ya uuzwaji mara mbili kwa ardhi \"{$landName}\" sasa inachunguzwa. Tafadhali shiriki katika uchunguzi.";
                        $officialTitle = mysqli_real_escape_string($conn, $officialTitle);
                        $officialMessage = mysqli_real_escape_string($conn, $officialMessage);

                        mysqli_query($conn, "INSERT INTO cbc_notifications (user_id, notification_type, title, message, land_id, metadata, created_at)
                                             VALUES ({$official['id']}, 'fraud_investigation', '$officialTitle', '$officialMessage', {$reportRow['land_id']}, '{\"report_id\": $report_id}', NOW())");
                    }
                }
            }

            header('Location: fraud-reports?success=Status updated');
            exit;
        }
    }
}

// Filter
$status_filter = $_GET['status'] ?? 'all';
$where = "1=1";

// Village officials only see reports from their village
if (in_array($user_role, ['village_chairman', 'land_officer'])) {
    $userVillage = mysqli_fetch_assoc(mysqli_query($conn, "SELECT village_id FROM users WHERE id = $user_id"));
    $userVillageId = intval($userVillage['village_id'] ?? 0);
    if ($userVillageId > 0) {
        $where .= " AND l.village_id = $userVillageId";
    }
}

if ($status_filter !== 'all' && in_array($status_filter, ['pending', 'investigating', 'resolved', 'dismissed'])) {
    $where .= " AND fr.status = '$status_filter'";
}

// Get reports
$reports = mysqli_query($conn, "
    SELECT fr.*,
           l.land_name, l.village_id,
           u.full_name as owner_name, u.phone as owner_phone,
           h.full_name as handled_by_name,
           r.name as region_name, d.name as district_name, v.name as village_name
    FROM land_fraud_reports fr
    JOIN lands l ON fr.land_id = l.id
    JOIN users u ON l.user_id = u.id
    LEFT JOIN users h ON fr.handled_by = h.id
    LEFT JOIN regions r ON l.region_id = r.id
    LEFT JOIN districts d ON l.district_id = d.id
    LEFT JOIN villages v ON l.village_id = v.id
    WHERE $where
    ORDER BY
        CASE fr.status
            WHEN 'pending' THEN 1
            WHEN 'investigating' THEN 2
            WHEN 'resolved' THEN 3
            WHEN 'dismissed' THEN 4
        END,
        fr.created_at DESC
");

// Get counts
$countQuery = mysqli_query($conn, "SELECT
    COUNT(*) as total,
    SUM(CASE WHEN fr.status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN fr.status = 'investigating' THEN 1 ELSE 0 END) as investigating,
    SUM(CASE WHEN fr.status = 'resolved' THEN 1 ELSE 0 END) as resolved,
    SUM(CASE WHEN fr.status = 'dismissed' THEN 1 ELSE 0 END) as dismissed
    FROM land_fraud_reports fr
    JOIN lands l ON fr.land_id = l.id
    WHERE " . str_replace("AND fr.status", "AND 1", $where));
$counts = mysqli_fetch_assoc($countQuery);

function getStatusBadge($status) {
    $badges = [
        'pending' => ['label' => 'Inasubiri', 'class' => 'badge-warning', 'icon' => 'fa-clock'],
        'investigating' => ['label' => 'Inachunguzwa', 'class' => 'badge-info', 'icon' => 'fa-search'],
        'resolved' => ['label' => 'Imekamilika', 'class' => 'badge-success', 'icon' => 'fa-check-circle'],
        'dismissed' => ['label' => 'Imekataliwa', 'class' => 'badge-secondary', 'icon' => 'fa-times-circle']
    ];
    return $badges[$status] ?? ['label' => ucfirst($status), 'class' => 'badge-secondary', 'icon' => 'fa-question'];
}

function generateLandId($id) {
    return 'LS-' . str_pad($id, 5, '0', STR_PAD_LEFT);
}
?>
<!DOCTYPE html>
<html lang="sw">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ripoti za Uuzwaji Mara Mbili - LandSecure</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/font-awesome/css/all.min.css">
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .app-main {
            margin-left: 280px;
            padding: 24px;
            min-height: 100vh;
            background: #f0f2f5;
        }

        @media (max-width: 1024px) {
            .app-main { margin-left: 0; padding-top: 80px; }
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
            flex-wrap: wrap;
            gap: 16px;
        }

        .page-title {
            font-size: 28px;
            font-weight: 700;
            color: #1e293b;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .page-title i {
            color: #dc2626;
        }

        .stats-row {
            display: flex;
            gap: 16px;
            margin-bottom: 24px;
            flex-wrap: wrap;
        }

        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            flex: 1;
            min-width: 150px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.04);
            display: flex;
            align-items: center;
            gap: 16px;
            text-decoration: none;
            transition: all 0.3s;
            border: 2px solid transparent;
        }

        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        }

        .stat-card.active {
            border-color: #667eea;
        }

        .stat-icon {
            width: 50px;
            height: 50px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }

        .stat-icon.warning { background: rgba(245, 158, 11, 0.1); color: #f59e0b; }
        .stat-icon.info { background: rgba(59, 130, 246, 0.1); color: #3b82f6; }
        .stat-icon.success { background: rgba(34, 197, 94, 0.1); color: #22c55e; }
        .stat-icon.secondary { background: rgba(100, 116, 139, 0.1); color: #64748b; }

        .stat-value {
            font-size: 28px;
            font-weight: 700;
            color: #1e293b;
        }

        .stat-label {
            font-size: 13px;
            color: #64748b;
        }

        .report-card {
            background: white;
            border-radius: 16px;
            padding: 24px;
            margin-bottom: 16px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.04);
            border-left: 4px solid #f59e0b;
        }

        .report-card.status-pending { border-left-color: #f59e0b; }
        .report-card.status-investigating { border-left-color: #3b82f6; }
        .report-card.status-resolved { border-left-color: #22c55e; }
        .report-card.status-dismissed { border-left-color: #64748b; }

        .report-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 16px;
            flex-wrap: wrap;
            gap: 12px;
        }

        .report-land {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .land-icon {
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 20px;
        }

        .land-info h4 {
            font-size: 16px;
            font-weight: 600;
            color: #1e293b;
            margin: 0 0 4px;
        }

        .land-info p {
            font-size: 13px;
            color: #64748b;
            margin: 0;
        }

        .badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 12px;
            border-radius: 8px;
            font-size: 12px;
            font-weight: 600;
        }

        .badge-warning { background: rgba(245, 158, 11, 0.1); color: #f59e0b; }
        .badge-info { background: rgba(59, 130, 246, 0.1); color: #3b82f6; }
        .badge-success { background: rgba(34, 197, 94, 0.1); color: #22c55e; }
        .badge-secondary { background: rgba(100, 116, 139, 0.1); color: #64748b; }
        .badge-danger { background: rgba(239, 68, 68, 0.1); color: #ef4444; }

        .report-details {
            background: #f8fafc;
            border-radius: 12px;
            padding: 16px;
            margin-bottom: 16px;
        }

        .report-details h5 {
            font-size: 12px;
            font-weight: 600;
            color: #64748b;
            text-transform: uppercase;
            margin-bottom: 8px;
        }

        .report-details p {
            font-size: 14px;
            color: #1e293b;
            margin: 0;
            line-height: 1.6;
        }

        .report-meta {
            display: flex;
            gap: 24px;
            flex-wrap: wrap;
            margin-bottom: 16px;
        }

        .meta-item {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 13px;
            color: #64748b;
        }

        .meta-item i {
            width: 20px;
            text-align: center;
        }

        .report-actions {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }

        .btn-action {
            padding: 10px 20px;
            border-radius: 10px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            border: none;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            text-decoration: none;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }

        .btn-outline {
            background: white;
            border: 1px solid #e2e8f0;
            color: #64748b;
        }

        .btn-success {
            background: linear-gradient(135deg, #22c55e, #16a34a);
            color: white;
        }

        .btn-warning {
            background: linear-gradient(135deg, #f59e0b, #d97706);
            color: white;
        }

        .btn-danger {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: white;
        }

        .location-info {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            margin-top: 8px;
        }

        .location-tag {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 4px 10px;
            background: #f1f5f9;
            border-radius: 6px;
            font-size: 12px;
            color: #475569;
        }

        .empty-state {
            text-align: center;
            padding: 80px 20px;
            color: #64748b;
        }

        .empty-state i {
            font-size: 80px;
            color: #cbd5e1;
            margin-bottom: 24px;
        }

        .empty-state h3 {
            font-size: 20px;
            font-weight: 600;
            color: #475569;
            margin-bottom: 8px;
        }

        /* Modal */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal-overlay.show {
            display: flex;
        }

        .modal-content {
            background: white;
            border-radius: 20px;
            width: 100%;
            max-width: 500px;
            max-height: 90vh;
            overflow-y: auto;
            margin: 20px;
        }

        .modal-header {
            padding: 24px;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            font-size: 18px;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            color: #64748b;
            cursor: pointer;
        }

        .modal-body {
            padding: 24px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            font-size: 13px;
            font-weight: 600;
            color: #475569;
            margin-bottom: 8px;
        }

        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px 14px;
            border: 1px solid #e2e8f0;
            border-radius: 10px;
            font-size: 14px;
        }

        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
        }

        .modal-footer {
            padding: 16px 24px;
            border-top: 1px solid #e2e8f0;
            display: flex;
            gap: 12px;
            justify-content: flex-end;
        }

        .alert {
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 24px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .alert-success {
            background: #dcfce7;
            border: 1px solid #86efac;
            color: #166534;
        }

        .owner-info {
            background: #eff6ff;
            border: 1px solid #bfdbfe;
            border-radius: 10px;
            padding: 12px;
            margin-top: 12px;
        }

        .owner-info h5 {
            font-size: 12px;
            font-weight: 600;
            color: #1e40af;
            margin-bottom: 8px;
        }

        .owner-info .info-row {
            display: flex;
            justify-content: space-between;
            font-size: 13px;
            padding: 4px 0;
        }

        .owner-info .info-row span:first-child {
            color: #64748b;
        }

        .owner-info .info-row span:last-child {
            color: #1e293b;
            font-weight: 500;
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="app-main">
        <div class="page-header">
            <h1 class="page-title">
                <i class="fas fa-exclamation-triangle"></i>
                Ripoti za Uuzwaji Mara Mbili
            </h1>
        </div>

        <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success">
            <i class="fas fa-check-circle"></i>
            <span><?php echo htmlspecialchars($_GET['success']); ?></span>
        </div>
        <?php endif; ?>

        <!-- Stats -->
        <div class="stats-row">
            <a href="fraud-reports" class="stat-card <?php echo $status_filter === 'all' ? 'active' : ''; ?>">
                <div class="stat-icon warning"><i class="fas fa-list"></i></div>
                <div>
                    <div class="stat-value"><?php echo intval($counts['total']); ?></div>
                    <div class="stat-label">Jumla / Total</div>
                </div>
            </a>
            <a href="fraud-reports?status=pending" class="stat-card <?php echo $status_filter === 'pending' ? 'active' : ''; ?>">
                <div class="stat-icon warning"><i class="fas fa-clock"></i></div>
                <div>
                    <div class="stat-value"><?php echo intval($counts['pending']); ?></div>
                    <div class="stat-label">Inasubiri / Pending</div>
                </div>
            </a>
            <a href="fraud-reports?status=investigating" class="stat-card <?php echo $status_filter === 'investigating' ? 'active' : ''; ?>">
                <div class="stat-icon info"><i class="fas fa-search"></i></div>
                <div>
                    <div class="stat-value"><?php echo intval($counts['investigating']); ?></div>
                    <div class="stat-label">Inachunguzwa / Investigating</div>
                </div>
            </a>
            <a href="fraud-reports?status=resolved" class="stat-card <?php echo $status_filter === 'resolved' ? 'active' : ''; ?>">
                <div class="stat-icon success"><i class="fas fa-check-circle"></i></div>
                <div>
                    <div class="stat-value"><?php echo intval($counts['resolved']); ?></div>
                    <div class="stat-label">Imekamilika / Resolved</div>
                </div>
            </a>
            <a href="fraud-reports?status=dismissed" class="stat-card <?php echo $status_filter === 'dismissed' ? 'active' : ''; ?>">
                <div class="stat-icon secondary"><i class="fas fa-times-circle"></i></div>
                <div>
                    <div class="stat-value"><?php echo intval($counts['dismissed']); ?></div>
                    <div class="stat-label">Imekataliwa / Dismissed</div>
                </div>
            </a>
        </div>

        <!-- Reports List -->
        <?php if (mysqli_num_rows($reports) == 0): ?>
        <div class="empty-state">
            <i class="fas fa-clipboard-check"></i>
            <h3>Hakuna Ripoti / No Reports</h3>
            <p>There are no fraud reports <?php echo $status_filter !== 'all' ? "with status '$status_filter'" : ''; ?> at the moment.</p>
        </div>
        <?php else: ?>

        <?php while ($report = mysqli_fetch_assoc($reports)):
            $statusBadge = getStatusBadge($report['status']);
        ?>
        <div class="report-card status-<?php echo $report['status']; ?>">
            <div class="report-header">
                <div class="report-land">
                    <div class="land-icon"><i class="fas fa-map"></i></div>
                    <div class="land-info">
                        <h4><?php echo htmlspecialchars($report['land_name'] ?? 'Land'); ?> <small style="color: #64748b;">(<?php echo generateLandId($report['land_id']); ?>)</small></h4>
                        <div class="location-info">
                            <?php if ($report['region_name']): ?>
                            <span class="location-tag"><i class="fas fa-globe-africa"></i> <?php echo htmlspecialchars($report['region_name']); ?></span>
                            <?php endif; ?>
                            <?php if ($report['district_name']): ?>
                            <span class="location-tag"><i class="fas fa-city"></i> <?php echo htmlspecialchars($report['district_name']); ?></span>
                            <?php endif; ?>
                            <?php if ($report['village_name']): ?>
                            <span class="location-tag"><i class="fas fa-home"></i> <?php echo htmlspecialchars($report['village_name']); ?></span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <span class="badge <?php echo $statusBadge['class']; ?>">
                    <i class="fas <?php echo $statusBadge['icon']; ?>"></i>
                    <?php echo $statusBadge['label']; ?>
                </span>
            </div>

            <!-- Owner Info (visible to admins) -->
            <?php if (in_array($user_role, ['admin', 'payment_admin'])): ?>
            <div class="owner-info">
                <h5><i class="fas fa-user"></i> Mmiliki wa Ardhi / Land Owner</h5>
                <div class="info-row">
                    <span>Jina / Name:</span>
                    <span><?php echo htmlspecialchars($report['owner_name']); ?></span>
                </div>
                <div class="info-row">
                    <span>Simu / Phone:</span>
                    <span><?php echo htmlspecialchars($report['owner_phone']); ?></span>
                </div>
            </div>
            <?php endif; ?>

            <div class="report-details">
                <h5><i class="fas fa-comment-alt"></i> Maelezo ya Ripoti / Report Details</h5>
                <p><?php echo nl2br(htmlspecialchars($report['report_details'])); ?></p>
            </div>

            <?php if ($report['admin_notes']): ?>
            <div class="report-details" style="background: #fef3c7; border: 1px solid #fcd34d;">
                <h5><i class="fas fa-sticky-note"></i> Maelezo ya Admin / Admin Notes</h5>
                <p><?php echo nl2br(htmlspecialchars($report['admin_notes'])); ?></p>
            </div>
            <?php endif; ?>

            <div class="report-meta">
                <div class="meta-item">
                    <i class="fas fa-calendar-alt"></i>
                    <span>Iliripotiwa: <?php echo date('d M Y, H:i', strtotime($report['created_at'])); ?></span>
                </div>
                <?php if ($report['handled_by_name']): ?>
                <div class="meta-item">
                    <i class="fas fa-user-shield"></i>
                    <span>Anayeshughulikia: <?php echo htmlspecialchars($report['handled_by_name']); ?></span>
                </div>
                <?php endif; ?>
                <div class="meta-item">
                    <i class="fas fa-hashtag"></i>
                    <span>Report #<?php echo $report['id']; ?></span>
                </div>
            </div>

            <div class="report-actions">
                <a href="view-land/<?php echo $report['land_id']; ?>" class="btn-action btn-outline">
                    <i class="fas fa-eye"></i> Tazama Ardhi
                </a>
                <a href="verify-land?id=<?php echo $report['land_id']; ?>" target="_blank" class="btn-action btn-outline">
                    <i class="fas fa-external-link-alt"></i> Ukurasa wa Uthibitisho
                </a>
                <?php if ($report['status'] !== 'resolved' && $report['status'] !== 'dismissed'): ?>
                <button class="btn-action btn-primary" onclick="openStatusModal(<?php echo $report['id']; ?>, '<?php echo $report['status']; ?>', '<?php echo addslashes($report['admin_notes'] ?? ''); ?>')">
                    <i class="fas fa-edit"></i> Badilisha Hali
                </button>
                <?php endif; ?>
            </div>
        </div>
        <?php endwhile; ?>

        <?php endif; ?>
    </main>

    <!-- Status Update Modal -->
    <div class="modal-overlay" id="statusModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="fas fa-edit"></i> Badilisha Hali ya Ripoti</h3>
                <button class="modal-close" onclick="closeModal()">&times;</button>
            </div>
            <form method="POST" action="">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update_status">
                    <input type="hidden" name="report_id" id="modalReportId">

                    <div class="form-group">
                        <label><i class="fas fa-flag"></i> Hali Mpya / New Status</label>
                        <select name="status" id="modalStatus" required>
                            <option value="pending">Inasubiri / Pending</option>
                            <option value="investigating">Inachunguzwa / Investigating</option>
                            <option value="resolved">Imekamilika / Resolved</option>
                            <option value="dismissed">Imekataliwa / Dismissed</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label><i class="fas fa-sticky-note"></i> Maelezo / Notes</label>
                        <textarea name="admin_notes" id="modalNotes" rows="4" placeholder="Andika maelezo ya uchunguzi au uamuzi..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-action btn-outline" onclick="closeModal()">Ghairi / Cancel</button>
                    <button type="submit" class="btn-action btn-primary">Hifadhi / Save</button>
                </div>
            </form>
        </div>
    </div>

    <script>
    function openStatusModal(reportId, currentStatus, currentNotes) {
        document.getElementById('modalReportId').value = reportId;
        document.getElementById('modalStatus').value = currentStatus;
        document.getElementById('modalNotes').value = currentNotes;
        document.getElementById('statusModal').classList.add('show');
    }

    function closeModal() {
        document.getElementById('statusModal').classList.remove('show');
    }

    // Close modal when clicking outside
    document.getElementById('statusModal').addEventListener('click', function(e) {
        if (e.target === this) {
            closeModal();
        }
    });
    </script>
</body>
</html>
