<?php
/**
 * سودانا — BillPayEngine v2
 * دفع الفواتير الكاملة: كهرباء، ماء، اتصالات، تعليم، صحة
 */
require_once __DIR__ . '/AccountingEngine.php';

class BillPayEngine {

    // ── getProviders(): قائمة مزودي الفواتير ─────────────────
    public static function getProviders(string $category=''): array {
        try {
            $where = 'is_active=1';
            $params = [];
            if ($category) { $where .= ' AND category=?'; $params[] = $category; }
            $st = db()->prepare("SELECT * FROM sdpay_bill_providers WHERE {$where} ORDER BY category,name_ar");
            $st->execute($params);
            return $st->fetchAll();
        } catch (Throwable $e) { return []; }
    }

    // ── validateAccount(): تحقق من رقم الحساب ────────────────
    public static function validateAccount(int $providerId, string $accountRef): array {
        try {
            $st = db()->prepare("SELECT * FROM sdpay_bill_providers WHERE id=? AND is_active=1 LIMIT 1");
            $st->execute([$providerId]);
            $provider = $st->fetch();
            if (!$provider) return ['ok'=>false,'error'=>'provider_not_found'];

            // تحقق من الدفعات السابقة
            $prev = db()->prepare(
                "SELECT amount_sdg, paid_at FROM sdpay_bill_payments
                 WHERE provider_id=? AND account_ref=? AND status='completed'
                 ORDER BY paid_at DESC LIMIT 1"
            );
            $prev->execute([$providerId, $accountRef]);
            $lastPayment = $prev->fetch();

            return [
                'ok'           => true,
                'provider'     => $provider,
                'account_ref'  => $accountRef,
                'last_payment' => $lastPayment,
                'fee_sdg'      => (float)($provider['fixed_fee_sdg'] ?? 0),
                'commission_pct'=> (float)($provider['commission_pct'] ?? 0),
            ];
        } catch (Throwable $e) { return ['ok'=>false,'error'=>$e->getMessage()]; }
    }

    // ── pay(): دفع فاتورة ─────────────────────────────────────
    public static function pay(int $userId, int $providerId, string $accountRef, float $amount, string $pin): array {
        require_once __DIR__ . '/SudannaPayEngine.php';
        try {
            // تحقق من المزود
            $st = db()->prepare("SELECT * FROM sdpay_bill_providers WHERE id=? AND is_active=1 LIMIT 1");
            $st->execute([$providerId]);
            $provider = $st->fetch();
            if (!$provider) return ['ok'=>false,'error'=>'provider_not_found'];

            // تحقق من PIN وخصم من المحفظة
            if (!SudannaPayEngine::verifyPin($userId, $pin))
                return ['ok'=>false,'error'=>'invalid_pin'];

            $acc = SudannaPayEngine::getAccount($userId);
            if (!$acc) return ['ok'=>false,'error'=>'no_account'];

            $fee = (float)($provider['fixed_fee_sdg'] ?? 0) + ($amount * (float)($provider['commission_pct'] ?? 0));
            $total = $amount + $fee;

            if ((float)$acc['balance_sdg'] < $total)
                return ['ok'=>false,'error'=>'insufficient_balance','balance'=>$acc['balance_sdg'],'required'=>$total];

            // خصم الرصيد
            db()->beginTransaction();
            try {
                db()->prepare("UPDATE sdpay_accounts SET balance_sdg=balance_sdg-? WHERE user_id=?")
                   ->execute([$total, $userId]);

                $txnRef = 'BILL' . date('YmdHis') . substr(md5(uniqid()),0,6);
                $billRef = 'BPR' . strtoupper(substr(md5($txnRef),0,10));

                db()->prepare(
                    "INSERT INTO sdpay_bill_payments
                     (user_id,provider_id,account_ref,amount_sdg,fee_sdg,txn_ref,reference_code,status,paid_at)
                     VALUES (?,?,?,?,?,?,?,'completed',NOW())"
                )->execute([$userId,$providerId,$accountRef,$amount,$fee,$txnRef,$billRef]);

                // سجل المعاملة
                db()->prepare(
                    "INSERT INTO sdpay_transactions
                     (txn_ref,type,from_account,amount_sdg,fee_sdg,net_sdg,status,channel,narration,metadata)
                     VALUES (?,?,?,?,?,?,'completed','app',?,?)"
                )->execute([
                    $txnRef, 'bill', $acc['account_no'],
                    $amount, $fee, $amount,
                    'دفع فاتورة ' . $provider['name_ar'],
                    json_encode(['provider_id'=>$providerId,'account_ref'=>$accountRef,'bill_ref'=>$billRef])
                ]);

                db()->commit();

                // قيد محاسبي
                try { AccountingEngine::recordBillPayment($txnRef, $userId, $amount, $fee, $provider['name_ar']); }
                catch (\Throwable $ignored) {}
                return [
                    'ok'         => true,
                    'txn_ref'    => $txnRef,
                    'bill_ref'   => $billRef,
                    'amount_sdg' => $amount,
                    'fee_sdg'    => $fee,
                    'provider'   => $provider['name_ar'],
                    'message'    => 'تم دفع الفاتورة بنجاح',
                ];
            } catch (Throwable $e) {
                db()->rollBack();
                throw $e;
            }
        } catch (Throwable $e) {
            error_log("[BillPayEngine::pay] ".$e->getMessage());
            return ['ok'=>false,'error'=>$e->getMessage()];
        }
    }

    // ── getHistory(): سجل فواتير المستخدم ────────────────────
    public static function getHistory(int $userId, int $limit=20): array {
        try {
            $st = db()->prepare(
                "SELECT bp.*, pr.name_ar as provider_name, pr.category, pr.logo_url
                 FROM sdpay_bill_payments bp
                 JOIN sdpay_bill_providers pr ON pr.id=bp.provider_id
                 WHERE bp.user_id=? ORDER BY bp.paid_at DESC LIMIT ?"
            );
            $st->execute([$userId,$limit]);
            return $st->fetchAll();
        } catch (Throwable $e) { return []; }
    }
}
