<?php
/**
 * Update Tenant Endpoint (Super Admin Only)
 */

use App\Core\Database;
use App\Core\Validator;
use App\Middleware\AuthMiddleware;

$decoded = AuthMiddleware::check();

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

$data = input();

$errors = Validator::validate($data, [
    'id'     => 'required',
    'name'   => 'required',
    'email'  => 'required|email',
    'status' => 'required'
]);

if ($errors) {
    json_error('Validation Failed', 422, $errors);
}

$db = Database::getInstance();

try {
    // Encrypt sensitive data
    $encryptedName = \App\Core\Encryption::encrypt($data['name']);
    $encryptedEmail = \App\Core\Encryption::encrypt($data['email']);

    $stmt = $db->prepare("
        UPDATE tenants 
        SET name = ?, email = ?, phone = ?, status = ?, updated_at = NOW() 
        WHERE id = ?
    ");
    
    $stmt->execute([
        $encryptedName,
        $encryptedEmail,
        $data['phone'] ?? null,
        $data['status'],
        $data['id']
    ]);

    if ($stmt->rowCount() === 0) {
        // Might be unchanged or ID doesn't exist
        $check = $db->prepare("SELECT id FROM tenants WHERE id = ?");
        $check->execute([$data['id']]);
        if (!$check->fetch()) {
            json_error('Tenant not found', 404);
        }
    }

    json_success(null, 'تم تحديث بيانات المكتب بنجاح');

} catch (\Exception $e) {
    json_error('حدث خطأ أثناء التحديث: ' . $e->getMessage(), 500);
}
