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

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

// 1. Auth + Role Check
$decoded = RoleMiddleware::require(['super_admin', 'admin']);
$db = Database::getInstance();

$currentUserId = $decoded['user_id'];
$currentUserRole = $decoded['role'];
$targetUserId = input('id');

if (!$targetUserId) {
    json_error('User ID is required', 422);
}

// 2. Prevent self-deletion
if ($currentUserId === $targetUserId) {
    json_error('لا يمكنك حذف حسابك الشخصي من هنا', 403);
}

// 3. Fetch target user to check permissions
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$targetUserId]);
$targetUser = $stmt->fetch();

if (!$targetUser) {
    json_error('المستخدم غير موجود', 404);
}

// 4. Role-based Authorization
if ($currentUserRole === 'super_admin') {
    // Super Admin can delete anyone except themselves
} elseif ($currentUserRole === 'admin') {
    // Admin can only delete users in THEIR tenant
    if ($targetUser['tenant_id'] !== $decoded['tenant_id']) {
        json_error('ليس لديك صلاحية لحذف هذا المستخدم', 403);
    }
    // Admin cannot delete other admins (only super_admin can)
    if ($targetUser['role'] === 'admin' || $targetUser['role'] === 'super_admin') {
        json_error('لا يمكنك حذف مدير آخر. فقط السوبر أدمن يمكنه ذلك.', 403);
    }
} else {
    json_error('غير مصرح لك بحذف المستخدمين', 403);
}

// 5. Perform Soft Delete
$stmt = $db->prepare("UPDATE users SET deleted_at = NOW(), is_active = 0 WHERE id = ?");
$stmt->execute([$targetUserId]);

AuditLogger::log('user.deleted', 'user', $targetUserId, [
    'role' => $targetUser['role'],
], null, $decoded);

json_success(null, 'تم حذف المستخدم بنجاح');
