<?php
/**
 * ============================================================================
 * ajax/get-disease.php - Get Disease Details
 * ============================================================================
 */
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 (!isset($_GET['id'])) {
    echo json_encode(['success' => false, 'message' => 'Disease ID required']);
    exit;
}

$diseaseId = intval($_GET['id']);
$userId = getUserId();

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $sql = "SELECT * FROM crop_diseases WHERE id = ? AND is_published = 1";
    $stmt = $db->prepare($sql);
    $stmt->execute([$diseaseId]);
    
    $disease = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($disease) {
        // Format data for display
        $disease['crop_type_formatted'] = ucwords(str_replace('_', ' ', $disease['crop_type']));
        $disease['category_formatted'] = ucfirst($disease['category']);
        $disease['severity_formatted'] = ucfirst($disease['severity_level']);
        
        // Track learning progress
        try {
            $progress_sql = "INSERT INTO learning_progress (user_id, content_type, content_id, status) 
                            VALUES (?, 'disease', ?, 'viewed')
                            ON DUPLICATE KEY UPDATE 
                            status = 'viewed', 
                            updated_at = CURRENT_TIMESTAMP";
            $progress_stmt = $db->prepare($progress_sql);
            $progress_stmt->execute([$userId, $diseaseId]);
        } catch (PDOException $e) {
            // Log but don't fail the request
            error_log("Error tracking progress: " . $e->getMessage());
        }
        
        echo json_encode([
            'success' => true,
            'data' => $disease
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Disease not found'
        ]);
    }
} catch (PDOException $e) {
    error_log("Database error in get-disease.php: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Database error occurred'
    ]);
}
?>