false, 'policy' => null, 'ledger' => ['pending_total' => 0, 'settled_total' => 0, 'currency' => null], 'entries' => [], ], 'لا توجد وثيقة نشطة'); } $summary = ['pending_total' => 0.0, 'settled_total' => 0.0, 'currency' => $policy['currency']]; $entries = []; try { $st = $con->prepare(" SELECT status, SUM(amount) AS total FROM insurance_premium_ledger WHERE policy_id = ? GROUP BY status "); $st->execute([$policy['id']]); foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $row) { if ($row['status'] === 'pending') $summary['pending_total'] = (float) $row['total']; if ($row['status'] === 'settled') $summary['settled_total'] = (float) $row['total']; } // ‏آخر ثلاثين قيداً: كافية لشهر يومي، وتمنع رداً ينمو بلا حد. $st = $con->prepare(" SELECT charge_date, amount, currency, status, note FROM insurance_premium_ledger WHERE policy_id = ? ORDER BY charge_date DESC LIMIT 30 "); $st->execute([$policy['id']]); $entries = $st->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $e) { error_log('[assurance/get] تعذّرت قراءة الدفتر: ' . $e->getMessage()); } jsonSuccess([ 'has_policy' => true, 'policy' => [ 'id' => (int) $policy['id'], 'plan' => $policy['plan_name'], 'provider' => $policy['provider_name_ar'] ?: $policy['provider_name'], 'policy_number' => $policy['policy_number'], 'coverage' => $policy['coverage_summary'], 'billing_cycle' => $policy['billing_cycle'], 'premium' => (float) $policy['premium'], 'currency' => $policy['currency'], 'started_at' => $policy['started_at'], 'last_charged_on' => $policy['last_charged_on'], ], 'ledger' => $summary, 'entries' => $entries, ], 'success');