<?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'] ?? '') . '%';
            [$cw, $cp] = client_where($user, 's.clients_id');
            if ($client_id) {
                $stmt = $db->prepare(
                    "SELECT s.record_id, s.client_sites_name, s.clients_id, c.clients_name
                     FROM client_sites s
                     LEFT JOIN clients c ON c.record_id = s.clients_id
                     WHERE ($cw) AND s.clients_id = ? AND s.client_sites_name LIKE ?
                     ORDER BY s.client_sites_name ASC"
                );
                $stmt->execute(array_merge($cp, [$client_id, $search]));
            } else {
                $stmt = $db->prepare(
                    "SELECT s.record_id, s.client_sites_name, s.clients_id, c.clients_name
                     FROM client_sites s
                     LEFT JOIN clients c ON c.record_id = s.clients_id
                     WHERE ($cw) AND s.client_sites_name LIKE ?
                     ORDER BY c.clients_name ASC, s.client_sites_name ASC
                     LIMIT 200"
                );
                $stmt->execute(array_merge($cp, [$search]));
            }
            json_success(['sites' => $stmt->fetchAll()]);
            break;

        case 'get':
            if (!$id) json_error('ID required');
            $stmt = $db->prepare(
                'SELECT s.record_id, s.client_sites_name, s.clients_id, c.clients_name
                 FROM client_sites s
                 LEFT JOIN clients c ON c.record_id = s.clients_id
                 WHERE s.record_id = ?'
            );
            $stmt->execute([$id]);
            $row = $stmt->fetch();
            if (!$row) json_error('Not found', 404);
            json_success(['site' => $row]);
            break;

        case 'create':
            $name      = trim($_POST['client_sites_name'] ?? '');
            $client_id = (int)($_POST['clients_id'] ?? 0);
            if (empty($name))   json_error('Site name required');
            if (!$client_id)    json_error('Client required');
            $db->prepare(
                'INSERT INTO client_sites (client_sites_name, clients_id) VALUES (?, ?)'
            )->execute([$name, $client_id]);
            json_success(['id' => $db->lastInsertId()], 'Site created');
            break;

        case 'update':
            if (!$id) json_error('ID required');
            $name      = trim($_POST['client_sites_name'] ?? '');
            $client_id = (int)($_POST['clients_id'] ?? 0);
            if (empty($name)) json_error('Site name required');
            $db->prepare(
                'UPDATE client_sites SET client_sites_name = ?, clients_id = ? WHERE record_id = ?'
            )->execute([$name, $client_id, $id]);
            json_success([], 'Site updated');
            break;

        case 'delete':
            require_admin($user);
            if (!$id) json_error('ID required');
            $db->prepare('DELETE FROM client_sites WHERE record_id = ?')->execute([$id]);
            json_success([], 'Site deleted');
            break;

        default:
            json_error('Unknown action: ' . htmlspecialchars($action));
    }

} catch (Throwable $e) {
    json_error('sites.php [' . $e->getLine() . ']: ' . $e->getMessage(), 500);
}