<?php
/**
 * ============================================================================
 * ajax/get-tip.php - Fetch Agricultural Tip Details
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

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

// Check if user is logged in
if (!isLoggedIn()) {
    jsonError('Unauthorized access', 401);
}

// Check if tip ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    jsonError('Tip ID is required');
}

$tipId = (int)$_GET['id'];

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $sql = "SELECT t.*, 
            CASE 
                WHEN t.category = 'crop_management' THEN 'Crop Management'
                WHEN t.category = 'pest_control' THEN 'Pest & Disease Control'
                WHEN t.category = 'soil_health' THEN 'Soil Health'
                WHEN t.category = 'irrigation' THEN 'Irrigation'
                WHEN t.category = 'harvesting' THEN 'Harvesting'
                WHEN t.category = 'storage' THEN 'Storage'
                ELSE 'General Farming'
            END as category_name
            FROM agricultural_tips t
            WHERE t.id = ? AND t.is_published = 1";
    
    $stmt = $db->prepare($sql);
    $stmt->execute([$tipId]);
    $tip = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$tip) {
        jsonError('Tip not found', 404);
    }
    
    // Format the content
    $tip['content'] = nl2br(htmlspecialchars($tip['content']));
    
    jsonSuccess('Tip fetched successfully', $tip);
    
} catch (PDOException $e) {
    error_log("Error fetching tip: " . $e->getMessage());
    jsonError('Failed to fetch tip details');
}
?>
