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

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

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