<?php
/**
 * ============================================================================
 * extension/diseases.php
 * Disease Management & Verification
 * National/Regional officers can verify reports, all can view
 * ============================================================================
 */

require_once __DIR__ . '/includes/base.php';

// Get filter parameters
$status = $_GET['status'] ?? 'all';
$severity = $_GET['severity'] ?? 'all';
$crop = $_GET['crop_type'] ?? 'all';

// Build query based on user level
$whereConditions = ["1=1"];
$params = [];

// Location-based filtering
if ($userLevel === 'regional' && $extensionSystem->userAssignment['region_id']) {
    $whereConditions[] = "u.region_id = ?";
    $params[] = $extensionSystem->userAssignment['region_id'];
} elseif ($userLevel === 'district' && $extensionSystem->userAssignment['district_id']) {
    $whereConditions[] = "u.district_id = ?";
    $params[] = $extensionSystem->userAssignment['district_id'];
} elseif ($userLevel === 'subcounty' && $extensionSystem->userAssignment['subcounty_id']) {
    $whereConditions[] = "u.subcounty_id = ?";
    $params[] = $extensionSystem->userAssignment['subcounty_id'];
} elseif ($userLevel === 'parish' && $extensionSystem->userAssignment['parish_id']) {
    $whereConditions[] = "u.parish_id = ?";
    $params[] = $extensionSystem->userAssignment['parish_id'];
} elseif ($userLevel === 'village' && $extensionSystem->userAssignment['village_id']) {
    $whereConditions[] = "u.village_id = ?";
    $params[] = $extensionSystem->userAssignment['village_id'];
}

// Status filter
if ($status !== 'all') {
    $whereConditions[] = "dr.status = ?";
    $params[] = $status;
}

// Severity filter
if ($severity !== 'all') {
    $whereConditions[] = "dr.severity = ?";
    $params[] = $severity;
}

// Crop filter
if ($crop !== 'all') {
    $whereConditions[] = "dr.crop_type = ?";
    $params[] = $crop;
}

$sql = "SELECT dr.*, 
        u.full_name as reporter_name, u.phone_number as reporter_phone,
        r.region_name, d.district_name, s.subcounty_name, p.parish_name, v.village_name,
        cd.disease_name, cd.scientific_name,
        verifier.full_name as verifier_name
        FROM disease_reports dr
        INNER JOIN users u ON dr.user_id = u.id
        LEFT JOIN regions r ON u.region_id = r.id
        LEFT JOIN districts d ON u.district_id = d.id
        LEFT JOIN subcounties s ON u.subcounty_id = s.id
        LEFT JOIN parishes p ON u.parish_id = p.id
        LEFT JOIN villages v ON u.village_id = v.id
        LEFT JOIN crop_diseases cd ON dr.disease_id = cd.id
        LEFT JOIN users verifier ON dr.verified_by = verifier.id
        WHERE " . implode(' AND ', $whereConditions) . "
        ORDER BY dr.created_at DESC";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$reports = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get unique crop types for filter
$cropSql = "SELECT DISTINCT crop_type FROM disease_reports ORDER BY crop_type";
$cropStmt = $db->prepare($cropSql);
$cropStmt->execute();
$cropTypes = $cropStmt->fetchAll(PDO::FETCH_COLUMN);

// Statistics
$statsSql = "SELECT 
    COUNT(*) as total_reports,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_count,
    SUM(CASE WHEN status = 'verified' THEN 1 ELSE 0 END) as verified_count,
    SUM(CASE WHEN severity = 'critical' THEN 1 ELSE 0 END) as critical_count,
    SUM(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 ELSE 0 END) as recent_count
    FROM disease_reports dr
    INNER JOIN users u ON dr.user_id = u.id
    WHERE " . implode(' AND ', $whereConditions);
$statsStmt = $db->prepare($statsSql);
$statsStmt->execute($params);
$stats = $statsStmt->fetch(PDO::FETCH_ASSOC);

$pageTitle = 'Disease Management - AIMS Extension';
$breadcrumbs = [
    ['title' => 'Disease Reports', 'url' => '']
];

renderExtensionHeader($pageTitle, $breadcrumbs);
?>

<style>
.disease-card {
    border-left: 4px solid #dc2626;
    transition: all 0.3s ease;
}

.disease-card:hover {
    transform: translateX(5px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.severity-badge {
    padding: 4px 12px;
    border-radius: 12px;
    font-size: 0.75rem;
    font-weight: 600;
}

.severity-low { background: #dcfce7; color: #166534; }
.severity-medium { background: #fef3c7; color: #92400e; }
.severity-high { background: #fee2e2; color: #991b1b; }
.severity-critical { background: #fecaca; color: #7f1d1d; }

.image-gallery {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 10px;
}

.image-gallery img {
    width: 100%;
    height: 100px;
    object-fit: cover;
    border-radius: 8px;
    cursor: pointer;
}
</style>

<div class="container-fluid py-4">
    <!-- Statistics Row -->
    <div class="row mb-4">
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stat-card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 small">Total Reports</p>
                            <h3 class="mb-0 fw-bold"><?php echo number_format($stats['total_reports']); ?></h3>
                        </div>
                        <div class="stat-icon bg-primary bg-opacity-10 text-primary">
                            <i class="bi bi-bug"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stat-card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 small">Pending Verification</p>
                            <h3 class="mb-0 fw-bold text-warning"><?php echo $stats['pending_count']; ?></h3>
                        </div>
                        <div class="stat-icon bg-warning bg-opacity-10 text-warning">
                            <i class="bi bi-clock"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stat-card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 small">Critical Cases</p>
                            <h3 class="mb-0 fw-bold text-danger"><?php echo $stats['critical_count']; ?></h3>
                        </div>
                        <div class="stat-icon bg-danger bg-opacity-10 text-danger">
                            <i class="bi bi-exclamation-triangle"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stat-card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 small">This Week</p>
                            <h3 class="mb-0 fw-bold text-info"><?php echo $stats['recent_count']; ?></h3>
                        </div>
                        <div class="stat-icon bg-info bg-opacity-10 text-info">
                            <i class="bi bi-calendar-week"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters & Actions -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <form method="GET" class="row g-3">
                        <div class="col-md-3">
                            <select name="status" class="form-select" onchange="this.form.submit()">
                                <option value="all" <?php echo $status === 'all' ? 'selected' : ''; ?>>All Status</option>
                                <option value="pending" <?php echo $status === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                <option value="verified" <?php echo $status === 'verified' ? 'selected' : ''; ?>>Verified</option>
                                <option value="resolved" <?php echo $status === 'resolved' ? 'selected' : ''; ?>>Resolved</option>
                                <option value="false_alarm" <?php echo $status === 'false_alarm' ? 'selected' : ''; ?>>False Alarm</option>
                            </select>
                        </div>

                        <div class="col-md-3">
                            <select name="severity" class="form-select" onchange="this.form.submit()">
                                <option value="all" <?php echo $severity === 'all' ? 'selected' : ''; ?>>All Severity</option>
                                <option value="low" <?php echo $severity === 'low' ? 'selected' : ''; ?>>Low</option>
                                <option value="medium" <?php echo $severity === 'medium' ? 'selected' : ''; ?>>Medium</option>
                                <option value="high" <?php echo $severity === 'high' ? 'selected' : ''; ?>>High</option>
                                <option value="critical" <?php echo $severity === 'critical' ? 'selected' : ''; ?>>Critical</option>
                            </select>
                        </div>

                        <div class="col-md-3">
                            <select name="crop_type" class="form-select" onchange="this.form.submit()">
                                <option value="all">All Crops</option>
                                <?php foreach ($cropTypes as $cropType): ?>
                                <option value="<?php echo e($cropType); ?>" <?php echo $crop === $cropType ? 'selected' : ''; ?>>
                                    <?php echo ucfirst($cropType); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-3">
                            <a href="<?php echo APP_URL; ?>/extension/diseases.php" class="btn btn-outline-secondary w-100">
                                <i class="bi bi-arrow-clockwise"></i> Reset
                            </a>
                        </div>
                    </form>
                </div>

                <div class="col-md-4 text-md-end mt-3 mt-md-0">
                    <a href="<?php echo APP_URL; ?>/extension/report-disease.php" class="btn btn-danger">
                        <i class="bi bi-plus-circle"></i> Report Disease
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Disease Reports -->
    <div class="row">
        <?php if (empty($reports)): ?>
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center py-5">
                    <i class="bi bi-inbox" style="font-size: 4rem; color: #d1d5db;"></i>
                    <h5 class="mt-3 text-muted">No disease reports found</h5>
                    <p class="text-muted">Change filters or report a new disease</p>
                </div>
            </div>
        </div>
        <?php else: ?>
        <?php foreach ($reports as $report): ?>
        <div class="col-lg-6 mb-4">
            <div class="card disease-card border-0 shadow-sm h-100">
                <div class="card-body">
                    <!-- Header -->
                    <div class="d-flex justify-content-between align-items-start mb-3">
                        <div>
                            <h6 class="mb-1 fw-bold">
                                <?php echo e($report['disease_name'] ?? 'Unknown Disease'); ?>
                            </h6>
                            <small class="text-muted">
                                <i class="bi bi-person"></i> <?php echo e($report['reporter_name']); ?>
                            </small>
                        </div>
                        <div class="text-end">
                            <span class="severity-badge severity-<?php echo $report['severity']; ?>">
                                <?php echo strtoupper($report['severity']); ?>
                            </span>
                        </div>
                    </div>

                    <!-- Crop & Location -->
                    <div class="mb-3">
                        <div class="row g-2">
                            <div class="col-6">
                                <small class="text-muted d-block">Crop Type</small>
                                <strong><?php echo ucfirst(e($report['crop_type'])); ?></strong>
                            </div>
                            <div class="col-6">
                                <small class="text-muted d-block">Location</small>
                                <strong><?php echo e($report['village_name'] ?? $report['parish_name'] ?? $report['subcounty_name'] ?? $report['district_name']); ?></strong>
                            </div>
                        </div>
                    </div>

                    <!-- Description -->
                    <p class="mb-3 small"><?php echo e($report['description']); ?></p>

                    <!-- Images -->
                    <?php if (!empty($report['images'])): 
                        $images = json_decode($report['images'], true);
                        if ($images && is_array($images)):
                    ?>
                    <div class="image-gallery mb-3">
                        <?php foreach (array_slice($images, 0, 4) as $image): ?>
                        <img src="<?php echo APP_URL . '/' . e($image); ?>" 
                             alt="Disease photo"
                             onclick="viewImage(this.src)">
                        <?php endforeach; ?>
                    </div>
                    <?php endif; endif; ?>

                    <!-- Status & Actions -->
                    <div class="d-flex justify-content-between align-items-center pt-3 border-top">
                        <div>
                            <span class="badge bg-<?php echo getStatusBadge($report['status']); ?>">
                                <?php echo ucfirst(str_replace('_', ' ', $report['status'])); ?>
                            </span>
                            <?php if ($report['verified_by']): ?>
                            <small class="text-muted d-block mt-1">
                                Verified by <?php echo e($report['verifier_name']); ?>
                            </small>
                            <?php endif; ?>
                        </div>
                        
                        <div>
                            <button class="btn btn-sm btn-outline-primary" onclick="viewReport(<?php echo $report['id']; ?>)">
                                <i class="bi bi-eye"></i> View
                            </button>
                            
                            <?php if ($report['status'] === 'pending' && in_array($userLevel, ['national', 'regional', 'district'])): ?>
                            <button class="btn btn-sm btn-success" onclick="verifyReport(<?php echo $report['id']; ?>)">
                                <i class="bi bi-check-circle"></i> Verify
                            </button>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <div class="card-footer bg-light">
                    <small class="text-muted">
                        <i class="bi bi-clock"></i> Reported <?php echo timeAgo($report['created_at']); ?>
                    </small>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<!-- View Report Modal -->
<div class="modal fade" id="viewReportModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Disease Report Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="reportDetails">
                <!-- Loaded via AJAX -->
            </div>
        </div>
    </div>
</div>

<!-- Verify Report Modal -->
<div class="modal fade" id="verifyModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="verifyForm">
                <div class="modal-header">
                    <h5 class="modal-title">Verify Disease Report</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="report_id" id="verify_report_id">
                    
                    <div class="mb-3">
                        <label class="form-label">Verification Status</label>
                        <select name="status" class="form-select" required>
                            <option value="verified">Verified - Disease Confirmed</option>
                            <option value="false_alarm">False Alarm - Not a Disease</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Disease Identification (Optional)</label>
                        <select name="disease_id" class="form-select">
                            <option value="">-- Select if identified --</option>
                            <?php
                            $diseaseSql = "SELECT id, disease_name, scientific_name FROM crop_diseases WHERE is_published = 1 ORDER BY disease_name";
                            $diseaseStmt = $db->prepare($diseaseSql);
                            $diseaseStmt->execute();
                            $diseases = $diseaseStmt->fetchAll(PDO::FETCH_ASSOC);
                            foreach ($diseases as $disease):
                            ?>
                            <option value="<?php echo $disease['id']; ?>">
                                <?php echo e($disease['disease_name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Notes</label>
                        <textarea name="notes" class="form-control" rows="3" placeholder="Verification notes, recommendations..."></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">Verify Report</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function viewReport(reportId) {
    showLoading();
    $.get('<?php echo APP_URL; ?>/api/extension.php', {
        action: 'get_disease_report',
        report_id: reportId
    }, function(response) {
        hideLoading();
        if (response.success) {
            $('#reportDetails').html(response.html);
            new bootstrap.Modal('#viewReportModal').show();
        } else {
            showToast(response.message, 'error');
        }
    }).fail(function() {
        hideLoading();
        showToast('Failed to load report details', 'error');
    });
}

function verifyReport(reportId) {
    $('#verify_report_id').val(reportId);
    new bootstrap.Modal('#verifyModal').show();
}

$('#verifyForm').on('submit', function(e) {
    e.preventDefault();
    
    showLoading();
    $.post('<?php echo APP_URL; ?>/api/extension.php', 
        $(this).serialize() + '&action=verify_disease_report',
        function(response) {
            hideLoading();
            if (response.success) {
                showToast(response.message, 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                showToast(response.message, 'error');
            }
        }
    ).fail(function() {
        hideLoading();
        showToast('Verification failed', 'error');
    });
});

function viewImage(src) {
    Swal.fire({
        imageUrl: src,
        imageAlt: 'Disease photo',
        showCloseButton: true,
        showConfirmButton: false
    });
}
</script>

<?php renderExtensionFooter(); ?>