<?php
/**
 * Violet MediaPay Callback Handler
 * - Validasi signature dari HEADER atau JSON body
 * - Update bill & customer status
 * - Catat saldo masuk ke cabang (PENDING H+5)
 * - Restore MikroTik
 */

$logFile = __DIR__ . '/violet_callback_log.txt';

// Log raw input
$rawInput = file_get_contents("php://input");
file_put_contents($logFile, date('Y-m-d H:i:s') . " - RAW: " . $rawInput . "\n", FILE_APPEND);

// Log all HTTP headers for debugging
$headers = [];
foreach ($_SERVER as $key => $value) {
    if (strpos($key, 'HTTP_') === 0) {
        $headers[$key] = $value;
    }
}
file_put_contents($logFile, date('Y-m-d H:i:s') . " - HEADERS: " . json_encode($headers) . "\n", FILE_APPEND);

// Response harus JSON
header('Content-Type: application/json');

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

// Parse JSON
$data = json_decode($rawInput);

if (!$data) {
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - ERROR: Invalid JSON\n", FILE_APPEND);
    echo json_encode(['status' => false, 'message' => 'Invalid JSON']);
    exit;
}

// Log parsed data
file_put_contents($logFile, date('Y-m-d H:i:s') . " - DATA: " . json_encode($data) . "\n", FILE_APPEND);

$ref           = $data->ref ?? '';          // merchant ref (bill_number)
$idReference   = $data->id_reference ?? '';  // violet transaction id
$status        = strtolower($data->status ?? '');
$amount        = (float)($data->total_amount ?? 0);
$amountRecv    = (float)($data->amount_received ?? 0);
$fee           = (float)($data->fee ?? 0);
$paymentMethod = $data->payment_method ?? '';
$paidAt        = $data->paid ?? '';

// ====================================================================
// AMBIL SIGNATURE DARI HEADER ATAU JSON BODY
// ====================================================================
// Violet mengirim signature via header X-Callback-Signature
$signature = $_SERVER['HTTP_X_CALLBACK_SIGNATURE'] 
          ?? $_SERVER['HTTP_X_CALLBACK_SIGNATURE'] 
          ?? $data->signature 
          ?? '';

file_put_contents($logFile, date('Y-m-d H:i:s') . " - SIGNATURE from header/body: " . ($signature ?: 'NOT FOUND') . "\n", FILE_APPEND);

// ====================================================================
// VALIDASI SIGNATURE
// ====================================================================
$violet = new Violet();

// Jika signature ada, validasi
if (!empty($signature)) {
    if (!$violet->verifyCallbackSignature($ref, $signature)) {
        file_put_contents($logFile, date('Y-m-d H:i:s') . " - ERROR: Invalid signature for ref=$ref\n", FILE_APPEND);
        echo json_encode(['status' => false, 'message' => 'Invalid signature']);
        exit;
    }
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - ✅ Signature valid for ref=$ref\n", FILE_APPEND);
} else {
    // Jika signature tidak ditemukan, log warning tapi tetap proses
    // (untuk testing/sandbox, Violet mungkin tidak mengirim signature)
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - ⚠️ WARNING: No signature found, processing anyway\n", FILE_APPEND);
}

// ====================================================================
// CARI BILL
// ====================================================================
$db = db();
$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([$ref]);
$bill = $stmt->fetch();

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

// ====================================================================
// PROSES BERDASARKAN STATUS
// ====================================================================
if ($status === 'success') {
    // Cek double payment
    if ($bill['status'] === 'paid') {
        echo json_encode(['status' => true, '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 = 'violet',
                payment_channel = ?,
                payment_gateway = 'violet',
                updated_at = NOW()
            WHERE id = ?
        ");
        $stmt->execute([$idReference, $paymentMethod, $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 cabang (pending H+5)
        $branchId = $bill['branch_id'] ?? null;
        
        if ($branchId) {
            $pendingUntil = date('Y-m-d H:i:s', strtotime('+5 days'));
            
            $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 (?, ?, ?, ?, ?, ?, ?, 'violet', ?, 'pending', ?, NOW())
            ");
            $stmt->execute([
                $branchId, $bill['id'], $bill['customer_id'], $idReference,
                $bill['bill_number'], $bill['customer_name'], $amountRecv,
                $paymentMethod, $pendingUntil
            ]);
            
            $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, $amountRecv, $amountRecv]);
            
            file_put_contents($logFile, 
                date('Y-m-d H:i:s') . " - SALDO: Cabang #$branchId +Rp " . number_format($amountRecv) . 
                " (pending until $pendingUntil)\n", FILE_APPEND);
        } else {
            file_put_contents($logFile, 
                date('Y-m-d H:i:s') . " - WARNING: Bill #$ref tidak punya branch_id\n", FILE_APPEND);
        }
        
        // 4. Restore MikroTik
        try {
            require_once __DIR__ . '/../classes/MikroTik.php';
            if (!empty($bill['pppoe_username']) && $branchId) {
                $mt = new MikroTik($branchId);
                $mt->restoreCustomer($bill['pppoe_username']);
                file_put_contents($logFile, 
                    date('Y-m-d H:i:s') . " - ✅ MikroTik restored for {$bill['pppoe_username']}\n", FILE_APPEND);
            }
        } 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 #$ref paid via Violet $paymentMethod (Rp " . number_format($amountRecv) . ")\n", 
            FILE_APPEND);
        
        echo json_encode(['status' => true, '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' => false, 'message' => $e->getMessage()]);
    }
    
} elseif ($status === 'belum dibayar' || $status === 'pending') {
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - PENDING: Bill #$ref\n", FILE_APPEND);
    echo json_encode(['status' => true, 'message' => 'Payment pending']);
    
} elseif ($status === 'kadaluarsa' || $status === 'expired') {
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - EXPIRED: Bill #$ref\n", FILE_APPEND);
    echo json_encode(['status' => true, 'message' => 'Payment expired']);
    
} elseif ($status === 'refund') {
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - REFUND: Bill #$ref\n", FILE_APPEND);
    echo json_encode(['status' => true, 'message' => 'Refund processed']);
    
} else {
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - UNKNOWN STATUS: $status for Bill #$ref\n", FILE_APPEND);
    echo json_encode(['status' => true, 'message' => 'Status recorded']);
}