<?php
/**
 * Delete Company Endpoint (Soft Delete)
 */

use App\Core\Database;
use App\Core\AuditLogger;
use App\Middleware\AuthMiddleware;
use App\Middleware\RoleMiddleware;
use App\Middleware\CompanyAccessMiddleware;

$decoded = RoleMiddleware::require(['super_admin', 'admin']);
$db = Database::getInstance();

$companyId = input('id');
if (!$companyId) {
    json_error('Company ID is required', 422);
}

// Authorization
if ($decoded['role'] !== 'super_admin' && $decoded['role'] !== 'admin') {
    json_error('Unauthorized', 403);
}

// Fetch company to check tenant if admin
$stmt = $db->prepare("SELECT tenant_id FROM companies WHERE id = ?");
$stmt->execute([$companyId]);
$company = $stmt->fetch();

if (!$company) {
    json_error('الشركة غير موجودة', 404);
}

// Verify tenant access (admin can only delete from their tenant)
CompanyAccessMiddleware::check($companyId, $decoded);

// Soft Delete
$stmt = $db->prepare("UPDATE companies SET deleted_at = NOW() WHERE id = ?");
$stmt->execute([$companyId]);

AuditLogger::log('company.deleted', 'company', $companyId, null, null, $decoded);

json_success(null, 'تم حذف الشركة بنجاح');
