<?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 = $_POST['action'] ?? $_GET['action'] ?? 'list';
    $id     = (int)($_POST['id'] ?? $_GET['id'] ?? 0);

    switch ($action) {

        case 'list':
            $client_id = (int)($_GET['clients_id'] ?? 0);
            $search    = trim($_GET['search'] ?? '');
            $like      = '%' . $search . '%';
            $limit     = 150;

            [$cw, $cp] = client_where($user, 'e.clients_id');

            if ($client_id) {
                $stmt = $db->prepare(
                    "SELECT e.record_id, e.client_employees_name, e.surname,
                            e.clients_id, e.i_doc_passport, e.cell,
                            e.company_number, e.occupation, e.teba_number,
                            e.badge_number, e.team_number, e.induction_date,
                            e.medical_date, e.industry,
                            c.clients_name
                     FROM client_employees e
                     LEFT JOIN clients c ON c.record_id = e.clients_id
                     WHERE ($cw) AND e.clients_id = ?
                       AND (e.client_employees_name LIKE ? OR e.surname LIKE ? OR e.i_doc_passport LIKE ?)
                     ORDER BY e.surname ASC, e.client_employees_name ASC
                     LIMIT $limit"
                );
                $stmt->execute(array_merge($cp, [$client_id, $like, $like, $like]));
            } elseif ($search !== '') {
                $stmt = $db->prepare(
                    "SELECT e.record_id, e.client_employees_name, e.surname,
                            e.clients_id, e.i_doc_passport, e.cell,
                            e.company_number, e.occupation, e.teba_number,
                            e.badge_number, e.team_number, e.induction_date,
                            e.medical_date, e.industry,
                            c.clients_name
                     FROM client_employees e
                     LEFT JOIN clients c ON c.record_id = e.clients_id
                     WHERE ($cw)
                       AND (e.client_employees_name LIKE ? OR e.surname LIKE ? OR e.i_doc_passport LIKE ?)
                     ORDER BY e.surname ASC, e.client_employees_name ASC
                     LIMIT $limit"
                );
                $stmt->execute(array_merge($cp, [$like, $like, $like]));
            } else {
                // No filter — return empty, JS will show prompt
                json_success(['employees' => [], 'prompt' => true]);
                break;
            }
            $rows = $stmt->fetchAll();
            json_success(['employees' => $rows, 'count' => count($rows), 'limit' => $limit]);
            break;

        case 'get':
            if (!$id) json_error('ID required');
            $stmt = $db->prepare(
                'SELECT e.record_id, e.client_employees_name, e.surname,
                        e.clients_id, e.i_doc_passport, e.cell,
                        e.company_number, e.occupation, e.teba_number,
                        e.badge_number, e.team_number, e.induction_date,
                        e.medical_date, e.industry,
                        c.clients_name
                 FROM client_employees e
                 LEFT JOIN clients c ON c.record_id = e.clients_id
                 WHERE e.record_id = ?'
            );
            $stmt->execute([$id]);
            $row = $stmt->fetch();
            if (!$row) json_error('Not found', 404);
            json_success(['employee' => $row]);
            break;

        case 'create':
            $name    = trim($_POST['client_employees_name'] ?? '');
            $surname = trim($_POST['surname'] ?? '');
            if (empty($name) || empty($surname)) json_error('Name and surname required');

            // Duplicate ID/passport check
            $id_doc = trim($_POST['i_doc_passport'] ?? '');
            if (!empty($id_doc)) {
                $chk = $db->prepare('SELECT record_id, client_employees_name, surname FROM client_employees WHERE i_doc_passport = ? LIMIT 1');
                $chk->execute([$id_doc]);
                $existing = $chk->fetch();
                if ($existing) {
                    json_error('ID/Passport ' . $id_doc . ' already exists for ' . $existing['client_employees_name'] . ' ' . $existing['surname'] . ' (ID: ' . $existing['record_id'] . ')', 409);
                }
            }

            $db->prepare(
                'INSERT INTO client_employees
                 (client_employees_name, surname, clients_id, i_doc_passport,
                  cell, company_number, occupation, teba_number, badge_number,
                  team_number, induction_date, medical_date, industry)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
            )->execute([
                $name,
                $surname,
                (int)($_POST['clients_id'] ?? 0),
                $_POST['i_doc_passport']  ?? null,
                $_POST['cell']            ?? null,
                $_POST['company_number']  ?? null,
                $_POST['occupation']      ?? null,
                $_POST['teba_number']     ?? null,
                $_POST['badge_number']    ?? null,
                $_POST['team_number']     ?? null,
                $_POST['induction_date']  ?? null,
                $_POST['medical_date']    ?? null,
                $_POST['industry']        ?? null,
            ]);
            json_success(['id' => $db->lastInsertId()], 'Employee created');
            break;

        case 'update':
            if (!$id) json_error('ID required');

            // Duplicate ID/passport check (exclude current record)
            $id_doc_upd = trim($_POST['i_doc_passport'] ?? '');
            if (!empty($id_doc_upd)) {
                $chk2 = $db->prepare('SELECT record_id, client_employees_name, surname FROM client_employees WHERE i_doc_passport = ? AND record_id != ? LIMIT 1');
                $chk2->execute([$id_doc_upd, $id]);
                $existing2 = $chk2->fetch();
                if ($existing2) {
                    json_error('ID/Passport ' . $id_doc_upd . ' already exists for ' . $existing2['client_employees_name'] . ' ' . $existing2['surname'] . ' (ID: ' . $existing2['record_id'] . ')', 409);
                }
            }

            $allowed = ['client_employees_name','surname','clients_id','i_doc_passport',
                        'cell','company_number','occupation','teba_number','badge_number',
                        'team_number','induction_date','medical_date','industry'];
            $sets = []; $vals = [];
            foreach ($allowed as $col) {
                if (array_key_exists($col, $_POST)) {
                    $sets[] = "$col = ?";
                    $vals[] = $_POST[$col];
                }
            }
            if (empty($sets)) json_error('Nothing to update');
            $vals[] = $id;
            $db->prepare('UPDATE client_employees SET ' . implode(', ', $sets) . ' WHERE record_id = ?')
               ->execute($vals);
            json_success([], 'Employee updated');
            break;

        case 'delete':
            require_admin($user);
            if (!$id) json_error('ID required');
            $db->prepare('DELETE FROM client_employees WHERE record_id = ?')->execute([$id]);
            json_success([], 'Employee deleted');
            break;

        default:
            json_error('Unknown action: ' . htmlspecialchars($action));
    }

} catch (Throwable $e) {
    json_error('employees.php [' . $e->getLine() . ']: ' . $e->getMessage(), 500);
}