<?php
/**
 * UPI PAYMENT API
 * Handles UPI payment processing, verification, and order creation
 * 
 * Endpoints:
 * 1. POST /upi-payment-api.php?action=generate_qr
 * 2. POST /upi-payment-api.php?action=verify_upi
 * 3. GET /upi-payment-api.php?action=check_payment_status
 * 4. POST /upi-payment-api.php?action=process_payment
 */

session_start();
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 0);

// Enable error logging
$log_file = __DIR__ . '/upi-payment-api.log';
ini_set('log_errors', 1);
ini_set('error_log', $log_file);

// Database connection
$host = 'localhost';
$db = 'zemaraim_interior';
$user = 'zemaraim';
$password = '8wwxk]-X3Kx]CJ]5';

$conn = new mysqli($host, $user, $password, $db);

if ($conn->connect_error) {
    http_response_code(500);
    die(json_encode(['success' => false, 'message' => 'Database connection failed: ' . $conn->connect_error]));
}

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'User not authenticated']);
    exit;
}

$user_id = $_SESSION['user_id'];
$action = $_GET['action'] ?? '';

// Wrap in try-catch for better error handling
try {
    // Handle different UPI actions
    switch ($action) {
        case 'generate_qr':
            generateUPIQRCode();
            break;
        case 'verify_upi':
            verifyUPIPayment();
            break;
        case 'check_payment_status':
            checkPaymentStatus();
            break;
        case 'process_payment':
            processUPIPayment();
            break;
        default:
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
} catch (Exception $e) {
    http_response_code(500);
    error_log("UPI API Error: " . $e->getMessage() . " | Trace: " . $e->getTraceAsString());
    echo json_encode(['success' => false, 'message' => 'An error occurred: ' . $e->getMessage()]);
}

/**
 * Generate UPI QR Code
 */
function generateUPIQRCode() {
    global $conn, $user_id;
    
    try {
        $raw_input = file_get_contents('php://input');
        $data = json_decode($raw_input, true);
        
        if (!$data || !isset($data['amount'])) {
            throw new Exception("Invalid request: amount required");
        }

        $amount = floatval($data['amount']);
        $merchant_upi = getConfigValue('MERCHANT_UPI', 'mohamedhalith117@okaxis');
        $merchant_name = getConfigValue('MERCHANT_NAME', 'Interior Design Store');
        $transaction_ref = 'ORD-' . $user_id . '-' . time();
        
        // Create UPI string
        $upi_string = sprintf(
            'upi://pay?pa=%s&pn=%s&am=%s&tn=%s&tr=%s',
            urlencode($merchant_upi),
            urlencode($merchant_name),
            $amount,
            urlencode('Order Payment'),
            urlencode($transaction_ref)
        );
        
        // Generate QR code URL using qrserver API
        $qr_code_url = 'https://api.qrserver.com/v1/create-qr-code/?size=250x250&data=' . urlencode($upi_string);
        
        // Store transaction in database
        $stmt = $conn->prepare("
            INSERT INTO upi_transactions (user_id, transaction_ref, amount, upi_string, qr_code_url, status, created_at)
            VALUES (?, ?, ?, ?, ?, 'pending', NOW())
        ");
        
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        $stmt->bind_param("isdss", $user_id, $transaction_ref, $amount, $upi_string, $qr_code_url);
        
        if (!$stmt->execute()) {
            throw new Exception("Execute failed: " . $stmt->error);
        }
        
        $transaction_id = $conn->insert_id;
        $stmt->close();
        
        // Return success response
        echo json_encode([
            'success' => true,
            'message' => 'QR code generated successfully',
            'data' => [
                'transaction_id' => $transaction_id,
                'qr_code_url' => $qr_code_url,
                'upi_string' => $upi_string,
                'merchant_upi' => $merchant_upi,
                'merchant_name' => $merchant_name,
                'amount' => $amount,
                'transaction_ref' => $transaction_ref
            ]
        ]);
        
    } catch (Exception $e) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
}

/**
 * Verify UPI Payment
 */
function verifyUPIPayment() {
    global $conn, $user_id;
    
    try {
        $raw_input = file_get_contents('php://input');
        $data = json_decode($raw_input, true);
        
        if (!$data || !isset($data['upi_id']) || !isset($data['transaction_id'])) {
            throw new Exception("Invalid request: upi_id and transaction_id required");
        }

        $upi_id = trim($data['upi_id']);
        $transaction_id = intval($data['transaction_id']);
        
        // Validate UPI ID format
        if (!preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z]{3,}$/', $upi_id)) {
            throw new Exception("Invalid UPI ID format");
        }
        
        // Get transaction details
        $stmt = $conn->prepare("SELECT * FROM upi_transactions WHERE id = ? AND user_id = ?");
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        $stmt->bind_param("ii", $transaction_id, $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $transaction = $result->fetch_assoc();
        $stmt->close();
        
        if (!$transaction) {
            throw new Exception("Transaction not found");
        }
        
        // Update transaction with UPI ID
        $stmt = $conn->prepare("
            UPDATE upi_transactions 
            SET upi_id = ?, verified_at = NOW()
            WHERE id = ?
        ");
        
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        $stmt->bind_param("si", $upi_id, $transaction_id);
        
        if (!$stmt->execute()) {
            throw new Exception("Execute failed: " . $stmt->error);
        }
        
        $stmt->close();
        
        echo json_encode([
            'success' => true,
            'message' => 'UPI verified successfully',
            'data' => [
                'transaction_id' => $transaction_id,
                'upi_id' => $upi_id,
                'status' => 'verified'
            ]
        ]);
        
    } catch (Exception $e) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
}

/**
 * Check Payment Status
 */
function checkPaymentStatus() {
    global $conn, $user_id;
    
    try {
        $transaction_id = intval($_GET['transaction_id'] ?? 0);
        
        if (!$transaction_id) {
            throw new Exception("transaction_id required");
        }
        
        // Get transaction status
        $stmt = $conn->prepare("
            SELECT id, status, amount, transaction_ref, created_at, verified_at 
            FROM upi_transactions 
            WHERE id = ? AND user_id = ?
        ");
        
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        $stmt->bind_param("ii", $transaction_id, $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $transaction = $result->fetch_assoc();
        $stmt->close();
        
        if (!$transaction) {
            throw new Exception("Transaction not found");
        }
        
        echo json_encode([
            'success' => true,
            'data' => $transaction
        ]);
        
    } catch (Exception $e) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
}

/**
 * Process UPI Payment (Create Order)
 */
function processUPIPayment() {
    global $conn, $user_id;
    
    try {
        $raw_input = file_get_contents('php://input');
        $data = json_decode($raw_input, true);
        
        if (!$data || !isset($data['transaction_id'])) {
            throw new Exception("Invalid request: transaction_id required");
        }

        $transaction_id = intval($data['transaction_id']);
        
        // Get transaction details
        $stmt = $conn->prepare("
            SELECT * FROM upi_transactions 
            WHERE id = ? AND user_id = ? AND status = 'pending'
        ");
        
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        $stmt->bind_param("ii", $transaction_id, $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $transaction = $result->fetch_assoc();
        $stmt->close();
        
        if (!$transaction) {
            throw new Exception("Transaction not found or already processed");
        }
        
        // Get user details
        $user_stmt = $conn->prepare("SELECT email, name FROM users WHERE id = ?");
        if (!$user_stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        $user_stmt->bind_param("i", $user_id);
        $user_stmt->execute();
        $user_result = $user_stmt->get_result();
        $user = $user_result->fetch_assoc();
        $user_stmt->close();
        
        if (!$user) {
            throw new Exception("User not found");
        }
        
        // Get cart items
        $cart_stmt = $conn->prepare("SELECT * FROM cart WHERE user_id = ?");
        if (!$cart_stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        $cart_stmt->bind_param("i", $user_id);
        $cart_stmt->execute();
        $cart_result = $cart_stmt->get_result();
        $cart_items = [];
        $subtotal = 0;
        
        while ($item = $cart_result->fetch_assoc()) {
            $item_total = $item['price'] * $item['quantity'];
            $subtotal += $item_total;
            $cart_items[] = $item;
        }
        $cart_stmt->close();
        
        if (empty($cart_items)) {
            throw new Exception("Cart is empty");
        }
        
        // Calculate totals
        $shipping = 500;
        $tax = round($subtotal * 0.1, 2);
        $total = $subtotal + $shipping + $tax;
        
        // Verify amount matches
        if (floatval($transaction['amount']) != $total) {
            throw new Exception("Amount mismatch. Expected: " . $total . ", Got: " . $transaction['amount']);
        }
        
        // Create order
        $order_number = 'ORD-' . time();
        $shipping_address = $data['shipping_address'] ?? $data['billing_address'] ?? [];
        $shipping_address_json = json_encode($shipping_address);
        
        $order_stmt = $conn->prepare("
            INSERT INTO orders (
                user_id, order_number, subtotal, tax, shipping, total, 
                payment_method, status, created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, 'upi', 'pending', NOW(), NOW())
        ");
        
        if (!$order_stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        $order_stmt->bind_param(
            "isdddd",
            $user_id,
            $order_number,
            $subtotal,
            $tax,
            $shipping,
            $total
        );
        
        if (!$order_stmt->execute()) {
            throw new Exception("Execute failed: " . $order_stmt->error);
        }
        
        $order_id = $conn->insert_id;
        $order_stmt->close();
        
        // Insert order items
        foreach ($cart_items as $item) {
            $item_stmt = $conn->prepare("
                INSERT INTO order_items (order_id, product_id, product_name, price, quantity, image)
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            
            if (!$item_stmt) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            
            $item_stmt->bind_param(
                "iisids",
                $order_id,
                $item['product_id'],
                $item['product_name'],
                $item['price'],
                $item['quantity'],
                $item['image']
            );
            
            if (!$item_stmt->execute()) {
                throw new Exception("Execute failed: " . $item_stmt->error);
            }
            
            $item_stmt->close();
        }
        
        // Update transaction status to completed
        $update_stmt = $conn->prepare("
            UPDATE upi_transactions 
            SET status = 'completed', order_id = ?, completed_at = NOW()
            WHERE id = ?
        ");
        
        if (!$update_stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        $update_stmt->bind_param("ii", $order_id, $transaction_id);
        
        if (!$update_stmt->execute()) {
            throw new Exception("Execute failed: " . $update_stmt->error);
        }
        
        $update_stmt->close();
        
        // Clear cart
        $clear_stmt = $conn->prepare("DELETE FROM cart WHERE user_id = ?");
        if ($clear_stmt) {
            $clear_stmt->bind_param("i", $user_id);
            $clear_stmt->execute();
            $clear_stmt->close();
        }
        
        // Send confirmation email
        sendConfirmationEmail($user['email'], $user['name'], $order_number, $order_id, $total);
        
        echo json_encode([
            'success' => true,
            'message' => 'Payment processed successfully',
            'data' => [
                'order_id' => $order_id,
                'order_number' => $order_number,
                'amount' => $total,
                'status' => 'completed',
                'redirect' => 'order-confirmation.php?order_id=' . $order_id
            ]
        ]);
        
    } catch (Exception $e) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
}

/**
 * Send confirmation email
 */
function sendConfirmationEmail($email, $name, $order_number, $order_id, $total) {
    $subject = "Order Confirmation - " . $order_number;
    $message = "
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; background-color: #f5f5f5; }
            .container { max-width: 600px; margin: 0 auto; background-color: white; padding: 20px; border-radius: 8px; }
            .header { text-align: center; border-bottom: 2px solid #d4a574; padding-bottom: 20px; margin-bottom: 20px; }
            .header h1 { color: #333; margin: 0; }
            .content { margin: 20px 0; }
            .order-details { background-color: #f9f9f9; padding: 15px; border-radius: 5px; margin: 15px 0; }
            .footer { text-align: center; color: #999; font-size: 12px; margin-top: 30px; padding-top: 20px; border-top: 1px solid #ddd; }
        </style>
    </head>
    <body>
        <div class=\"container\">
            <div class=\"header\">
                <h1>✅ Order Confirmed!</h1>
            </div>
            
            <div class=\"content\">
                <p>Dear <strong>$name</strong>,</p>
                
                <p>Thank you for your order! Your payment has been successfully received via UPI.</p>
                
                <div class=\"order-details\">
                    <p><strong>Order Number:</strong> $order_number</p>
                    <p><strong>Order ID:</strong> #$order_id</p>
                    <p><strong>Total Amount:</strong> Rs. " . number_format($total, 2) . "</p>
                    <p><strong>Payment Method:</strong> UPI</p>
                    <p><strong>Status:</strong> Pending Confirmation</p>
                </div>
                
                <p>Your order is now being processed. You can track your order status by logging into your account.</p>
                
                <p>We appreciate your business!</p>
                
                <p>Best regards,<br>Interior Design Store</p>
            </div>
            
            <div class=\"footer\">
                <p>This is an automated email. Please do not reply to this email.</p>
            </div>
        </div>
    </body>
    </html>
    ";
    
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=UTF-8\r\n";
    $headers .= "From: support@interiordesign.com\r\n";
    
    mail($email, $subject, $message, $headers);
}

/**
 * Get configuration value
 */
function getConfigValue($key, $default = '') {
    global $conn;
    
    $stmt = $conn->prepare("SELECT value FROM upi_config WHERE `key` = ?");
    if (!$stmt) {
        return $default;
    }
    
    $stmt->bind_param("s", $key);
    $stmt->execute();
    $result = $stmt->get_result();
    $config = $result->fetch_assoc();
    $stmt->close();
    
    return $config ? $config['value'] : $default;
}
?>
