<?php

if ( ! defined( 'ABSPATH' ) ) exit;
/**
 * 1. THE ORDER PROCESSING ENGINE
 * Handles the order saving before the page renders
 */
add_action('wp_loaded', 'afdp_master_checkout_handler');
function afdp_master_checkout_handler() {
    // Catch AJAX Order Submission
    if (isset($_POST['afdp_place_order'])) {
        if (ob_get_length()) ob_clean();
        header('Content-Type: application/json');

        // Security Check (Nonce)
        $nonce = isset($_POST['afdp_nonce']) ? sanitize_key($_POST['afdp_nonce']) : '';
        if (!wp_verify_nonce($nonce, 'afdp_place_order_action')) {
            echo json_encode(['status' => 'error', 'message' => 'Security check failed. Please refresh.']);
            exit;
        }

        $data = json_decode(stripslashes($_POST['afdp_place_order']), true);
        if (!$data || empty($data['cart'])) {
            echo json_encode(['status' => 'error', 'message' => 'Your cart is empty.']);
            exit;
        }

        $user_id = get_current_user_id() ?: 0;
        
        // Insert the Order Post
        $order_id = wp_insert_post([
            'post_type'   => 'afdp_food_order',
            'post_title'  => 'Order #' . time() . ' - ' . sanitize_text_field($data['fullName']),
            'post_status' => 'publish',
            'post_author' => $user_id
        ]);

        if ($order_id && !is_wp_error($order_id)) {
            // Store Metadata for Admin and History
            update_post_meta($order_id, 'afdp_order_type', sanitize_text_field($data['orderType']));
            update_post_meta($order_id, 'afdp_payment_method', sanitize_text_field($data['paymentMethod']));
            update_post_meta($order_id, 'afdp_customer_name', sanitize_text_field($data['fullName']));
            update_post_meta($order_id, 'afdp_customer_phone', sanitize_text_field($data['phone']));
            update_post_meta($order_id, 'afdp_customer_address', sanitize_textarea_field($data['address']));
            update_post_meta($order_id, 'afdp_order_items', $data['cart']); 
            update_post_meta($order_id, 'afdp_total_price', floatval($data['total']));
            update_post_meta($order_id, 'afdp_order_status', 'pending');

            echo json_encode(['status' => 'success', 'order_id' => $order_id]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'System error: Database write failed.']);
        }
        exit; // Important: Prevents page HTML from being appended to JSON
    }
}

/**
 * 2. THE CHECKOUT UI SHORTCODE
 */
add_shortcode('afdp_checkout', 'afdp_checkout_shortcode');
function afdp_checkout_shortcode() {
    // A. LOGIN CHECK: Redirect guests to Login Page
    if (!is_user_logged_in()) {
        $login_url = home_url('/afdp-login/');
        echo "<script>window.location.href='" . esc_url($login_url) . "';</script>";
        return '<div style="text-align:center; padding:100px; font-family:sans-serif; color:#64748b;">Redirecting to login...</div>';
    }

    // B. LOAD SETTINGS
    $u = wp_get_current_user();
    $currency_code = get_option('afdp_currency', 'USD');
    $symbols = ['USD'=>'$', 'GBP'=>'£', 'EUR'=>'€', 'INR'=>'₹', 'AED'=>'د.إ', 'BDT'=>'৳', 'CAD'=>'C$', 'SAR'=>'SR'];
    $currency = isset($symbols[$currency_code]) ? $symbols[$currency_code] : '$';
    
    $delivery_fee = (float) get_option('afdp_delivery_fee', 3.50);
    $cod_enabled  = get_option('afdp_enable_cod', 'yes');
    $bacs_enabled = get_option('afdp_enable_bacs', 'no');

    ob_start();
    ?>

    <style>
        .afdp-checkout-wrapper { max-width: 1140px; margin: 40px auto; font-family: 'Plus Jakarta Sans', sans-serif; color: #1e293b; }
        .afdp-row { display: flex; flex-wrap: wrap; gap: 30px; }
        .afdp-col-left { flex: 1 1 600px; }
        .afdp-col-right { flex: 0 0 380px; }

        .afdp-card { background: #fff; border-radius: 20px; padding: 30px; border: 1px solid #e2e8f0; margin-bottom: 25px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05); }
        .afdp-card-h { font-size: 19px; font-weight: 800; margin-bottom: 25px; color: #0f172a; display: flex; align-items: center; gap: 10px; }
        
        .afdp-input-wrap { margin-bottom: 15px; }
        .afdp-label { display: block; font-weight: 700; font-size: 13px; color: #64748b; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.5px; }
        .afdp-input { width: 100%; padding: 14px 18px; border-radius: 12px; border: 2px solid #f1f5f9; font-size: 15px; transition: 0.3s; background: #fcfdfe; }
        .afdp-input:focus { border-color: #FF385C; outline: none; background: #fff; box-shadow: 0 0 0 4px rgba(255, 56, 92, 0.05); }
        
        /* Toggle Selectors */
        .afdp-selector-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }
        .afdp-selector-item input { display: none; }
        .afdp-selector-item label { 
            display: block; padding: 18px; text-align: center; border: 2px solid #f1f5f9; 
            border-radius: 16px; cursor: pointer; font-weight: 800; transition: 0.3s; background: #f8fafc;
        }
        .afdp-selector-item input:checked + label { border-color: #FF385C; background: #fff; color: #FF385C; box-shadow: 0 10px 15px -3px rgba(255, 56, 92, 0.1); }

        /* Dark Premium Summary */
        .afdp-sidebar { background: #0f172a; color: white; border-radius: 24px; padding: 35px; position: sticky; top: 20px; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1); }
        .afdp-sidebar h3 { margin-top: 0; font-weight: 800; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 15px; }
        .afdp-sum-row { display: flex; justify-content: space-between; margin-bottom: 15px; font-size: 14px; color: #94a3b8; }
        .afdp-divider { height: 1px; background: rgba(255,255,255,0.1); margin: 20px 0; }
        .afdp-total { display: flex; justify-content: space-between; align-items: center; font-size: 26px; font-weight: 800; color: #fff; }
        
        .afdp-place-btn { 
            width: 100%; background: #FF385C; color: white; border: none; padding: 20px; 
            border-radius: 16px; font-weight: 800; font-size: 17px; cursor: pointer; 
            margin-top: 25px; transition: 0.3s; box-shadow: 0 10px 15px -3px rgba(255, 56, 92, 0.3);
        }
        .afdp-place-btn:hover { background: #e11d48; transform: translateY(-2px); }
        .afdp-place-btn:disabled { background: #334155; cursor: not-allowed; transform: none; box-shadow: none; }

        @media (max-width: 900px) { .afdp-col-right { flex: 1 1 100%; } }
    </style>

    <div class="afdp-checkout-wrapper">
        <div class="afdp-row">
            
            <div class="afdp-col-left">
                <div class="afdp-card">
                    <div class="afdp-card-h"><span class="dashicons dashicons-location"></span> Fulfillment Method</div>
                    <div class="afdp-selector-grid">
                        <div class="afdp-selector-item">
                            <input type="radio" name="afdp_type" id="afdp_del" value="delivery" checked>
                            <label for="afdp_del">🚀 Delivery</label>
                        </div>
                        <div class="afdp-selector-item">
                            <input type="radio" name="afdp_type" id="afdp_pick" value="pickup">
                            <label for="afdp_pick">🥡 Store Pickup</label>
                        </div>
                    </div>
                </div>

                <div class="afdp-card">
                    <div class="afdp-card-h"><span class="dashicons dashicons-admin-users"></span> Contact Details</div>
                    <div class="afdp-row">
                        <div style="flex:1" class="afdp-input-wrap">
                            <label class="afdp-label">Full Name</label>
                            <input type="text" id="afdp_fullName" class="afdp-input" value="<?php echo esc_attr($u->display_name); ?>">
                        </div>
                        <div style="flex:1" class="afdp-input-wrap">
                            <label class="afdp-label">Phone Number</label>
                            <input type="tel" id="afdp_phone" class="afdp-input" value="<?php echo esc_attr(get_user_meta($u->ID, 'phone', true)); ?>">
                        </div>
                    </div>
                    <div id="afdp_address_area" class="afdp-input-wrap">
                        <label class="afdp-label">Delivery Address</label>
                        <textarea id="afdp_address" class="afdp-input" rows="3" placeholder="House/Flat No, Street, Landmark..."><?php echo esc_textarea(get_user_meta($u->ID, 'address', true)); ?></textarea>
                    </div>
                </div>

                <div class="afdp-card">
                    <div class="afdp-card-h"><span class="dashicons dashicons-cart"></span> Payment Method</div>
                    <div class="afdp-selector-grid">
                        <?php if($cod_enabled === 'yes'): ?>
                        <div class="afdp-selector-item">
                            <input type="radio" name="afdp_pay" id="afdp_pay_cod" value="cod" checked>
                            <label for="afdp_pay_cod">Cash on Delivery</label>
                        </div>
                        <?php endif; ?>
                        <?php if($bacs_enabled === 'yes'): ?>
                        <div class="afdp-selector-item">
                            <input type="radio" name="afdp_pay" id="afdp_pay_bank" value="bacs">
                            <label for="afdp_pay_bank">Bank Transfer</label>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="afdp-col-right">
                <div class="afdp-sidebar">
                    <h3>Order Summary</h3>
                    <div id="afdp_cart_render"></div>
                    
                    <div class="afdp_calc_area" style="margin-top:20px;">
                        <div class="afdp-sum-row"><span>Subtotal</span><span id="afdp_txt_sub">0.00</span></div>
                        <div class="afdp-sum-row" id="afdp_row_fee"><span>Delivery Fee</span><span id="afdp_txt_fee">0.00</span></div>
                    </div>

                    <div class="afdp-divider"></div>

                    <div class="afdp-total">
                        <span style="font-size: 14px; opacity: 0.6; font-weight: 400;">Total</span>
                        <span><?php echo esc_attr($currency); ?><span id="afdp_txt_total">0.00</span></span>
                    </div>

                    <?php wp_nonce_field('afdp_place_order_action', 'afdp_nonce_id'); ?>
                    <button id="afdp_btn_confirm" class="afdp-place-btn">CONFIRM ORDER</button>
                </div>
            </div>

        </div>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const cart = JSON.parse(localStorage.getItem('afdp_final_cart')) || [];
        const deliveryFee = <?php echo (float) $delivery_fee; ?>;
const currency = "<?php echo esc_js( $currency ); ?>";

        function updateDisplay() {
            const isPickup = document.getElementById('afdp_pick').checked;
            const container = document.getElementById('afdp_cart_render');
            
            // Toggle Address & Fee
            document.getElementById('afdp_address_area').style.display = isPickup ? 'none' : 'block';
            document.getElementById('afdp_row_fee').style.display = isPickup ? 'none' : 'flex';

            if(cart.length === 0) {
                container.innerHTML = '<p style="color:#94a3b8">Basket is empty.</p>';
                document.getElementById('afdp_btn_confirm').disabled = true;
                return;
            }

            let subtotal = 0;
            container.innerHTML = cart.map(item => {
                let itemTotal = parseFloat(item.unitPrice) * parseInt(item.qty);
                subtotal += itemTotal;
                return `<div class="afdp-sum-row"><span>${item.qty}x ${item.title}</span><span>${currency}${itemTotal.toFixed(2)}</span></div>`;
            }).join('');

            const finalFee = isPickup ? 0 : deliveryFee;
            document.getElementById('afdp_txt_sub').innerText = currency + subtotal.toFixed(2);
            document.getElementById('afdp_txt_fee').innerText = currency + finalFee.toFixed(2);
            document.getElementById('afdp_txt_total').innerText = (subtotal + finalFee).toFixed(2);
        }

        // Fulfillment Change Listeners
        document.querySelectorAll('input[name="afdp_type"]').forEach(r => r.addEventListener('change', updateDisplay));

        // Submit Logic
        document.getElementById('afdp_btn_confirm').addEventListener('click', function() {
            const btn = this;
            const orderType = document.querySelector('input[name="afdp_type"]:checked').value;
            const payMethod = document.querySelector('input[name="afdp_pay"]:checked')?.value;

            const payload = {
                fullName: document.getElementById('afdp_fullName').value,
                phone: document.getElementById('afdp_phone').value,
                address: orderType === 'delivery' ? document.getElementById('afdp_address').value : 'Store Pickup',
                orderType: orderType,
                paymentMethod: payMethod,
                cart: cart,
                total: document.getElementById('afdp_txt_total').innerText,
                email: '<?php echo esc_js( $u->user_email ); ?>'
            };

            if(!payload.fullName || !payload.phone || (orderType === 'delivery' && !payload.address)) {
                alert('Please fill in all delivery details.');
                return;
            }

            btn.disabled = true;
            btn.innerText = "PROCESSING...";

            const fd = new FormData();
            fd.append('afdp_place_order', JSON.stringify(payload));
            fd.append('afdp_nonce', document.getElementById('afdp_nonce_id').value);

            fetch(window.location.href, { method: 'POST', body: fd })
            .then(res => res.json())
            .then(res => {
                if(res.status === 'success') {
                    localStorage.removeItem('afdp_final_cart');
                    window.location.href = "<?php echo esc_url( home_url( '/afdp-thanks/' ) ); ?>?order_id=" + res.order_id;
                } else {
                    alert(res.message);
                    btn.disabled = false;
                    btn.innerText = "CONFIRM ORDER";
                }
            })
            .catch(() => {
                alert('Connection Error. Please check your internet.');
                btn.disabled = false;
            });
        });

        updateDisplay();
    });
    </script>

    <?php
    return ob_get_clean();
}