<?php
/**
 * WALLET PAYMENT - COMPLETE PROCESSING
 * File: payment-wallet.php (ROOT)
 * 
 * Processes wallet payment completely (like payment-callback does for Paystack)
 */

ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

require_once 'app/Core/init.php';
require_once 'app/Core/WalletProcessor.php';

ob_clean();
header('Content-Type: application/json');

if (!Auth::check() || Auth::userType() !== 'customer') {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Invalid request']);
    exit;
}

$reference = $_POST['reference'] ?? '';
$amount = floatval($_POST['amount'] ?? 0);

if (!$reference || $amount <= 0) {
    echo json_encode(['success' => false, 'error' => 'Invalid payment data']);
    exit;
}

if (!isset($_SESSION['pending_booking'])) {
    echo json_encode(['success' => false, 'error' => 'No pending booking found']);
    exit;
}

$booking = $_SESSION['pending_booking'];
$booking['payment_gateway'] = 'wallet';

try {
    $db = Database::getInstance();
    
    if ($booking['order_reference'] !== $reference) {
        throw new Exception('Reference mismatch');
    }
    
    if (abs($booking['total_amount'] - $amount) > 0.01) {
        throw new Exception('Amount mismatch');
    }
    
    $customerModel = new Customer();
    $customer = $customerModel->findByUserId(Auth::id());
    
    if (!$customer) {
        throw new Exception('Customer not found');
    }
    
    // Verify wallet balance
    $walletModel = new Wallet();
    $wallet = $walletModel->findByUserId(Auth::id());
    
    if (!$wallet) {
        throw new Exception('Wallet not found');
    }
    
    $wallet_balance = floatval($wallet['balance']);
    
    if ($wallet_balance < $amount) {
        throw new Exception('Insufficient balance. Available: ₦' . number_format($wallet_balance, 2));
    }
    
    // Check if already processed
    $existingOrder = $db->fetch("
        SELECT o.id, o.order_number 
        FROM orders o
        JOIN online_payments op ON o.id = op.order_id
        WHERE op.transaction_reference = ?
    ", [$reference]);
    
    if ($existingOrder) {
        unset($_SESSION['pending_booking']);
        
        $_SESSION['send_order_emails'] = [
            'order_id' => $existingOrder['id'],
            'timestamp' => time()
        ];
        
        echo json_encode([
            'success' => true,
            'reference' => $reference,
            'order_number' => $existingOrder['order_number'],
            'message' => 'Already processed'
        ]);
        exit;
    }
    
    // Get commission
    $categoryCommission = $db->fetch("
        SELECT c.commission_percentage 
        FROM items i 
        INNER JOIN categories c ON i.category_id = c.id 
        WHERE i.id = ? 
        LIMIT 1
    ", [$booking['item_id']]);
    
    $commissionPercentage = 10.00;
    if ($categoryCommission && isset($categoryCommission['commission_percentage'])) {
        $commissionPercentage = floatval($categoryCommission['commission_percentage']);
    }
    
    $platformCommission = round(($booking['subtotal'] * $commissionPercentage) / 100, 2);
    $booking['commission_percentage'] = $commissionPercentage;
    $booking['platform_commission'] = $platformCommission;
    
    error_log("Wallet payment - Commission: {$commissionPercentage}% = ₦{$platformCommission}");
    
    $db->beginTransaction();
    
    try {
        // Create order with same format as Paystack
        $orderNumber = 'R' . date('ymdHis') . strtoupper(substr(uniqid(), -3));
        
        $db->execute("
            INSERT INTO orders (
                order_number, customer_id, vendor_id, item_id, 
                start_date, end_date, rental_days, quantity,
                subtotal, security_deposit, platform_fee, total_amount, 
                status, payment_status, rental_completed, security_deposit_status,
                created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'confirmed', 'paid', 0, 'held', NOW(), NOW())
        ", [
            $orderNumber, $booking['customer_id'], $booking['vendor_id'], $booking['item_id'],
            $booking['start_date'], $booking['end_date'], $booking['number_of_days'], $booking['quantity'],
            $booking['subtotal'], $booking['security_deposit'], $platformCommission, $booking['total_amount']
        ]);
        
        $orderId = $db->lastInsertId();
        
        if (!$orderId) {
            throw new Exception("Failed to create order");
        }
        
        error_log("Wallet payment - Order created: ID={$orderId}, Number={$orderNumber}");
        
        // Update or create payment record
        $existingPayment = $db->fetch("
            SELECT id FROM online_payments 
            WHERE transaction_reference = ?
        ", [$reference]);
        
        if ($existingPayment) {
            $db->execute("
                UPDATE online_payments 
                SET order_id = ?, payment_gateway = 'wallet', status = 'completed',
                    gateway_response = ?, completed_at = NOW(), updated_at = NOW()
                WHERE transaction_reference = ?
            ", [$orderId, json_encode(['wallet' => true, 'amount' => $amount]), $reference]);
            $paymentId = $existingPayment['id'];
            error_log("Wallet payment - Payment updated: ID={$paymentId}");
        } else {
            $db->execute("
                INSERT INTO online_payments (
                    customer_id, order_id, transaction_reference, payment_gateway, 
                    amount, payment_type, currency, customer_email, status, 
                    gateway_response, completed_at, created_at, updated_at
                ) VALUES (?, ?, ?, 'wallet', ?, 'order_payment', 'NGN', ?, 'completed', ?, NOW(), NOW(), NOW())
            ", [
                $customer['id'], $orderId, $reference, 
                $booking['total_amount'], Auth::user()['email'],
                json_encode(['wallet' => true, 'amount' => $amount])
            ]);
            $paymentId = $db->lastInsertId();
            error_log("Wallet payment - Payment created: ID={$paymentId}");
        }
        
        // Create commission record
        try {
            $db->execute("
                INSERT INTO commissions (
                    order_id, vendor_id, commission_percentage, 
                    commission_amount, rental_amount, status, created_at
                ) VALUES (?, ?, ?, ?, ?, 'pending', NOW())
            ", [
                $orderId, $booking['vendor_id'], 
                $commissionPercentage, $platformCommission, $booking['subtotal']
            ]);
            error_log("Wallet payment - Commission record created");
        } catch (Exception $e) {
            error_log("Wallet payment - Commission record skipped: " . $e->getMessage());
        }
        
        // Process wallet via WalletProcessor
        error_log("Wallet payment - Starting WalletProcessor...");
        $walletProcessor = new WalletProcessor();
        if (!$walletProcessor->processPayment($orderId, $paymentId, $booking)) {
            throw new Exception("Wallet processing failed");
        }
        error_log("Wallet payment - WalletProcessor completed");
        
        $db->commit();
        error_log("Wallet payment - Transaction committed successfully");
        
        unset($_SESSION['pending_booking']);
        
        $_SESSION['send_order_emails'] = [
            'order_id' => $orderId,
            'timestamp' => time()
        ];
        
        echo json_encode([
            'success' => true,
            'reference' => $reference,
            'order_number' => $orderNumber,
            'order_id' => $orderId
        ]);
        
    } catch (Exception $e) {
        $db->rollback();
        error_log("Wallet payment - Transaction rolled back: " . $e->getMessage());
        throw $e;
    }
    
} catch (Exception $e) {
    error_log("Wallet payment error: " . $e->getMessage());
    error_log("Reference: {$reference}");
    
    if (isset($db) && $db->inTransaction()) {
        $db->rollback();
    }
    
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}