Files
musadaq-saas/app/modules_app/companies/create.php
2026-05-05 00:01:17 +03:00

89 lines
2.6 KiB
PHP

<?php
/**
* Create Company Endpoint (Synchronized Schema)
*/
use App\Core\Database;
use App\Core\Encryption;
use App\Core\Validator;
use App\Middleware\AuthMiddleware;
$decoded = AuthMiddleware::check();
if ($decoded['role'] !== 'super_admin' && $decoded['role'] !== 'admin') {
json_error('Unauthorized', 403);
}
$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();
json_success(null, 'تم إنشاء الشركة بنجاح');
} catch (\Exception $e) {
$db->rollBack();
json_error('حدث خطأ أثناء حفظ البيانات: ' . $e->getMessage(), 500);
}