<?php
/**
 * ============================================================================
 * ajax/report-disease.php - Report Disease Outbreak
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json');

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$userId = getUserId();
$crop_type = $_POST['crop_type'] ?? '';
$location = $_POST['location'] ?? '';
$description = $_POST['description'] ?? '';
$severity = $_POST['severity'] ?? 'medium';

if (empty($crop_type) || empty($description)) {
    echo json_encode(['success' => false, 'message' => 'Required fields missing']);
    exit;
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Handle image uploads if present
    $images = [];
    if (isset($_FILES['images']) && !empty($_FILES['images']['name'][0])) {
        $upload_dir = __DIR__ . '/../assets/uploads/disease-reports/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }
        
        foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
            if ($_FILES['images']['error'][$key] === UPLOAD_ERR_OK) {
                $original_name = $_FILES['images']['name'][$key];
                $extension = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
                
                // Validate image
                if (in_array($extension, ['jpg', 'jpeg', 'png', 'gif'])) {
                    $new_filename = 'report_' . $userId . '_' . time() . '_' . $key . '.' . $extension;
                    $destination = $upload_dir . $new_filename;
                    
                    if (move_uploaded_file($tmp_name, $destination)) {
                        $images[] = 'assets/uploads/disease-reports/' . $new_filename;
                    }
                }
            }
        }
    }
    
    $images_json = !empty($images) ? json_encode($images) : null;
    
    // Insert disease report
    $sql = "INSERT INTO disease_reports 
            (user_id, crop_type, location, description, images, severity, status) 
            VALUES (?, ?, ?, ?, ?, ?, 'pending')";
    
    $stmt = $db->prepare($sql);
    $stmt->execute([
        $userId,
        $crop_type,
        $location,
        $description,
        $images_json,
        $severity
    ]);
    
    $reportId = $db->lastInsertId();
    
    // Notify extension officers
    try {
        $notify_sql = "INSERT INTO notifications (user_id, title, message, type, icon, link)
                      SELECT id, 'Disease Report Submitted', 
                             CONCAT('A disease outbreak has been reported in ', ?),
                             'warning', 'exclamation-triangle',
                             '/admin/disease-reports.php'
                      FROM users 
                      WHERE user_type IN ('extension_officer', 'admin')";
        $notify_stmt = $db->prepare($notify_sql);
        $notify_stmt->execute([$location ?: 'your area']);
    } catch (PDOException $e) {
        // Log but don't fail
        error_log("Error creating notifications: " . $e->getMessage());
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Disease report submitted successfully',
        'report_id' => $reportId
    ]);
    
} catch (PDOException $e) {
    error_log("Database error in report-disease.php: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Failed to submit report'
    ]);
}
?>