Files
musadaq-saas/app/Modules/Companies/CompanyController.php

89 lines
3.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Modules\Companies;
use App\Core\{Request, Response};
use App\Modules\Companies\{CompanyModel, CompanyService};
use Throwable;
final class CompanyController
{
public function __construct(
private readonly CompanyModel $companyModel,
private readonly CompanyService $companyService
) {}
public function list(Request $request): void
{
$tenantId = $request->tenantId;
$role = $request->user->role ?? 'viewer';
$assignedCompanyId = $request->user->assigned_company_id ?? null;
$db = \App\Core\Database::getInstance();
$columns = "id, name, name_en, tax_identification_number, commercial_registration_number, city, is_jofotara_linked, is_active, created_at";
if (in_array($role, ['admin', 'super_admin'], true)) {
$stmt = $db->prepare("SELECT {$columns} FROM companies WHERE tenant_id = ? AND deleted_at IS NULL");
$stmt->execute([$tenantId]);
} else {
$stmt = $db->prepare("SELECT {$columns} FROM companies WHERE tenant_id = ? AND id = ? AND deleted_at IS NULL");
$stmt->execute([$tenantId, $assignedCompanyId]);
}
$companies = $stmt->fetchAll();
Response::json([
'success' => true,
'data' => $companies
]);
}
public function create(Request $request): void
{
$data = $request->getBody();
if (empty($data['name']) || empty($data['tax_identification_number'])) {
throw new \App\Core\Exceptions\HttpException("اسم الشركة والرقم الضريبي مطلوبان", "VALIDATION_ERROR", 422);
}
$data['tenant_id'] = $request->tenantId;
$companyId = $this->companyService->createCompany($data);
Response::json([
'success' => true,
'data' => ['id' => $companyId],
'message' => 'تم إضافة الشركة بنجاح'
], 201);
}
public function updateJoFotara(Request $request, string $id): void
{
// 1. Verify Tenant Ownership (IDOR Prevention)
$db = \App\Core\Database::getInstance();
$stmt = $db->prepare("SELECT id FROM companies WHERE id = ? AND tenant_id = ?");
$stmt->execute([$id, $request->tenantId]);
if (!$stmt->fetchColumn()) {
throw new \App\Core\Exceptions\HttpException("الشركة غير موجودة أو لا تملك صلاحية الوصول", "NOT_FOUND", 404);
}
$clientId = $request->input('client_id');
$secretKey = $request->input('secret_key');
if (empty($clientId) || empty($secretKey)) {
throw new \App\Core\Exceptions\HttpException("يجب توفير Client ID و Secret Key", "VALIDATION_ERROR", 422);
}
$data = [
'jofotara_client_id' => $clientId,
'jofotara_secret_key' => $secretKey,
'is_jofotara_linked' => 1
];
$this->companyService->updateJoFotara($id, $data);
Response::json([
'success' => true,
'message' => 'تم تحديث بيانات جو-فواتير بنجاح'
]);
}
}