<?php
/**
 * Create Company Endpoint (Synchronized Schema)
 */

use App\Core\Database;
use App\Core\Encryption;
use App\Core\Validator;
use App\Core\AuditLogger;
use App\Middleware\AuthMiddleware;
use App\Middleware\RoleMiddleware;

$decoded = RoleMiddleware::require(['super_admin', 'admin']);

$data = input();

// 1. Validation
$errors = Validator::validate($data, [
    'name' => 'required',
    'tax_identification_number' => 'required'
]);

if ($errors) {
    json_error('Validation Failed', 422, $errors);
}

$db = Database::getInstance();

try {
    $db->beginTransaction();

    // 2. Encrypt sensitive fields
    $encryptedName = Encryption::encrypt($data['name']);
    $encryptedNameEn = !empty($data['name_en']) ? Encryption::encrypt($data['name_en']) : null;
    
    // Encrypt JoFotara keys if provided
    $jofotaraClientId = !empty($data['jofotara_client_id']) ? Encryption::encrypt($data['jofotara_client_id']) : null;
    $jofotaraSecretKey = !empty($data['jofotara_secret_key']) ? Encryption::encrypt($data['jofotara_secret_key']) : null;

    // 3. Save to Database
    $stmt = $db->prepare("
        INSERT INTO companies (
            id, tenant_id, name, name_en, tax_identification_number, commercial_registration_number, 
            city, address, contact_email, contact_phone, 
            jofotara_client_id_encrypted, jofotara_secret_key_encrypted, 
            created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    
    // Determine tenant_id: Super Admin chooses, Admin uses own
    $tenantId = null;
    if ($decoded['role'] === 'super_admin') {
        if (empty($data['tenant_id'])) {
            json_error('يجب اختيار المكتب المحاسبي', 422);
        }
        $tenantId = $data['tenant_id'];
    } else {
        $tenantId = $decoded['tenant_id'];
    }

    // --- QUOTA CHECK ---
    \App\Middleware\QuotaMiddleware::checkCompanyQuota($tenantId);
    // -------------------

    $stmt->execute([
        \App\Core\Database::generateUuid(),
        $tenantId,
        $encryptedName,
        $encryptedNameEn,
        $data['tax_identification_number'],
        $data['commercial_registration_number'] ?? null,
        $data['city'] ?? null,
        $data['address'] ?? null,
        $data['contact_email'] ?? null,
        $data['contact_phone'] ?? null,
        $jofotaraClientId,
        $jofotaraSecretKey,
        date('Y-m-d H:i:s')
    ]);
    
    $db->commit();

    AuditLogger::log('company.created', 'company', null, null, [
        'name' => $data['name'],
        'tin'  => $data['tax_identification_number'],
    ], $decoded);

    json_success(null, 'تم إنشاء الشركة بنجاح');

} catch (\Exception $e) {
    $db->rollBack();
    json_error('حدث خطأ أثناء حفظ البيانات: ' . $e->getMessage(), 500);
}
