<?php
/**
 * ============================================================================
 * ajax/get-variety.php - Get Crop Variety 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' => 'Variety ID required']);
    exit;
}

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

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