<?php
/**
 * iPaymu Payment Callback Handler
 * - Update bill & customer status
 * - Catat saldo masuk ke cabang (PENDING, akan di-release H+5)
 * - Restore MikroTik sesuai cabang
 */

// Log semua request
$logFile = __DIR__ . '/callback_log.txt';
file_put_contents($logFile, date('Y-m-d H:i:s') . " - " . json_encode($_POST) . "\n", FILE_APPEND);

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../classes/Bill.php';
require_once __DIR__ . '/../classes/Customer.php';

$trxId         = $_POST['trx_id'] ?? '';
$referenceId   = $_POST['reference_id'] ?? '';

// PERBAIKAN: Gunakan strtolower() agar pengecekan status tidak case-sensitive
$status        = strtolower($_POST['status'] ?? ''); 

$amount        = (float)($_POST['amount'] ?? 0);
$paymentMethod = $_POST['payment_method'] ?? '';
$paymentChannel= $_POST['payment_channel'] ?? '';
$buyerName     = $_POST['buyer_name'] ?? '';

$db = db();

// Cari bill berdasarkan reference_id (bill_number)
$stmt = $db->prepare("
    SELECT b.*, c.name as customer_name, c.branch_id, c.pppoe_username, c.id as customer_id
    FROM bills b
    LEFT JOIN customers c ON b.customer_id = c.id
    WHERE b.bill_number = ?
");
$stmt->execute([$referenceId]);
$bill = $stmt->fetch();

if (!$bill) {
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - Bill not found: $referenceId\n", FILE_APPEND);
    http_response_code(404);
    echo json_encode(['status' => 'error', 'message' => 'Bill not found']);
    exit;
}

// PERBAIKAN: Sesuaikan kondisi dengan huruf kecil semua
if ($status === 'success' || $status === 'berhasil') {
    // Cek double payment
    if ($bill['status'] === 'paid') {
        echo json_encode(['status' => 'success', 'message' => 'Already paid']);
        exit;
    }
    
    try {
        $db->beginTransaction();
        
        // ====================================================================
        // 1. UPDATE BILL STATUS
        // ====================================================================
        $stmt = $db->prepare("
            UPDATE bills 
            SET status = 'paid', 
                paid_at = NOW(),
                transaction_id = ?,
                payment_method = ?,
                payment_channel = ?,
                updated_at = NOW()
            WHERE id = ?
        ");
        $stmt->execute([$trxId, $paymentMethod, $paymentChannel, $bill['id']]);
        
        // ====================================================================
        // 2. UPDATE CUSTOMER STATUS
        // ====================================================================
        $stmt = $db->prepare("UPDATE customers SET status = 'active', updated_at = NOW() WHERE id = ?");
        $stmt->execute([$bill['customer_id']]);
        
        // ====================================================================
        // 3. CATAT SALDO MASUK KE CABANG (PENDING H+5)
        // ====================================================================
        $branchId = $bill['branch_id'] ?? null;
        
        if ($branchId) {
            // Hitung tanggal release (H+5 dari sekarang)
            $pendingUntil = date('Y-m-d H:i:s', strtotime('+5 days'));
            
            // 3a. Insert transaksi ke branch_transactions
            $stmt = $db->prepare("
                INSERT INTO branch_transactions 
                (branch_id, bill_id, customer_id, transaction_id, bill_number, 
                 customer_name, amount, payment_method, payment_channel, 
                 status, pending_until, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, NOW())
            ");
            $stmt->execute([
                $branchId,
                $bill['id'],
                $bill['customer_id'],
                $trxId,
                $bill['bill_number'],
                $bill['customer_name'],
                $amount,
                $paymentMethod,
                $paymentChannel,
                $pendingUntil
            ]);
            
            // 3b. Update branch_balances: tambah ke pending_balance
            $stmt = $db->prepare("
                INSERT INTO branch_balances 
                (branch_id, pending_balance, available_balance, total_withdrawn, total_income)
                VALUES (?, ?, 0, 0, ?)
                ON DUPLICATE KEY UPDATE 
                    pending_balance = pending_balance + VALUES(pending_balance),
                    total_income = total_income + VALUES(total_income),
                    last_updated_at = NOW()
            ");
            $stmt->execute([$branchId, $amount, $amount]);
            
            file_put_contents($logFile, 
                date('Y-m-d H:i:s') . " - SALDO: Cabang #$branchId +Rp " . number_format($amount) . 
                " (pending until $pendingUntil)\n", 
                FILE_APPEND);
        } else {
            file_put_contents($logFile, 
                date('Y-m-d H:i:s') . " - WARNING: Bill #{$bill['bill_number']} tidak punya branch_id\n", 
                FILE_APPEND);
        }
        
        // ====================================================================
        // 4. RESTORE MIKROTIK (sesuai cabang)
        // ====================================================================
        try {
            require_once __DIR__ . '/../classes/MikroTik.php';
            
            if (!empty($bill['pppoe_username'])) {
                // Gunakan branch_id agar connect ke MikroTik cabang yang benar
                $mt = new MikroTik($branchId);
                $mt->restoreCustomer($bill['pppoe_username']);
            }
        } catch (\Throwable $e) {
            file_put_contents($logFile, 
                date('Y-m-d H:i:s') . " - MikroTik error: " . $e->getMessage() . "\n", 
                FILE_APPEND);
        }
        
        $db->commit();
        
        file_put_contents($logFile, 
            date('Y-m-d H:i:s') . " - SUCCESS: Bill #{$bill['bill_number']} paid via $paymentMethod $paymentChannel\n", 
            FILE_APPEND);
        
        echo json_encode(['status' => 'success', 'message' => 'Payment processed']);
        
    } catch (\Throwable $e) {
        $db->rollBack();
        file_put_contents($logFile, date('Y-m-d H:i:s') . " - ERROR: " . $e->getMessage() . "\n", FILE_APPEND);
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    
// PERBAIKAN: Sesuaikan kondisi pending dengan huruf kecil
} elseif ($status === 'pending') {
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - PENDING: Bill #{$bill['bill_number']} - Status: $status\n", FILE_APPEND);
    echo json_encode(['status' => 'success', 'message' => 'Payment pending']);
    
} else {
    // Status lainnya seperti expired, failed, dll
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - FAILED/EXPIRED: Bill #{$bill['bill_number']} - Status: $status\n", FILE_APPEND);
    echo json_encode(['status' => 'success', 'message' => 'Payment failed or expired']);
}