<?php
// File: checkout_handler.php (Fixed)
require_once 'session_init.php';
require_once 'db.php';
require_once 'phonepe_config.php'; 

// Security: Ensure user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}
$user_id = $_SESSION['user_id'];

// Security: Ensure cart is not empty
$cart_items = $_SESSION['cart'] ?? [];
if (empty($cart_items)) {
    header('Location: cart.php');
    exit();
}

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // 1. Sanitize Shipping Information
        $shipping_name = trim($_POST['shipping_name']);
        $shipping_address = trim($_POST['shipping_address']);
        $shipping_phone = trim($_POST['shipping_phone']);

        // 2. Recalculate Total Amount on the server
        $total_amount = 0;
        
        $painting_ids = array_keys($cart_items);
        $id_placeholders = implode(',', array_fill(0, count($painting_ids), '?'));
        $types = str_repeat('i', count($painting_ids));

        $stmt = $conn->prepare("SELECT id, title, price, sale_price FROM paintings WHERE id IN ($id_placeholders)");
        $stmt->bind_param($types, ...$painting_ids);
        $stmt->execute();
        $result = $stmt->get_result();

        $order_items_details = [];
        while ($row = $result->fetch_assoc()) {
            $price = (isset($row['sale_price']) && floatval($row['sale_price']) > 0) ? $row['sale_price'] : $row['price'];
            $quantity = $cart_items[$row['id']]['quantity'];
            $total_amount += $price * $quantity;
            
            $order_items_details[] = [
                'painting_id' => $row['id'],
                'quantity' => $quantity,
                'price_at_purchase' => $price
            ];
        }
        $stmt->close();
        
        // 3. Create a new order in the `orders` table
        $conn->begin_transaction();
        
        $merchantTransactionId = "UCF-ORDER-" . uniqid(); 
        
        $stmt_order = $conn->prepare("INSERT INTO orders (user_id, total_amount, payment_status, shipping_name, shipping_address, shipping_phone, merchant_transaction_id, order_date) VALUES (?, ?, 'pending', ?, ?, ?, ?, NOW())");
        
        // --- ⭐️⭐️⭐️ THIS IS THE FIX ⭐️⭐️⭐️ ---
        // Changed "idsssss" (7 characters) to "idssss" (6 characters)
        // This matches the 6 variables being passed.
        $stmt_order->bind_param("idssss", $user_id, $total_amount, $shipping_name, $shipping_address, $shipping_phone, $merchantTransactionId);
        // --- END OF FIX ---

        $stmt_order->execute();
        $order_id = $conn->insert_id; 
        $stmt_order->close();

        $stmt_items = $conn->prepare("INSERT INTO order_items (order_id, painting_id, quantity, price_at_purchase) VALUES (?, ?, ?, ?)");
        foreach ($order_items_details as $item) {
            $stmt_items->bind_param("iiid", $order_id, $item['painting_id'], $item['quantity'], $item['price_at_purchase']);
            $stmt_items->execute();
        }
        $stmt_items->close();
        
        $conn->commit();
        
        // 5. Redirect to PhonePe
        $amount_in_paise = $total_amount * 100;
        $redirect_url = "https://unitedculturalforum.com/order_status.php?order_id=" . $order_id;
        $callback_url = "https://unitedculturalforum.com/checkout_callback.php";

        $payload = [
            'merchantId' => $PHONEPE_MERCHANT_ID,
            'merchantTransactionId' => $merchantTransactionId,
            'merchantUserId' => $user_id,
            'amount' => $amount_in_paise,
            'redirectUrl' => $redirect_url,
            'redirectMode' => 'GET',
            'callbackUrl' => $callback_url, 
            'mobileNumber' => $shipping_phone,
            'paymentInstrument' => [ 'type' => 'PAY_PAGE' ],
        ];

        // --- Standard PhonePe cURL request ---
        $base64_payload = base64_encode(json_encode($payload));
        $hash_string = $base64_payload . $PHONEPE_PAY_ENDPOINT . $PHONEPE_SALT_KEY;
        $sha256_hash = hash('sha256', $hash_string);
        $x_verify_header = $sha256_hash . '###' . $PHONEPE_SALT_INDEX;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $PHONEPE_HOST_URL . $PHONEPE_PAY_ENDPOINT);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['request' => $base64_payload]));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'X-VERIFY: ' . $x_verify_header ]);
        $response = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        $json_response = json_decode($response, true);

        if ($http_status == 200 && isset($json_response['success']) && $json_response['success'] === true) {
            // Do NOT clear the cart yet. We clear it in order_status.php after payment is confirmed.
            $payment_page_url = $json_response['data']['instrumentResponse']['redirectInfo']['url'];
            header('Location: ' . $payment_page_url);
            exit();
        } else {
            throw new Exception("PhonePe initiation failed. Response: " . $response);
        }

    } else {
        header('Location: index.php');
        exit();
    }
} catch (Exception $e) {
    // This is the production-safe error handler
    if ($conn && $conn->inTransaction()) {
        $conn->rollback();
    }
    
    // Log the error for your records
    error_log("Checkout Handler FATAL Error: " . $e->getMessage());
    
    // Send the user back with a generic error
    header('Location: checkout.php?error=db_error');
    exit();
}
?>