<?php
// Checkout API - Save order to database
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');

require_once 'config.php';

// Handle request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    sendResponse(false, 'Invalid request method. Only POST is allowed');
}

try {
    // Get JSON data
    $input = json_decode(file_get_contents('php://input'), true);

    // Validate required fields
    if (!$input) {
        sendResponse(false, 'Invalid or empty JSON data');
    }

    if (!isset($input['fullName']) || !isset($input['email']) || !isset($input['phone']) || !isset($input['address'])) {
        sendResponse(false, 'Missing required fields: fullName, email, phone, address');
    }

    $fullName = trim($input['fullName']);
    $email = trim($input['email']);
    $phone = trim($input['phone']);
    $address = trim($input['address']);
    $paymentMethod = isset($input['paymentMethod']) ? trim($input['paymentMethod']) : 'cash-on-delivery';
    $userId = isset($input['userId']) ? (int)$input['userId'] : null;
    $items = isset($input['items']) ? $input['items'] : [];
    $subtotal = isset($input['subtotal']) ? (float)$input['subtotal'] : 0;
    $tax = isset($input['tax']) ? (float)$input['tax'] : 0;
    $total = isset($input['total']) ? (float)$input['total'] : 0;

    // Log the received data for debugging
    error_log('Checkout - UserId received: ' . ($userId === null ? 'NULL' : $userId) . ', UserId type: ' . gettype($userId));
    error_log('Checkout - Raw input userId: ' . (isset($input['userId']) ? $input['userId'] : 'NOT_SET'));

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        sendResponse(false, 'Invalid email format');
    }

    // Validate phone format (basic validation)
    if (!preg_match('/^[0-9\+\-\(\)\s]{7,}$/', $phone)) {
        sendResponse(false, 'Invalid phone number format');
    }

    // Check if cart has items
    if (empty($items)) {
        sendResponse(false, 'Cart is empty. Please add items before checkout');
    }

    // Start transaction
    $conn->begin_transaction();

    // Generate unique order number
    $orderNumber = 'ORD-' . date('YmdHis') . '-' . mt_rand(1000, 9999);

    // Insert order
    $insertOrderSql = "INSERT INTO orders (user_id, order_number, full_name, email, phone, address, payment_method, subtotal, tax, total, status) 
                       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')";
    
    $stmt = $conn->prepare($insertOrderSql);
    if (!$stmt) {
        throw new Exception('Prepare statement failed: ' . $conn->error);
    }

    $stmt->bind_param("issssssddd", $userId, $orderNumber, $fullName, $email, $phone, $address, $paymentMethod, $subtotal, $tax, $total);
    
    if (!$stmt->execute()) {
        throw new Exception('Execute failed: ' . $stmt->error);
    }

    $orderId = $conn->insert_id;
    $stmt->close();

    // Insert order items
    if (!empty($items)) {
        $insertItemsSql = "INSERT INTO order_items (order_id, item_name, quantity, price) VALUES (?, ?, ?, ?)";
        $stmtItems = $conn->prepare($insertItemsSql);
        
        if (!$stmtItems) {
            throw new Exception('Prepare statement failed for items: ' . $conn->error);
        }

        foreach ($items as $item) {
            $itemName = isset($item['name']) ? trim($item['name']) : '';
            $quantity = isset($item['quantity']) ? (int)$item['quantity'] : 0;
            $price = isset($item['price']) ? (float)$item['price'] : 0;

            if (empty($itemName) || $quantity <= 0) {
                throw new Exception('Invalid item data: name or quantity missing');
            }

            $stmtItems->bind_param("isid", $orderId, $itemName, $quantity, $price);
            
            if (!$stmtItems->execute()) {
                throw new Exception('Execute failed for items: ' . $stmtItems->error);
            }
        }
        $stmtItems->close();
    }

    // Commit transaction
    $conn->commit();

    // Log successful checkout
    error_log('Order created - Order ID: ' . $orderId . ', User ID: ' . ($userId === null ? 'NULL (Guest)' : $userId) . ', Email: ' . $email);

    // Return success response with order details
    sendResponse(true, 'Order placed successfully', [
        'orderId' => $orderId,
        'orderNumber' => $orderNumber,
        'userId' => $userId,
        'fullName' => $fullName,
        'email' => $email,
        'phone' => $phone,
        'address' => $address,
        'paymentMethod' => $paymentMethod,
        'subtotal' => $subtotal,
        'tax' => $tax,
        'total' => $total,
        'itemCount' => count($items),
        'status' => 'pending',
        'createdAt' => date('Y-m-d H:i:s')
    ]);

} catch (Exception $e) {
    // Rollback transaction on error
    if ($conn) {
        $conn->rollback();
    }
    
    error_log('Checkout error: ' . $e->getMessage());
    http_response_code(400);
    sendResponse(false, 'Failed to place order: ' . $e->getMessage());

} catch (Error $e) {
    // Handle fatal errors
    if ($conn) {
        $conn->rollback();
    }
    
    error_log('Checkout fatal error: ' . $e->getMessage());
    http_response_code(500);
    sendResponse(false, 'Server error: ' . $e->getMessage());
}

if ($conn) {
    $conn->close();
}
?>

