<?php
ob_start();
require_once __DIR__ . '/../config/auth.php';

if (!function_exists('is_admin')) {
    function is_admin(array $user): bool { return (int)$user['user_type_id'] === 1; }
}
if (!function_exists('allowed_clients')) {
    function allowed_clients(array $user): ?array {
        if (is_admin($user)) return null;
        $ids = array_values(array_filter(array_map('intval', explode(',', $user['clients_multi'] ?? ''))));
        return $ids ?: [-1];
    }
}
if (!function_exists('client_where')) {
    function client_where(array $user, string $col = 'clients_id'): array {
        $ids = allowed_clients($user);
        if ($ids === null) return ['1=1', []];
        $ph = implode(',', array_fill(0, count($ids), '?'));
        return ["$col IN ($ph)", $ids];
    }
}

$user = require_auth();

try {
    $db     = db();
    $action = $_GET['action'] ?? 'list';
    $emp_id = (int)($_GET['client_employees_id'] ?? 0);
    $id     = (int)($_GET['id'] ?? 0);
    $type   = $_GET['type'] ?? 'assessment'; // assessment | test

    switch ($action) {

        // ── List all assessments + tests for an employee ──────────────────
        case 'list':
            if (!$emp_id) json_error('client_employees_id required');
            // Verify employee belongs to an allowed client
            $ec = $db->prepare('SELECT clients_id FROM client_employees WHERE record_id=?');
            $ec->execute([$emp_id]);
            $emp_row = $ec->fetch();
            $allowed_r = allowed_clients($user);
            if ($emp_row && $allowed_r !== null && !in_array((int)$emp_row['clients_id'], $allowed_r)) {
                json_error('Access denied to this employee', 403);
            }

            $ass_stmt = $db->prepare(
                'SELECT a.record_id, a.assesses_name, a.assesses_info, a.results,
                        a.date, a.booking, a.passmark, a.current_mark,
                        a.nqf_level, a.credits, a.notes, a.vehicle_model,
                        a.safesure_users_id, a.image_file_path,
                        u.safesure_users_name as assessor_name, u.name as assessor_full_name,
                        u.assessor_number,
                        b.booking_number
                 FROM assesses a
                 LEFT JOIN safesure_users u ON u.record_id = a.safesure_users_id
                 LEFT JOIN bookings b ON b.record_id = a.booking
                 WHERE a.client_employees_id = ?
                 ORDER BY a.record_id DESC'
            );
            $ass_stmt->execute([$emp_id]);
            $assessments = $ass_stmt->fetchAll();

            $test_stmt = $db->prepare(
                'SELECT t.record_id, t.test_name, t.test_info, t.results,
                        t.date, t.booking, t.passmark, t.current_mark,
                        t.nqf_level, t.credits, t.notes, t.vehicle_model,
                        t.safesure_users_id, t.image_file_path,
                        u.safesure_users_name as assessor_name, u.name as assessor_full_name,
                        u.assessor_number,
                        b.booking_number
                 FROM tests_sec t
                 LEFT JOIN safesure_users u ON u.record_id = t.safesure_users_id
                 LEFT JOIN bookings b ON b.record_id = t.booking
                 WHERE t.client_employees_id = ?
                 ORDER BY t.record_id DESC'
            );
            $test_stmt->execute([$emp_id]);
            $tests = $test_stmt->fetchAll();

            json_success(['assessments' => $assessments, 'tests' => $tests]);
            break;

        // ── Get full detail for one assessment ────────────────────────────
        case 'get_assessment':
            if (!$id) json_error('id required');
            $stmt = $db->prepare(
                'SELECT a.*,
                        u.safesure_users_name as assessor_name, u.name as assessor_full_name, u.assessor_number,
                        c.clients_name, c.client_code,
                        e.client_employees_name, e.surname, e.i_doc_passport, e.company_number, e.occupation,
                        b.booking_number
                 FROM assesses a
                 LEFT JOIN safesure_users u ON u.record_id = a.safesure_users_id
                 LEFT JOIN clients c ON c.record_id = a.clients_id
                 LEFT JOIN client_employees e ON e.record_id = a.client_employees_id
                 LEFT JOIN bookings b ON b.record_id = a.booking
                 WHERE a.record_id = ?'
            );
            $stmt->execute([$id]);
            $ass = $stmt->fetch();
            if (!$ass) json_error('Not found', 404);

            // Sections + questions
            $sec_stmt = $db->prepare('SELECT * FROM assesses_sections WHERE assesses_id = ? ORDER BY record_id ASC');
            $sec_stmt->execute([$id]);
            $sections = $sec_stmt->fetchAll();
            foreach ($sections as &$sec) {
                $q_stmt = $db->prepare('SELECT * FROM assesses_section_questions WHERE assesses_section_id = ? ORDER BY record_id ASC');
                $q_stmt->execute([$sec['record_id']]);
                $sec['questions'] = $q_stmt->fetchAll();
                // Parse subtotal e.g. "22-0" => total-nyc
                $parts = explode('-', $sec['subtotal'] ?? '0-0');
                $sec['total']  = (int)($parts[0] ?? 0);
                $sec['nyc']    = (int)($parts[1] ?? 0);
                $sec['scored'] = $sec['total'] - $sec['nyc'];
            }
            $ass['sections'] = $sections;

            json_success(['assessment' => $ass]);
            break;

        // ── Get full detail for one test ──────────────────────────────────
        case 'get_test':
            if (!$id) json_error('id required');
            $stmt = $db->prepare(
                'SELECT t.*,
                        u.safesure_users_name as assessor_name, u.name as assessor_full_name, u.assessor_number,
                        c.clients_name, c.client_code,
                        e.client_employees_name, e.surname, e.i_doc_passport, e.company_number, e.occupation,
                        b.booking_number
                 FROM tests_sec t
                 LEFT JOIN safesure_users u ON u.record_id = t.safesure_users_id
                 LEFT JOIN clients c ON c.record_id = t.clients_id
                 LEFT JOIN client_employees e ON e.record_id = t.client_employees_id
                 LEFT JOIN bookings b ON b.record_id = t.booking
                 WHERE t.record_id = ?'
            );
            $stmt->execute([$id]);
            $test = $stmt->fetch();
            if (!$test) json_error('Not found', 404);

            // Questions + answers
            $q_stmt = $db->prepare('SELECT * FROM tests_questions_sec WHERE tests_sec_id = ? ORDER BY record_id ASC');
            $q_stmt->execute([$id]);
            $questions = $q_stmt->fetchAll();
            foreach ($questions as &$q) {
                $a_stmt = $db->prepare('SELECT * FROM tests_answers_sec WHERE tests_questions_sec_id = ? ORDER BY record_id ASC');
                $a_stmt->execute([$q['record_id']]);
                $q['answers'] = $a_stmt->fetchAll();
                $parts = explode('-', $q['subtotal'] ?? '0-0');
                $q['total']  = (int)($parts[0] ?? 0);
                $q['scored'] = (int)($parts[1] ?? 0);
            }
            $test['questions'] = $questions;

            json_success(['test' => $test]);
            break;

        default:
            json_error('Unknown action');
    }

} catch (Throwable $e) {
    json_error('results.php [' . $e->getLine() . ']: ' . $e->getMessage(), 500);
}