prepare("SELECT * FROM subscription_plans WHERE id = ? AND is_active = 1"); $stmt->execute([$planId]); $plan = $stmt->fetch(); if (!$plan) { json_error('الباقة المختارة غير صالحة أو غير نشطة.', 422); } // 2. Update or Create Subscription $db->beginTransaction(); $startDate = date('Y-m-d H:i:s'); $endDate = date('Y-m-d H:i:s', strtotime("+{$durationDays} days")); $stmt = $db->prepare(" INSERT INTO subscriptions ( tenant_id, plan_id, max_companies, max_invoices_per_month, max_users, price_jod, status, current_period_start, current_period_end, updated_at ) VALUES ( :t_id, :p_id, :max_c, :max_i, :max_u, :price, 'active', :start, :end, NOW() ) ON DUPLICATE KEY UPDATE plan_id = VALUES(plan_id), max_companies = VALUES(max_companies), max_invoices_per_month = VALUES(max_invoices_per_month), max_users = VALUES(max_users), price_jod = VALUES(price_jod), status = 'active', current_period_start = VALUES(current_period_start), current_period_end = VALUES(current_period_end), updated_at = NOW() "); $stmt->execute([ 't_id' => $targetTenantId, 'p_id' => $planId, 'max_c' => $plan['max_companies'], 'max_i' => $plan['max_invoices_month'], 'max_u' => $plan['max_users'], 'price' => $plan['price_jod'], 'start' => $startDate, 'end' => $endDate ]); // 3. Log the change $logStmt = $db->prepare("INSERT INTO audit_logs (tenant_id, user_id, action, entity_type, entity_id, details) VALUES (?, ?, 'plan_assigned', 'tenant', ?, ?)"); $logStmt->execute([ $targetTenantId, $decoded['user_id'], $targetTenantId, json_encode(['plan_id' => $planId, 'assigned_by' => $decoded['user_id']]) ]); $db->commit(); json_success([ 'tenant_id' => $targetTenantId, 'plan_id' => $planId, 'period_end' => $endDate ], 'تم تحديث باقة الاشتراك بنجاح'); } catch (\Exception $e) { if ($db->inTransaction()) $db->rollBack(); error_log("Subscription Assign Error: " . $e->getMessage()); json_error('حدث خطأ أثناء تعيين الباقة: ' . $e->getMessage(), 500); }