<?php
require_once 'db/config.php';

if (isset($_GET['id'])) {
    header('Content-Type: application/json');
    try {
        $person_id = $_GET['id'];
        $pdo = db();

        // Fetch person details
        $stmt = $pdo->prepare("SELECT * FROM people WHERE id = ?");
        $stmt->execute([$person_id]);
        $person = $stmt->fetch(PDO::FETCH_ASSOC);

        // Fetch all functions
        $stmt = $pdo->query("
            SELECT f.id, f.name, bg.name as group_name
            FROM functions f
            LEFT JOIN bni_groups bg ON f.bni_group_id = bg.id
            ORDER BY bg.display_order, f.display_order
        ");
        $all_functions = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Fetch person's functions
        $stmt = $pdo->prepare("SELECT function_id FROM user_functions WHERE user_id = ?");
        $stmt->execute([$person_id]);
        $person_functions = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);

        // --- Fetch Follow-up Process Summary ---
        $follow_up_summary = null;
        $stmt_def = $pdo->prepare("SELECT id FROM process_definitions WHERE code = 'guest_handling' LIMIT 1");
        $stmt_def->execute();
        $follow_up_def_id = $stmt_def->fetchColumn();

        if ($follow_up_def_id) {
            $stmt_inst = $pdo->prepare("SELECT * FROM process_instances WHERE person_id = ? AND process_definition_id = ? ORDER BY id DESC LIMIT 1");
            $stmt_inst->execute([$person_id, $follow_up_def_id]);
            $instance = $stmt_inst->fetch(PDO::FETCH_ASSOC);

            if ($instance) {
                $data = $instance['data_json'] ? json_decode($instance['data_json'], true) : [];
                $follow_up_summary = [
                    'last_call_outcome' => $data['outcome_status'] ?? null,
                    'last_call_date' => $data['call_date'] ?? null,
                    'next_contact_date' => $data['next_contact_date'] ?? null,
                    'final_outcome' => $instance['current_status'], // e.g., completed, terminated
                    'reason' => $instance['current_reason']
                ];
            }
        }

        $response = [
            'person' => $person,
            'all_functions' => $all_functions,
            'person_functions' => $person_functions,
            'follow_up_summary' => $follow_up_summary
        ];

        echo json_encode($response);
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit;
}
?>