<?php
/**
 * ============================================================================
 * learning/diseases.php - Crop Diseases & Pest Management
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

$pageTitle = 'Diseases & Pests';
$userId = getUserId();

// Get database connection
$database = new Database();
$db = $database->getConnection();

// Get filter parameters
$crop_filter = isset($_GET['crop']) ? $_GET['crop'] : 'all';
$category_filter = isset($_GET['category']) ? $_GET['category'] : 'all';
$severity_filter = isset($_GET['severity']) ? $_GET['severity'] : 'all';

// Build query
$sql = "SELECT * FROM crop_diseases WHERE is_published = 1";
$params = [];

if ($crop_filter != 'all') {
    $sql .= " AND crop_type = ?";
    $params[] = $crop_filter;
}

if ($category_filter != 'all') {
    $sql .= " AND category = ?";
    $params[] = $category_filter;
}

if ($severity_filter != 'all') {
    $sql .= " AND severity_level = ?";
    $params[] = $severity_filter;
}

$sql .= " ORDER BY severity_level DESC, crop_type, disease_name";

try {
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $diseases = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $diseases = [];
    error_log("Error fetching diseases: " . $e->getMessage());
}

// Get crop types for filter
try {
    $crops_sql = "SELECT DISTINCT crop_type FROM crop_diseases WHERE is_published = 1 ORDER BY crop_type";
    $crops_stmt = $db->query($crops_sql);
    $available_crops = $crops_stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (PDOException $e) {
    $available_crops = [];
}

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<div class="container-fluid py-4">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                <div>
                    <h2 class="mb-1">
                        <i class="bi bi-bug text-danger"></i> Crop Diseases & Pests
                    </h2>
                    <p class="text-muted mb-0">Identify, prevent, and treat crop diseases</p>
                </div>
                <div class="d-flex gap-2">
                    <a href="<?php echo APP_URL; ?>/learning/" class="btn btn-outline-primary">
                        <i class="bi bi-arrow-left"></i> Back
                    </a>
                    <button class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#reportDiseaseModal">
                        <i class="bi bi-exclamation-triangle"></i> Report Disease
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Stats -->
    <div class="row mb-4">
        <div class="col-md-3 col-6 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body text-center">
                    <div class="text-danger mb-2">
                        <i class="bi bi-bug" style="font-size: 2rem;"></i>
                    </div>
                    <h3 class="mb-0"><?php echo count($diseases); ?></h3>
                    <small class="text-muted">Total Diseases</small>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-6 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body text-center">
                    <div class="text-warning mb-2">
                        <i class="bi bi-exclamation-triangle" style="font-size: 2rem;"></i>
                    </div>
                    <h3 class="mb-0">
                        <?php 
                        $critical = array_filter($diseases, function($d) { 
                            return $d['severity_level'] == 'critical' || $d['severity_level'] == 'high'; 
                        });
                        echo count($critical);
                        ?>
                    </h3>
                    <small class="text-muted">High Priority</small>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-6 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body text-center">
                    <div class="text-info mb-2">
                        <i class="bi bi-flower3" style="font-size: 2rem;"></i>
                    </div>
                    <h3 class="mb-0"><?php echo count($available_crops); ?></h3>
                    <small class="text-muted">Crops Covered</small>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-6 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body text-center">
                    <div class="text-success mb-2">
                        <i class="bi bi-shield-check" style="font-size: 2rem;"></i>
                    </div>
                    <h3 class="mb-0">
                        <?php 
                        $preventable = array_filter($diseases, function($d) { 
                            return !empty($d['prevention']); 
                        });
                        echo count($preventable);
                        ?>
                    </h3>
                    <small class="text-muted">Preventable</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <form method="GET" action="" class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label"><i class="bi bi-funnel"></i> Crop Type</label>
                            <select name="crop" class="form-select" onchange="this.form.submit()">
                                <option value="all" <?php echo $crop_filter == 'all' ? 'selected' : ''; ?>>All Crops</option>
                                <?php foreach ($available_crops as $crop): ?>
                                    <option value="<?php echo $crop; ?>" <?php echo $crop_filter == $crop ? 'selected' : ''; ?>>
                                        <?php echo ucwords(str_replace('_', ' ', $crop)); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><i class="bi bi-tag"></i> Category</label>
                            <select name="category" class="form-select" onchange="this.form.submit()">
                                <option value="all" <?php echo $category_filter == 'all' ? 'selected' : ''; ?>>All Categories</option>
                                <option value="fungal" <?php echo $category_filter == 'fungal' ? 'selected' : ''; ?>>Fungal</option>
                                <option value="bacterial" <?php echo $category_filter == 'bacterial' ? 'selected' : ''; ?>>Bacterial</option>
                                <option value="viral" <?php echo $category_filter == 'viral' ? 'selected' : ''; ?>>Viral</option>
                                <option value="pest" <?php echo $category_filter == 'pest' ? 'selected' : ''; ?>>Pest</option>
                                <option value="nutritional" <?php echo $category_filter == 'nutritional' ? 'selected' : ''; ?>>Nutritional</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><i class="bi bi-exclamation-circle"></i> Severity</label>
                            <select name="severity" class="form-select" onchange="this.form.submit()">
                                <option value="all" <?php echo $severity_filter == 'all' ? 'selected' : ''; ?>>All Levels</option>
                                <option value="low" <?php echo $severity_filter == 'low' ? 'selected' : ''; ?>>Low</option>
                                <option value="medium" <?php echo $severity_filter == 'medium' ? 'selected' : ''; ?>>Medium</option>
                                <option value="high" <?php echo $severity_filter == 'high' ? 'selected' : ''; ?>>High</option>
                                <option value="critical" <?php echo $severity_filter == 'critical' ? 'selected' : ''; ?>>Critical</option>
                            </select>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Disease Cards -->
    <div class="row">
        <?php if (!empty($diseases)): ?>
            <?php foreach ($diseases as $disease): ?>
                <div class="col-lg-6 col-xl-4 mb-4">
                    <div class="card border-0 shadow-sm h-100 disease-card">
                        <!-- Severity Badge -->
                        <div class="position-absolute top-0 end-0 m-3">
                            <?php
                            $severity_colors = [
                                'low' => 'success',
                                'medium' => 'warning',
                                'high' => 'danger',
                                'critical' => 'dark'
                            ];
                            $badge_color = $severity_colors[$disease['severity_level']] ?? 'secondary';
                            ?>
                            <span class="badge bg-<?php echo $badge_color; ?>">
                                <?php echo ucfirst($disease['severity_level']); ?> Severity
                            </span>
                        </div>

                        <div class="card-body">
                            <!-- Header -->
                            <div class="d-flex align-items-start mb-3">
                                <div class="flex-grow-1">
                                    <h5 class="card-title mb-1"><?php echo htmlspecialchars($disease['disease_name']); ?></h5>
                                    <?php if ($disease['scientific_name']): ?>
                                        <small class="text-muted fst-italic"><?php echo htmlspecialchars($disease['scientific_name']); ?></small>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Badges -->
                            <div class="mb-3">
                                <span class="badge bg-primary me-1">
                                    <i class="bi bi-flower3"></i> <?php echo ucwords(str_replace('_', ' ', $disease['crop_type'])); ?>
                                </span>
                                <span class="badge bg-info">
                                    <i class="bi bi-tag"></i> <?php echo ucfirst($disease['category']); ?>
                                </span>
                            </div>

                            <!-- Symptoms Preview -->
                            <div class="mb-3">
                                <h6 class="text-danger mb-2">
                                    <i class="bi bi-exclamation-circle"></i> Symptoms:
                                </h6>
                                <p class="text-muted small mb-0">
                                    <?php echo truncate(strip_tags($disease['symptoms']), 100); ?>
                                </p>
                            </div>

                            <!-- Affected Parts -->
                            <?php if ($disease['affected_parts']): ?>
                                <div class="mb-3">
                                    <small class="text-muted">
                                        <i class="bi bi-pin-map"></i> Affects: <?php echo htmlspecialchars($disease['affected_parts']); ?>
                                    </small>
                                </div>
                            <?php endif; ?>

                            <!-- Actions -->
                            <div class="d-grid">
                                <button class="btn btn-outline-danger" onclick="viewDisease(<?php echo $disease['id']; ?>)">
                                    <i class="bi bi-eye"></i> View Full Details
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="col-12">
                <div class="alert alert-info">
                    <i class="bi bi-info-circle"></i> No diseases found matching your filters.
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Prevention Tips -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0">
                        <i class="bi bi-shield-check"></i> General Prevention Tips
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <div class="d-flex">
                                <div class="flex-shrink-0">
                                    <i class="bi bi-check-circle-fill text-success fs-4"></i>
                                </div>
                                <div class="flex-grow-1 ms-3">
                                    <h6>Use Resistant Varieties</h6>
                                    <p class="text-muted mb-0">Plant disease-resistant crop varieties when available</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <div class="d-flex">
                                <div class="flex-shrink-0">
                                    <i class="bi bi-check-circle-fill text-success fs-4"></i>
                                </div>
                                <div class="flex-grow-1 ms-3">
                                    <h6>Crop Rotation</h6>
                                    <p class="text-muted mb-0">Rotate crops to break disease cycles</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <div class="d-flex">
                                <div class="flex-shrink-0">
                                    <i class="bi bi-check-circle-fill text-success fs-4"></i>
                                </div>
                                <div class="flex-grow-1 ms-3">
                                    <h6>Regular Scouting</h6>
                                    <p class="text-muted mb-0">Inspect crops regularly for early disease detection</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <div class="d-flex">
                                <div class="flex-shrink-0">
                                    <i class="bi bi-check-circle-fill text-success fs-4"></i>
                                </div>
                                <div class="flex-grow-1 ms-3">
                                    <h6>Proper Spacing</h6>
                                    <p class="text-muted mb-0">Maintain recommended spacing for good air circulation</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Disease Details Modal -->
<div class="modal fade" id="diseaseModal" tabindex="-1">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="diseaseModalTitle">Loading...</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="diseaseModalBody">
                <div class="text-center py-5">
                    <div class="spinner-border text-danger" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-success" onclick="bookmarkDisease()">
                    <i class="bi bi-bookmark"></i> Bookmark
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Report Disease Modal -->
<div class="modal fade" id="reportDiseaseModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-exclamation-triangle text-danger"></i> Report Disease Outbreak
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="reportDiseaseForm">
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="bi bi-info-circle"></i> Help us track disease outbreaks in your area
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Crop Type *</label>
                        <select class="form-select" name="crop_type" required>
                            <option value="">Select crop</option>
                            <option value="maize">Maize</option>
                            <option value="beans">Beans</option>
                            <option value="cassava">Cassava</option>
                            <option value="bananas">Bananas</option>
                            <option value="vegetables">Vegetables</option>
                            <option value="sugar_cane">Sugar Cane</option>
                            <option value="coffee">Coffee</option>
                            <option value="other">Other</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Location (Village/Parish)</label>
                        <input type="text" class="form-control" name="location" placeholder="Where is the outbreak?">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Description *</label>
                        <textarea class="form-control" name="description" rows="4" required 
                                  placeholder="Describe the symptoms you're seeing..."></textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Severity</label>
                        <select class="form-select" name="severity">
                            <option value="low">Low - Few plants affected</option>
                            <option value="medium" selected>Medium - Some plants affected</option>
                            <option value="high">High - Many plants affected</option>
                            <option value="critical">Critical - Most/all plants affected</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Upload Photos (Optional)</label>
                        <input type="file" class="form-control" name="images[]" accept="image/*" multiple>
                        <small class="text-muted">Upload clear photos of affected plants</small>
                    </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">
                        <i class="bi bi-send"></i> Submit Report
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
.disease-card {
    transition: all 0.3s ease;
}

.disease-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgba(0,0,0,0.15) !important;
}

.severity-indicator {
    width: 4px;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
}

.severity-low { background-color: #22c55e; }
.severity-medium { background-color: #eab308; }
.severity-high { background-color: #ef4444; }
.severity-critical { background-color: #991b1b; }
</style>

<script>
let currentDiseaseId = null;

function viewDisease(diseaseId) {
    currentDiseaseId = diseaseId;
    const modal = new bootstrap.Modal(document.getElementById('diseaseModal'));
    modal.show();
    
    // Fetch disease details
    $.get(APP_URL + '/ajax/get-disease.php', { id: diseaseId }, function(response) {
        if (response.success) {
            const disease = response.data;
            $('#diseaseModalTitle').html(disease.disease_name);
            
            let html = `
                <div class="disease-details">
                    ${disease.scientific_name ? `<p class="fst-italic text-muted">${disease.scientific_name}</p>` : ''}
                    
                    <div class="mb-4">
                        <span class="badge bg-primary">${disease.crop_type_formatted}</span>
                        <span class="badge bg-info">${disease.category_formatted}</span>
                        <span class="badge bg-${getSeverityColor(disease.severity_level)}">${disease.severity_level} Severity</span>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="info-section mb-4">
                                <h6 class="text-danger"><i class="bi bi-exclamation-circle"></i> Symptoms</h6>
                                <p>${disease.symptoms}</p>
                            </div>

                            <div class="info-section mb-4">
                                <h6 class="text-warning"><i class="bi bi-question-circle"></i> Causes</h6>
                                <p>${disease.causes}</p>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="info-section mb-4">
                                <h6 class="text-success"><i class="bi bi-shield-check"></i> Prevention</h6>
                                <p>${disease.prevention}</p>
                            </div>

                            <div class="info-section mb-4">
                                <h6 class="text-info"><i class="bi bi-heart-pulse"></i> Treatment</h6>
                                <p>${disease.treatment}</p>
                            </div>
                        </div>
                    </div>

                    ${disease.spread_method ? `
                        <div class="alert alert-warning">
                            <h6><i class="bi bi-arrow-repeat"></i> How it Spreads:</h6>
                            <p class="mb-0">${disease.spread_method}</p>
                        </div>
                    ` : ''}

                    ${disease.optimal_conditions ? `
                        <div class="alert alert-info">
                            <h6><i class="bi bi-thermometer-half"></i> Favorable Conditions:</h6>
                            <p class="mb-0">${disease.optimal_conditions}</p>
                        </div>
                    ` : ''}
                </div>
            `;
            
            $('#diseaseModalBody').html(html);
        } else {
            $('#diseaseModalBody').html('<div class="alert alert-danger">Failed to load disease details.</div>');
        }
    }).fail(function() {
        $('#diseaseModalBody').html('<div class="alert alert-danger">Connection error.</div>');
    });
}

function getSeverityColor(severity) {
    const colors = {
        'low': 'success',
        'medium': 'warning',
        'high': 'danger',
        'critical': 'dark'
    };
    return colors[severity] || 'secondary';
}

function bookmarkDisease() {
    if (!currentDiseaseId) return;
    
    $.post(APP_URL + '/ajax/bookmark-content.php', {
        content_type: 'disease',
        content_id: currentDiseaseId
    }, function(response) {
        if (response.success) {
            Toastify({
                text: "Disease bookmarked successfully!",
                backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
                duration: 3000
            }).showToast();
        }
    });
}

// Report Disease Form
$('#reportDiseaseForm').on('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    $.ajax({
        url: APP_URL + '/ajax/report-disease.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Report Submitted!',
                    text: 'Thank you for reporting. Extension officers will be notified.',
                    confirmButtonColor: '#059669'
                });
                $('#reportDiseaseModal').modal('hide');
                $('#reportDiseaseForm')[0].reset();
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: response.message || 'Failed to submit report'
                });
            }
        },
        error: function() {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Connection error. Please try again.'
            });
        }
    });
});
</script>

<?php
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>