<?php
/**
 * Create Payment Request (Admin/Accountant)
 * POST /api/v1/payments/create
 * 
 * Creates a payment request for subscription upgrade.
 * Returns CliQ alias and reference number for transfer.
 */

declare(strict_types=1);

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

$decoded = AuthMiddleware::check();

// Only admin, accountant or super_admin can create payment requests
if (!in_array($decoded['role'], ['admin', 'accountant', 'super_admin'])) {
    json_error('غير مصرح لك بإنشاء طلب دفع.', 403);
}

$data = Security::sanitize(input());

$errors = Validator::validate($data, [
    'plan_id' => 'required',
]);
if ($errors) {
    json_error('معرف الباقة مطلوب.', 422);
}

$db = Database::getInstance();
$tenantId = $decoded['tenant_id'];
$userId = $decoded['user_id'];
$planId = $data['plan_id'];

try {
    // 1. Get plan details
    $stmt = $db->prepare("SELECT * FROM subscription_plans WHERE id = ? AND is_active = 1");
    $stmt->execute([$planId]);
    $plan = $stmt->fetch();

    if (!$plan) {
        json_error('الباقة المختارة غير صالحة أو غير نشطة.', 422);
    }

    // 2. Check for existing pending payment for this tenant
    $stmt = $db->prepare("SELECT id FROM payment_requests WHERE tenant_id = ? AND status = 'pending' LIMIT 1");
    $stmt->execute([$tenantId]);
    $existing = $stmt->fetch();

    if ($existing) {
        json_error('لديك طلب دفع قائم بالفعل. يرجى إتمامه أو إلغاؤه أولاً.', 409);
    }

    // 3. Generate unique reference number (MSQ-XXXXXX)
    $referenceNumber = 'MSQ-' . strtoupper(substr(md5(uniqid((string)mt_rand(), true)), 0, 8));

    // 4. Get CliQ alias from config
    $cliqAlias = env('CLIQ_ALIAS', 'musadaq-pay');

    // 5. Get payer name
    $stmt = $db->prepare("SELECT name, phone FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch();

    // 6. Create payment request
    $paymentId = Database::generateUuid();
    $stmt = $db->prepare("
        INSERT INTO payment_requests (id, tenant_id, user_id, plan_id, amount_jod, internal_reference, cliq_alias, payer_name, status, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())
    ");
    $stmt->execute([
        $paymentId,
        $tenantId,
        $userId,
        $planId,
        $plan['price_jod'],
        $referenceNumber,
        $cliqAlias,
        $user['name'] ?? ''
    ]);

    // 7. Log
    $logStmt = $db->prepare("INSERT INTO audit_logs (tenant_id, user_id, action, entity_type, entity_id, new_data) VALUES (?, ?, 'payment.created', 'payment', ?, ?)");
    $logStmt->execute([
        $tenantId,
        $userId,
        $paymentId,
        json_encode(['plan_id' => $planId, 'amount' => $plan['price_jod'], 'ref' => $referenceNumber])
    ]);

    json_success([
        'payment_id'       => $paymentId,
        'reference_number' => $referenceNumber,
        'cliq_alias'       => $cliqAlias,
        'amount_jod'       => (float)$plan['price_jod'],
        'plan_name'        => $plan['name_ar'] ?? $plan['name_en'],
        'payer_name'       => $user['name'] ?? '',
        'instructions'     => "قم بالتحويل عبر CliQ إلى الاسم المستعار: {$cliqAlias} بمبلغ {$plan['price_jod']} دينار أردني.",
    ], 'تم إنشاء طلب الدفع بنجاح');

} catch (\Throwable $e) {
    error_log("Payment Create Error: " . $e->getMessage());
    json_error('حدث خطأ أثناء إنشاء طلب الدفع.', 500);
}
