<?php
/**
 * ============================================================================
 * extension/report-disease.php
 * Report New Disease - Extension Officers & Farmers
 * ============================================================================
 */

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

$pageTitle = 'Report Disease - AIMS Extension';
$breadcrumbs = [
    ['title' => 'Disease Reports', 'url' => APP_URL . '/extension/diseases.php'],
    ['title' => 'Report Disease', 'url' => '']
];

renderExtensionHeader($pageTitle, $breadcrumbs);
?>

<div class="container-fluid py-4">
    <div class="row justify-content-center">
        <div class="col-xl-8">
            <!-- Header -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center">
                        <a href="<?php echo APP_URL; ?>/extension/diseases.php" class="btn btn-outline-secondary me-3">
                            <i class="bi bi-arrow-left"></i>
                        </a>
                        <div>
                            <h4 class="mb-1 fw-bold">
                                <i class="bi bi-bug text-danger me-2"></i>Report Disease Outbreak
                            </h4>
                            <p class="text-muted mb-0">Help identify and manage crop diseases in your area</p>
                        </div>
                    </div>
                </div>
            </div>

            <form id="reportDiseaseForm" method="POST" enctype="multipart/form-data">
                <!-- Crop Information -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-white py-3">
                        <h6 class="mb-0 fw-bold">
                            <i class="bi bi-tree text-success me-2"></i>Crop Information
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold">
                                    Crop Type <span class="text-danger">*</span>
                                </label>
                                <select name="crop_type" class="form-select form-select-lg" required>
                                    <option value="">Select crop type</option>
                                    <option value="maize">Maize</option>
                                    <option value="beans">Beans</option>
                                    <option value="coffee">Coffee</option>
                                    <option value="cassava">Cassava</option>
                                    <option value="bananas">Bananas</option>
                                    <option value="sweet_potato">Sweet Potato</option>
                                    <option value="rice">Rice</option>
                                    <option value="sugarcane">Sugarcane</option>
                                    <option value="vegetables">Vegetables</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold">Severity Level</label>
                                <select name="severity" class="form-select form-select-lg" required>
                                    <option value="low">Low - Minor spots/damage</option>
                                    <option value="medium" selected>Medium - Noticeable damage</option>
                                    <option value="high">High - Significant crop loss</option>
                                    <option value="critical">Critical - Severe outbreak</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Disease Details -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-white py-3">
                        <h6 class="mb-0 fw-bold">
                            <i class="bi bi-clipboard-pulse text-danger me-2"></i>Disease Details
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label fw-semibold">
                                Suspected Disease (Optional)
                            </label>
                            <select name="disease_id" class="form-select form-select-lg">
                                <option value="">-- Select if you know the disease --</option>
                                <?php
                                $sql = "SELECT id, disease_name, scientific_name, crop_type 
                                        FROM crop_diseases 
                                        WHERE is_published = 1 
                                        ORDER BY crop_type, disease_name";
                                $stmt = $db->prepare($sql);
                                $stmt->execute();
                                $diseases = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                
                                $currentCrop = '';
                                foreach ($diseases as $disease):
                                    if ($currentCrop !== $disease['crop_type']):
                                        if ($currentCrop !== '') echo '</optgroup>';
                                        $currentCrop = $disease['crop_type'];
                                        echo '<optgroup label="' . ucfirst($currentCrop) . '">';
                                    endif;
                                ?>
                                <option value="<?php echo $disease['id']; ?>">
                                    <?php echo e($disease['disease_name']); ?>
                                </option>
                                <?php endforeach; ?>
                                <?php if ($currentCrop !== '') echo '</optgroup>'; ?>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-semibold">
                                Describe the symptoms <span class="text-danger">*</span>
                            </label>
                            <textarea name="description" class="form-control" rows="5" required
                                      placeholder="Describe what you see: leaf spots, color changes, wilting, stem damage, etc."></textarea>
                            <small class="text-muted">
                                <i class="bi bi-info-circle me-1"></i>
                                Be as detailed as possible. Include when you first noticed it and how fast it's spreading.
                            </small>
                        </div>
                    </div>
                </div>

                <!-- Location -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-white py-3">
                        <h6 class="mb-0 fw-bold">
                            <i class="bi bi-geo-alt text-primary me-2"></i>Location
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Farm Location</label>
                            <input type="text" name="location" class="form-control form-control-lg" 
                                   value="<?php echo htmlspecialchars($coverageArea); ?>" readonly>
                            <small class="text-muted">Location auto-filled from your profile</small>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold">GPS Coordinates (Optional)</label>
                                <button type="button" class="btn btn-outline-primary w-100" onclick="getLocation()">
                                    <i class="bi bi-geo"></i> Get Current Location
                                </button>
                                <input type="hidden" name="location_lat" id="location_lat">
                                <input type="hidden" name="location_lng" id="location_lng">
                                <small id="locationStatus" class="text-muted"></small>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold">Affected Area (acres)</label>
                                <input type="number" name="affected_area" class="form-control" 
                                       step="0.1" placeholder="e.g., 2.5">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Photos -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-white py-3">
                        <h6 class="mb-0 fw-bold">
                            <i class="bi bi-camera text-info me-2"></i>Photos (Highly Recommended)
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <i class="bi bi-lightbulb me-2"></i>
                            <strong>Photo Tips:</strong> Take clear photos showing:
                            <ul class="mb-0 mt-2">
                                <li>Close-up of affected leaves/stems</li>
                                <li>Overall view of affected plants</li>
                                <li>Comparison with healthy plants if available</li>
                            </ul>
                        </div>

                        <div class="mb-3">
                            <input type="file" name="images[]" class="form-control" 
                                   accept="image/*" multiple id="diseaseImages" onchange="previewImages(this)">
                            <small class="text-muted">You can upload up to 5 photos (Max 5MB each)</small>
                        </div>

                        <div id="imagePreview" class="row g-2"></div>
                    </div>
                </div>

                <!-- Submit -->
                <div class="card border-0 shadow-sm">
                    <div class="card-body">
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-danger btn-lg flex-fill">
                                <i class="bi bi-send me-2"></i>Submit Disease Report
                            </button>
                            <a href="<?php echo APP_URL; ?>/extension/diseases.php" class="btn btn-outline-secondary btn-lg">
                                Cancel
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function getLocation() {
    if (navigator.geolocation) {
        $('#locationStatus').html('<i class="bi bi-hourglass-split"></i> Getting location...');
        
        navigator.geolocation.getCurrentPosition(
            function(position) {
                $('#location_lat').val(position.coords.latitude);
                $('#location_lng').val(position.coords.longitude);
                $('#locationStatus').html('<i class="bi bi-check-circle text-success"></i> Location captured successfully');
            },
            function(error) {
                $('#locationStatus').html('<i class="bi bi-x-circle text-danger"></i> Could not get location');
                showToast('Location access denied. You can still submit without coordinates.', 'warning');
            }
        );
    } else {
        showToast('Geolocation is not supported by your browser', 'error');
    }
}

function previewImages(input) {
    const preview = $('#imagePreview');
    preview.html('');
    
    if (input.files) {
        const filesArray = Array.from(input.files).slice(0, 5);
        
        filesArray.forEach((file, index) => {
            const reader = new FileReader();
            
            reader.onload = function(e) {
                const col = $('<div class="col-md-3 col-6"></div>');
                const img = $('<img class="img-thumbnail" style="height: 150px; object-fit: cover;">');
                img.attr('src', e.target.result);
                col.append(img);
                preview.append(col);
            }
            
            reader.readAsDataURL(file);
        });
        
        if (input.files.length > 5) {
            showToast('Only first 5 images will be uploaded', 'warning');
        }
    }
}

$('#reportDiseaseForm').on('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    formData.append('action', 'report_disease');
    
    showLoading();
    
    $.ajax({
        url: '<?php echo APP_URL; ?>/api/extension.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            hideLoading();
            if (response.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Report Submitted',
                    text: response.message,
                    confirmButtonColor: '#059669'
                }).then(() => {
                    window.location.href = '<?php echo APP_URL; ?>/extension/diseases.php';
                });
            } else {
                showToast(response.message, 'error');
            }
        },
        error: function() {
            hideLoading();
            showToast('Failed to submit report. Please try again.', 'error');
        }
    });
});
</script>

<?php renderExtensionFooter(); ?>