<?php
/**
 * Create 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, [
    'name'  => 'required',
    'email' => 'required|email',
    'manager_name' => 'required',
    'manager_email' => 'required|email',
    'manager_password' => 'required'
]);

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

$db = Database::getInstance();

try {
    $db->beginTransaction();

    // Generate Tenant UUID in PHP so we can use it immediately
    $tenantId = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );

    // 1. Create Tenant
    $encryptedTenantName = \App\Core\Encryption::encrypt($data['name']);
    $encryptedTenantEmail = \App\Core\Encryption::encrypt($data['email']);

    $stmt = $db->prepare("INSERT INTO tenants (id, name, email, phone, status, created_at) VALUES (?, ?, ?, ?, 'active', NOW())");
    $stmt->execute([
        $tenantId,
        $encryptedTenantName,
        $encryptedTenantEmail,
        $data['phone'] ?? null
    ]);

    // Generate User UUID
    $userId = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );

    // Encrypt sensitive user data
    $encryptedName = \App\Core\Encryption::encrypt($data['manager_name']);
    $encryptedEmail = \App\Core\Encryption::encrypt($data['manager_email']);
    $emailHash = hash('sha256', strtolower($data['manager_email']));

    // 2. Create Initial Manager (Admin) for this Tenant
    $stmtUser = $db->prepare("INSERT INTO users (id, tenant_id, name, email, email_hash, password_hash, role, created_at) VALUES (?, ?, ?, ?, ?, ?, 'admin', NOW())");
    $stmtUser->execute([
        $userId,
        $tenantId,
        $encryptedName,
        $encryptedEmail,
        $emailHash,
        password_hash($data['manager_password'], PASSWORD_DEFAULT)
    ]);

    $db->commit();
    json_success(null, 'تم إنشاء المكتب ومدير المكتب بنجاح');
} catch (\Exception $e) {
    $db->rollBack();
    json_error('حدث خطأ أثناء حفظ البيانات: ' . $e->getMessage(), 500);
}

