<?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':
            $search = '%' . trim($_GET['search'] ?? '') . '%';
            [$cw, $cp] = client_where($user, 'c.record_id');
            $stmt = $db->prepare(
                "SELECT c.record_id, c.clients_name, c.provinces_id, c.email,
                        c.phone, c.address, c.client_code, c.client_logo,
                        p.provinces_name
                 FROM clients c
                 LEFT JOIN provinces p ON p.record_id = c.provinces_id
                 WHERE ($cw)
                   AND (c.clients_name LIKE ? OR c.client_code LIKE ?)
                 ORDER BY c.clients_name ASC"
            );
            $stmt->execute(array_merge($cp, [$search, $search]));
            json_success(['clients' => $stmt->fetchAll()]);
            break;

        case 'get':
            if (!$id) json_error('ID required');
            [$cw2, $cp2] = client_where($user, 'c.record_id');
            $stmt = $db->prepare(
                "SELECT c.record_id, c.clients_name, c.provinces_id, c.email,
                        c.phone, c.address, c.client_code, c.client_logo,
                        p.provinces_name
                 FROM clients c
                 LEFT JOIN provinces p ON p.record_id = c.provinces_id
                 WHERE ($cw2) AND c.record_id = ?"
            );
            $stmt->execute(array_merge($cp2, [$id]));
            $row = $stmt->fetch();
            if (!$row) json_error('Not found', 404);
            json_success(['client' => $row]);
            break;

        case 'provinces':
            $rows = $db->query(
                'SELECT record_id, provinces_name FROM provinces ORDER BY provinces_name ASC'
            )->fetchAll();
            json_success(['provinces' => $rows]);
            break;

        case 'create':
            require_admin($user);
            $name    = trim($_POST['clients_name'] ?? '');
            $prov    = (int)($_POST['provinces_id'] ?? 0);
            $email   = trim($_POST['email'] ?? '');
            $phone   = trim($_POST['phone'] ?? '');
            $address = trim($_POST['address'] ?? '');
            $code    = trim($_POST['client_code'] ?? '');
            if (empty($name)) json_error('Client name required');
            $db->prepare(
                'INSERT INTO clients (clients_name, provinces_id, email, phone, address, client_code, client_logo)
                 VALUES (?, ?, ?, ?, ?, ?, ?)'
            )->execute([$name, $prov, $email, $phone, $address, $code, '']);
            json_success(['id' => $db->lastInsertId()], 'Client created');
            break;

        case 'update':
            require_admin($user);
            if (!$id) json_error('ID required');
            $name    = trim($_POST['clients_name'] ?? '');
            $prov    = (int)($_POST['provinces_id'] ?? 0);
            $email   = trim($_POST['email'] ?? '');
            $phone   = trim($_POST['phone'] ?? '');
            $address = trim($_POST['address'] ?? '');
            $code    = trim($_POST['client_code'] ?? '');
            if (empty($name)) json_error('Client name required');
            $db->prepare(
                'UPDATE clients
                 SET clients_name = ?, provinces_id = ?, email = ?,
                     phone = ?, address = ?, client_code = ?
                 WHERE record_id = ?'
            )->execute([$name, $prov, $email, $phone, $address, $code, $id]);
            json_success([], 'Client updated');
            break;

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

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

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