<?php
require_once ABSPATH . 'wp-content/themes/my-theme/payment/config.php';

// 1. Hook the registration function to the 'rest_api_init' action
add_action('rest_api_init', 'create_checkout_session_api_register_routes');

function create_checkout_session_api_register_routes()
{
    $namespace = 'api/v1'; // Namespace for your custom route prefixed with /wp-json/
    $route = '/create-checkout-session';          // The specific route segment

    register_rest_route($namespace, $route, array(
        'methods' => 'POST', // HTTP method (GET, POST, etc.)
        'callback' => 'create_checkout_session_api_callback', // Function to execute
        'permission_callback' => '__return_true', // Authentication check (true for public)
    ));
}

// 2. The Callback Function
function create_checkout_session_api_callback($request)
{
    global $wpdb;
    $params = $request->get_params();

    header('content-type: application/json');

    $user = get_user_by('login', $params['username']);

    $data = [];
    try {
        $products = $params['products'] ?? [];
        //echo '<pre>' . print_r($products, true) . '</pre>';
        if (empty($products)) {
            throw new Exception('The products array is required!');
        }

        // Create line_items
        $line_items = [];
        foreach ($products as $product) {
            if (empty($product['priceId'])) {
                throw new Exception('Each product must have a priceId!');
            }

            $line_items[] = [
                'price' => $product['priceId'],
                'quantity' => $product['quantity']
            ];
        }

        // Determine payment mode ("subscription" if price is recurring)
        $mode = "payment"; // default mode for one-time payment
        foreach ($products as $product) {
            try {
                $price = \Stripe\Price::retrieve($product['priceId']);
                if ($price->type === "recurring") {
                    $mode = "subscription";
                    break;
                }

            } catch (Exception $ex1) {
                // continue if price retrival fails for one product
                continue;
            }
        }

        // Create checkout session params
        $sessionParams = [
            'payment_method_types' => ['card'],
            'line_items' => $line_items,
            'mode' => $mode,
            'success_url' => 'http://' . $_SERVER['HTTP_HOST'] . '/+Websites/+Wordpress/xtra-market-wordpress/order-success/?session_id={CHECKOUT_SESSION_ID}',
            'cancel_url' => 'http://' . $_SERVER['HTTP_HOST'] . '/+Websites/+Wordpress/xtra-market-wordpress/order-cancel/',
            'customer_creation' => 'if_required',
            'metadata' => [
                'checkout_type' => 'multiple'
            ],
            'locale' => 'en'
        ];

        $session = \Stripe\Checkout\Session::create($sessionParams);

        $data = [
            'success' => true,
            'id' => $session->id,
            'mode' => $mode
        ];

    } catch (Exception $ex) {
        http_response_code(400);

        $data = [
            'success' => false,
            'error' => $ex->getMessage()
        ];
    }

    return new WP_REST_Response($data, 200);
}



