<?php
/**
 * List Companies Endpoint (Synchronized Schema)
 */

use App\Core\Database;
use App\Core\Encryption;
use App\Middleware\AuthMiddleware;

$decoded = AuthMiddleware::check();
$db = Database::getInstance();

try {
    // 1. Super Admin sees ALL companies
    if ($decoded['role'] === 'super_admin') {
        $stmt = $db->prepare("
            SELECT c.*, t.name as tenant_name,
                   (SELECT COUNT(*) FROM invoices WHERE company_id = c.id AND deleted_at IS NULL) as invoices_count,
                   (SELECT SUM(grand_total) FROM invoices WHERE company_id = c.id AND deleted_at IS NULL) as total_amount
            FROM companies c 
            LEFT JOIN tenants t ON c.tenant_id = t.id 
            WHERE c.deleted_at IS NULL ORDER BY c.created_at DESC
        ");
        $stmt->execute();
        $companies = $stmt->fetchAll();
    } 
    // 2. Tenant Users (Admin, Accountant, Employee) see all companies in their tenant
    else {
        $stmt = $db->prepare("
            SELECT *,
                   (SELECT COUNT(*) FROM invoices WHERE company_id = companies.id AND deleted_at IS NULL) as invoices_count,
                   (SELECT SUM(grand_total) FROM invoices WHERE company_id = companies.id AND deleted_at IS NULL) as total_amount
            FROM companies 
            WHERE tenant_id = ? AND deleted_at IS NULL ORDER BY created_at DESC
        ");
        $stmt->execute([$decoded['tenant_id']]);
        $companies = $stmt->fetchAll();
    }

    // 3. Decrypt fields
    $dec = function($val) {
        if (empty($val)) return '';
        $result = \App\Core\Encryption::decrypt((string)$val);
        return ($result !== false && $result !== null) ? $result : (string)$val;
    };

    foreach ($companies as &$company) {
        $company['name'] = $dec($company['name']);
        
        if (!empty($company['name_en'])) {
            $company['name_en'] = $dec($company['name_en']);
        }

        if (isset($company['tenant_name'])) {
            $company['tenant_name'] = $dec($company['tenant_name']);
        }

        // Redact JoFotara secrets
        $company['jofotara_client_id_encrypted'] = !empty($company['jofotara_client_id_encrypted']);
        unset($company['jofotara_secret_key_encrypted']);
        unset($company['certificate_password_encrypted']);
    }

    json_success($companies);

} catch (\Exception $e) {
    json_error('SQL Error in Companies List: ' . $e->getMessage(), 500);
}
