<?php

namespace Models;

class CompanyModel
{
    private \PDO $pdo;

    public function __construct()
    {
        if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof \PDO) {
            $this->pdo = $GLOBALS['pdo'];
        } else {
            throw new \RuntimeException('Global PDO connection not initialized');
        }
    }

    public function createCompany(string $name, string $cnpj, string $flag = 'a'): int
    {
        $stmt = $this->pdo->prepare('INSERT INTO "company" (company_name, company_cnpj, company_flag) VALUES (:name, :cnpj, :flag) RETURNING company_id');
        $stmt->execute([
            'name' => $name,
            'cnpj' => $cnpj,
            'flag' => $flag
        ]);
        
        return (int)$stmt->fetchColumn();
    }

    public function createRole(int $companyId, string $roleName, array $permission = [], string $flag = 'a'): int
    {
        $stmt = $this->pdo->prepare('INSERT INTO "role" (company_id, role_name, role_permission, role_flag) VALUES (:company_id, :role_name, :permission::jsonb, :flag) RETURNING role_id');
        $stmt->execute([
            'company_id' => $companyId,
            'role_name' => $roleName,
            'permission' => json_encode($permission, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
            'flag' => $flag,
        ]);
        return (int)$stmt->fetchColumn();
    }
}
