'required', ]); if ($errors) { json_error('معرف الباقة مطلوب.', 422); } $db = Database::getInstance(); $tenantId = $decoded['tenant_id']; $userId = $decoded['user_id']; $planId = $data['plan_id']; $cycle = $data['billing_cycle'] ?? 'annual'; // Default to annual if (!in_array($cycle, ['monthly', 'annual'])) { json_error('دورة الفوترة غير صالحة.', 422); } 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); } // Determine amount based on cycle $amount = ($cycle === 'monthly') ? ($plan['price_monthly_jod'] ?? $plan['price_jod']) : ($plan['price_annual_jod'] ?? ($plan['price_jod'] * 10)); // 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, billing_cycle, amount_jod, internal_reference, cliq_alias, payer_name, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW()) "); $stmt->execute([ $paymentId, $tenantId, $userId, $planId, $cycle, $amount, $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, 'cycle' => $cycle, 'amount' => $amount, 'ref' => $referenceNumber]) ]); json_success([ 'payment_id' => $paymentId, 'reference_number' => $referenceNumber, 'cliq_alias' => $cliqAlias, 'amount_jod' => (float)$amount, 'plan_name' => ($plan['name_ar'] ?? $plan['name_en']) . " (" . ($cycle === 'monthly' ? 'شهري' : 'سنوي') . ")", 'payer_name' => $user['name'] ?? '', 'instructions' => "قم بالتحويل عبر CliQ إلى الاسم المستعار: {$cliqAlias} بمبلغ {$amount} دينار أردني.", ], 'تم إنشاء طلب الدفع بنجاح'); } catch (\Throwable $e) { error_log("Payment Create Error: " . $e->getMessage()); json_error('حدث خطأ أثناء إنشاء طلب الدفع.', 500); }