'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['tenant_id'], // Correctly using tenant_id from JWT $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); }