<?php
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/iPaymu.php';

class Payment {
    /**
     * Buat pembayaran baru via iPaymu
     */
    public static function create($billId, $method = 'va', $channel = 'bca') {
        $db = db();
        $bill = Bill::find($billId);
        if (!$bill) return ['success' => false, 'error' => 'Tagihan tidak ditemukan'];
        if ($bill['status'] === 'paid') return ['success' => false, 'error' => 'Tagihan sudah lunas'];

        $refId = 'PAY-' . $billId . '-' . time();
        
        $ipaymu = new iPaymu();
        $result = $ipaymu->directPayment([
            'buyer_name'      => $bill['name'],
            'buyer_phone'     => $bill['phone'],
            'buyer_email'     => '',
            'amount'          => $bill['amount'],
            'reference_id'    => $refId,
            'payment_method'  => $method,
            'payment_channel' => $channel,
        ]);

        if (($result['Status'] ?? -1) != 200) {
            return ['success' => false, 'error' => $result['Comments'] ?? 'Failed to create payment'];
        }

        // Simpan ke DB
        $stmt = $db->prepare("INSERT INTO payments 
            (bill_id, customer_id, amount, payment_method, payment_channel, 
             reference_id, ipaymu_session_id, payment_url, va_number, status) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')");
        $stmt->execute([
            $billId,
            $bill['customer_id'],
            $bill['amount'],
            $method,
            $channel,
            $refId,
            $result['Data']['SessionID'] ?? null,
            $result['Data']['Url'] ?? null,
            $result['Data']['VA'] ?? null
        ]);

        return [
            'success'      => true,
            'payment_id'   => $db->lastInsertId(),
            'url'          => $result['Data']['Url'] ?? null,
            'va_number'    => $result['Data']['VA'] ?? null,
            'reference_id' => $refId
        ];
    }

    /**
     * Proses callback dari iPaymu
     */
    public static function processCallback($data) {
        $db = db();
        $refId = $data['reference_id'] ?? ($data['ReferenceId'] ?? null);
        if (!$refId) return false;

        $stmt = $db->prepare("SELECT * FROM payments WHERE reference_id = ?");
        $stmt->execute([$refId]);
        $payment = $stmt->fetch();
        if (!$payment) return false;

        $status = strtolower($data['status'] ?? ($data['Status'] ?? ''));
        $successStatuses = ['success', 'paid', 'berhasil'];
        
        if (in_array($status, $successStatuses)) {
            $db->prepare("UPDATE payments SET status = 'success', paid_at = NOW(), 
                         transaction_id = ?, callback_data = ? WHERE id = ?")
               ->execute([
                   $data['transaction_id'] ?? ($data['TransactionID'] ?? null),
                   json_encode($data),
                   $payment['id']
               ]);
            
            // Tandai bill sebagai paid
            Bill::markAsPaid($payment['bill_id'], $data);
            return true;
        } elseif (in_array($status, ['expired', 'gagal', 'failed'])) {
            $db->prepare("UPDATE payments SET status = ?, callback_data = ? WHERE id = ?")
               ->execute([$status, json_encode($data), $payment['id']]);
        }
        return false;
    }
}

require_once __DIR__ . '/Bill.php';