<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

require_once 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        $ticket_id = $_GET['ticket_id'] ?? null;
        
        if (!$ticket_id) {
            throw new Exception("Ticket ID is required");
        }

        // Fetch consultation details with joined information
        $stmt = $pdo->prepare("
            SELECT 
                c.id, 
                c.ticket_id, 
                c.question_category, 
                c.question_subcategory, 
                c.problem_statement,
                c.crop_age,
                c.crop_age_period,
                c.status,
                c.created_at,
                cd.expert_diagnosis,
                cd.prescribed_medicines,
                cd.recommended_actions,
                cd.follow_up_advice
            FROM 
                consultations c
            LEFT JOIN 
                consultation_details cd ON c.id = cd.consultation_id
            WHERE 
                c.ticket_id = :ticket_id
        ");
        
        $stmt->execute(['ticket_id' => $ticket_id]);
        $consultation = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$consultation) {
            throw new Exception("Consultation not found");
        }

        // Parse prescribed medicines JSON
        $consultation['prescribed_medicines'] = 
            json_decode($consultation['prescribed_medicines'], true) ?? [];

        echo json_encode([
            'status' => 'success',
            'data' => $consultation
        ]);

    } catch (Exception $e) {
        echo json_encode([
            'status' => 'error',
            'message' => $e->getMessage()
        ]);
    }
}
?>