73 lines
2.1 KiB
PHP
73 lines
2.1 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 (
|
|
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
");
|
|
|
|
$stmt->execute([
|
|
$decoded['user_id'], // Using current admin as tenant_id
|
|
$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);
|
|
}
|