Update: 2026-05-03 21:58:11
This commit is contained in:
78
app/modules_app/companies/create.php
Normal file
78
app/modules_app/companies/create.php
Normal file
@@ -0,0 +1,78 @@
|
||||
<?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')
|
||||
]);
|
||||
|
||||
$companyId = $db->lastInsertId();
|
||||
|
||||
// 4. Pivot link
|
||||
$stmt = $db->prepare("INSERT INTO user_companies (user_id, company_id, role) VALUES (?, ?, ?)");
|
||||
$stmt->execute([$decoded['user_id'], $companyId, 'admin']);
|
||||
|
||||
$db->commit();
|
||||
json_success(['id' => $companyId], 'تم إنشاء الشركة بنجاح');
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$db->rollBack();
|
||||
json_error('حدث خطأ أثناء حفظ البيانات: ' . $e->getMessage(), 500);
|
||||
}
|
||||
Reference in New Issue
Block a user