<?php
/**
 * Process Order
 * Digital Product Store
 */

require_once __DIR__ . '/config/database.php';

// Check if form submitted
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ' . BASE_URL . '/checkout.php');
    exit;
}

// Get cart
$cart = get_cart();
if (empty($cart)) {
    set_flash_message('Your cart is empty.', 'error');
    header('Location: ' . BASE_URL . '/cart.php');
    exit;
}

// Get form data
$first_name = sanitize($_POST['first_name'] ?? '');
$last_name = sanitize($_POST['last_name'] ?? '');
$email = sanitize($_POST['email'] ?? '');
$phone = sanitize($_POST['phone'] ?? '');
$payment_method = sanitize($_POST['payment_method'] ?? '');

// Validate required fields
if (!$first_name || !$last_name || !$email || !$payment_method) {
    set_flash_message('Please fill in all required fields.', 'error');
    header('Location: ' . BASE_URL . '/checkout.php');
    exit;
}

if (!is_valid_email($email)) {
    set_flash_message('Please enter a valid email address.', 'error');
    header('Location: ' . BASE_URL . '/checkout.php');
    exit;
}

// Calculate totals
$subtotal = get_cart_total();
$applied_coupon = get_applied_coupon();
$discount = $applied_coupon ? $applied_coupon['discount'] : 0;
$total = $subtotal - $discount;

// Generate order number
$order_number = generate_order_number();

// Handle file upload for EFT
$payment_proof = '';
if ($payment_method === 'eft' && isset($_FILES['payment_proof']) && $_FILES['payment_proof']['error'] === UPLOAD_ERR_OK) {
    $upload_result = upload_file($_FILES['payment_proof'], 'payment_proofs', ['image/jpeg', 'image/png', 'image/gif', 'application/pdf']);
    if ($upload_result['success']) {
        $payment_proof = $upload_result['path'];
    }
}

// Get BTC transaction ID
$btc_transaction_id = sanitize($_POST['btc_transaction_id'] ?? '');

try {
    $pdo->beginTransaction();
    
    // Create or get customer
    $stmt = $pdo->prepare("SELECT id FROM customers WHERE email = ?");
    $stmt->execute([$email]);
    $customer = $stmt->fetch();
    
    if ($customer) {
        $customer_id = $customer['id'];
        // Update customer info
        $stmt = $pdo->prepare("UPDATE customers SET first_name = ?, last_name = ?, phone = ? WHERE id = ?");
        $stmt->execute([$first_name, $last_name, $phone, $customer_id]);
    } else {
        // Create new customer (guest)
        $stmt = $pdo->prepare("INSERT INTO customers (email, first_name, last_name, phone, is_guest) VALUES (?, ?, ?, ?, 1)");
        $stmt->execute([$email, $first_name, $last_name, $phone]);
        $customer_id = $pdo->lastInsertId();
    }
    
    // Determine payment status
    $payment_status = 'pending';
    if ($payment_method === 'paypal' || $payment_method === 'paystack' || $payment_method === 'flutterwave') {
        $payment_status = 'pending'; // Will be updated by webhook
    }
    
    // Create order
    $stmt = $pdo->prepare("INSERT INTO orders 
        (order_number, customer_id, customer_email, customer_name, customer_phone, 
         subtotal, discount_amount, coupon_code, total, payment_method, payment_status, 
         order_status, ip_address, user_agent) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    
    $customer_full_name = $first_name . ' ' . $last_name;
    $ip_address = get_client_ip();
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    $stmt->execute([
        $order_number,
        $customer_id,
        $email,
        $customer_full_name,
        $phone,
        $subtotal,
        $discount,
        $applied_coupon ? $applied_coupon['code'] : null,
        $total,
        $payment_method,
        $payment_status,
        'pending',
        $ip_address,
        $user_agent
    ]);
    
    $order_id = $pdo->lastInsertId();
    
    // Create order items
    foreach ($cart as $item) {
        $download_token = generate_download_token();
        $token_expires = date('Y-m-d H:i:s', strtotime('+7 days'));
        
        $stmt = $pdo->prepare("INSERT INTO order_items 
            (order_id, product_id, product_name, price, quantity, download_token, token_expires) 
            VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $order_id,
            $item['id'],
            $item['name'],
            $item['price'],
            $item['quantity'],
            $download_token,
            $token_expires
        ]);
        
        // Update product sales count
        $stmt = $pdo->prepare("UPDATE products SET sales_count = sales_count + ? WHERE id = ?");
        $stmt->execute([$item['quantity'], $item['id']]);
    }
    
    // Increment coupon usage
    if ($applied_coupon) {
        increment_coupon_usage($applied_coupon['code']);
    }
    
    $pdo->commit();
    
    // Store order info in session for payment processing
    $_SESSION['pending_order'] = [
        'order_id' => $order_id,
        'order_number' => $order_number,
        'total' => $total,
        'email' => $email,
        'payment_method' => $payment_method
    ];
    
    // Handle different payment methods
    switch ($payment_method) {
        case 'paypal':
            // Redirect to PayPal payment
            header('Location: ' . BASE_URL . '/payment/paypal.php?order=' . $order_number);
            exit;
            
        case 'paystack':
            // Redirect to Paystack payment
            header('Location: ' . BASE_URL . '/payment/paystack.php?order=' . $order_number);
            exit;
            
        case 'flutterwave':
            // Redirect to Flutterwave payment
            header('Location: ' . BASE_URL . '/payment/flutterwave.php?order=' . $order_number);
            exit;
            
        case 'eft':
        case 'bitcoin':
            // Manual payment - show pending page
            clear_cart();
            clear_coupon();
            set_flash_message('Order placed successfully! We will verify your payment and send download links shortly.', 'success');
            header('Location: ' . BASE_URL . '/order-pending.php?order=' . $order_number);
            exit;
            
        default:
            // Unknown payment method
            set_flash_message('Invalid payment method.', 'error');
            header('Location: ' . BASE_URL . '/checkout.php');
            exit;
    }
    
} catch (PDOException $e) {
    $pdo->rollBack();
    error_log('Order creation failed: ' . $e->getMessage());
    set_flash_message('An error occurred while processing your order. Please try again.', 'error');
    header('Location: ' . BASE_URL . '/checkout.php');
    exit;
}
?>