<?php
declare(strict_types=1);

require_once __DIR__ . '/../system/bootstrap.php';
require_once __DIR__ . '/../system/auth.php';
require_once __DIR__ . '/../system/response.php';

header('Content-Type: application/json');

try {

    /* =========================
       AUTH
       ========================= */
    $user = require_auth($pdo);

    $role = strtolower(trim((string)($user['role_key'] ?? '')));

    if (!in_array($role, [
        'super_admin',
        'support',
        'rsp_owner',
        'rsp_admin',
        'company_admin'
    ], true)) {
        error_forbidden('Forbidden');
    }

    /* =========================
       INPUT (PAGINATION)
       ========================= */
    $page   = max(1, (int)($_GET['page'] ?? 1));
    $limit  = max(1, (int)($_GET['limit'] ?? 10));
    $offset = ($page - 1) * $limit;
    $search = trim($_GET['search'] ?? '');

    /* =========================
       FILTERS
       ========================= */
    $where  = [
        'deleted_at IS NULL',
        'status = 1'
    ];
    $params = [];

    /*
       RSP isolation
       RSP should see:
       - its own company record
       - all companies under it
    */
    if ($role === 'rsp_admin' || $role === 'rsp_owner') {
        $where[] = '(id = :rsp_id OR rsp_id = :rsp_id)';
        $params['rsp_id'] = (int)$user['company_id'];
    }

    if ($search !== '') {
        $where[] = 'company_name LIKE :search';
        $params['search'] = '%' . $search . '%';
    }

    $whereSql = 'WHERE ' . implode(' AND ', $where);

    /* =========================
       TOTAL
       ========================= */
    $stmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM companies
        $whereSql
    ");

    $stmt->execute($params);
    $total = (int)$stmt->fetchColumn();

    /* =========================
       DATA
       ========================= */
    $stmt = $pdo->prepare("
        SELECT
            id,
            company_name,
            contact_email,
            rsp_id,
            created_at
        FROM companies
        $whereSql
        ORDER BY id DESC
        LIMIT :limit OFFSET :offset
    ");

    foreach ($params as $k => $v) {
        $stmt->bindValue(':' . $k, $v);
    }

    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);

    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    /* =========================
       RESPONSE
       ========================= */
    success('Companies loaded', [
        'companies' => $rows,
        'total'     => $total,
        'page'      => $page,
        'limit'     => $limit
    ]);

} catch (Throwable $e) {
    error_log('COMPANIES LIST ERROR: ' . $e->getMessage());
    error_server('Failed to load companies');
}