<?php

require_once __DIR__ . '/../../core/api_bootstrap.php';
require_once __DIR__ . '/../../core/permissions.php';

/* METHOD */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(false, 'Invalid request method.', [], 405);
}

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

/* RBAC */
require_permission($user, 'bulk_upload', 'create', $pdo);

/* INPUT */
$input = json_decode(file_get_contents('php://input'), true);

if (
    !$input ||
    empty($input['type']) ||
    empty($input['rows']) ||
    !is_array($input['rows'])
) {
    json_response(false, 'Invalid request.', [], 400);
}

$type = $input['type'];
$rows = $input['rows'];

/* HARD ROW LIMIT */
if (count($rows) > 500) {
    json_response(false, 'Maximum 500 rows per upload.', [], 400);
}

if (!in_array($type, ['companies', 'users'], true)) {
    json_response(false, 'Invalid upload type.', [], 400);
}

$inserted = 0;

$pdo->beginTransaction();

try {

    /* ==========================================================
       COMPANIES
    ========================================================== */
    if ($type === 'companies') {

        $stmt = $pdo->prepare("
            INSERT INTO companies (company_name, rsp_id, type, status, created_at)
            VALUES (?, ?, ?, ?, NOW())
        ");

        foreach ($rows as $row) {

            if (empty($row['company_name']) || empty($row['rsp_id']) || empty($row['type'])) {
                throw new Exception('Invalid company row.');
            }

            $name = trim($row['company_name']);
            $rsp_id = (int)$row['rsp_id'];
            $company_type = trim($row['type']);

            if (!in_array($company_type, ['fleet', 'sp'], true)) {
                throw new Exception("Invalid company type: {$company_type}");
            }

            /* RSP isolation */
            if (!empty($user['rsp_id']) && $rsp_id !== (int)$user['rsp_id']) {
                throw new Exception('RSP isolation violation.');
            }

            /* Duplicate check */
            $check = $pdo->prepare("
                SELECT COUNT(*) FROM companies 
                WHERE LOWER(company_name) = LOWER(?) AND rsp_id = ?
            ");
            $check->execute([$name, $rsp_id]);

            if ((int)$check->fetchColumn() > 0) {
                throw new Exception("Duplicate company: {$name}");
            }

            $stmt->execute([
                $name,
                $rsp_id,
                $company_type,
                $row['status'] ?? 'active'
            ]);

            $inserted++;
        }
    }

    /* ==========================================================
       USERS
    ========================================================== */
    if ($type === 'users') {

        require_permission($user, 'users', 'create', $pdo);

        $stmt = $pdo->prepare("
            INSERT INTO users
            (first_name, last_name, email, password_hash, role, company_id, status, created_at)
            VALUES (?, ?, ?, ?, ?, ?, 'active', NOW())
        ");

        $emailCheck = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ?");

        $allowed_roles = [
            'admin',
            'rsp_admin',
            'fleet_controller',
            'sp_admin',
            'artisan'
        ];

        foreach ($rows as $row) {

            if (empty($row['email']) || empty($row['role']) || empty($row['company_id'])) {
                throw new Exception('Invalid user row.');
            }

            $role = trim($row['role']);

            if (!in_array($role, $allowed_roles, true)) {
                throw new Exception("Invalid role: {$role}");
            }

            /* Prevent privilege escalation */
            if ($role === 'super_admin') {
                throw new Exception('Cannot bulk create super_admin.');
            }

            $company_id = (int)$row['company_id'];

            /* RSP isolation */
            if (!empty($user['rsp_id'])) {

                $checkCompany = $pdo->prepare("SELECT rsp_id FROM companies WHERE id = ?");
                $checkCompany->execute([$company_id]);
                $companyRsp = $checkCompany->fetchColumn();

                if (!$companyRsp || (int)$companyRsp !== (int)$user['rsp_id']) {
                    throw new Exception('RSP isolation violation.');
                }
            }

            $email = strtolower(trim($row['email']));

            $emailCheck->execute([$email]);
            if ((int)$emailCheck->fetchColumn() > 0) {
                throw new Exception("Duplicate email: {$email}");
            }

            $temp_password = bin2hex(random_bytes(4));
            $hash = password_hash($temp_password, PASSWORD_DEFAULT);

            $stmt->execute([
                trim($row['first_name'] ?? ''),
                trim($row['last_name'] ?? ''),
                $email,
                $hash,
                $role,
                $company_id
            ]);

            $inserted++;
        }
    }

    /* AUDIT */
    log_admin_action(
        $pdo,
        (int)$user['id'],
        'bulk_upload',
        'create',
        null
    );

    $pdo->commit();

} catch (Throwable $e) {

    $pdo->rollBack();
    json_response(false, 'Bulk insert failed: ' . $e->getMessage(), [], 400);
}

json_response(true, 'Bulk upload completed successfully.', [
    'type' => $type,
    'rows_inserted' => $inserted
]);