<?php 

if ( ! defined( 'ABSPATH' ) ) exit;
/**
 * Shortcode for User Account Dashboard
 * Usage: [afdp_account]
 */
add_shortcode('afdp_account', 'afdp_custom_account_dashboard');

function afdp_custom_account_dashboard() {
    if (!is_user_logged_in()) {
        return '<div style="text-align:center; padding:50px;"><p>Please log in to view your account.</p><a href="' . wp_login_url(get_permalink()) . '" class="afdp-btn-red-action">Log In</a></div>';
    }

    $current_user = wp_get_current_user();
    $user_id = $current_user->ID;
    $success_msg = '';
    $error_msg   = '';
    
    // Get dynamic currency from settings
    $afdp_currency_code = get_option('afdp_currency', 'USD');
    $afdp_symbols = ['USD'=>'$','GBP'=>'£','EUR'=>'€','INR'=>'₹','BDT'=>'৳','AUD'=>'A$','CAD'=>'C$','JPY'=>'¥','AED'=>'د.إ','SAR'=>'SR'];
    $currency = isset($afdp_symbols[$afdp_currency_code]) ? $afdp_symbols[$afdp_currency_code] : $afdp_currency_code;

    // --- HANDLE PROFILE UPDATE ---
    if (isset($_POST['update_profile']) && isset($_POST['afdp_profile_nonce'])) {
        if (wp_verify_nonce(sanitize_key(wp_unslash($_POST['afdp_profile_nonce'])), 'afdp_update_profile_action')) {
            $first_name = isset($_POST['first_name']) ? sanitize_text_field(wp_unslash($_POST['first_name'])) : '';
            $last_name  = isset($_POST['last_name']) ? sanitize_text_field(wp_unslash($_POST['last_name'])) : '';
            $full_name  = isset($_POST['full_name']) ? sanitize_text_field(wp_unslash($_POST['full_name'])) : '';
            $phone      = isset($_POST['phone']) ? sanitize_text_field(wp_unslash($_POST['phone'])) : '';
            $address    = isset($_POST['address']) ? sanitize_textarea_field(wp_unslash($_POST['address'])) : '';

            wp_update_user([
                'ID'           => $user_id,
                'first_name'   => $first_name,
                'last_name'    => $last_name,
                'display_name' => $full_name,
            ]);

            update_user_meta($user_id, 'phone', $phone);
            update_user_meta($user_id, 'address', $address);

            $success_msg = 'Profile details updated successfully!';
            $current_user = wp_get_current_user(); 
        }
    }

    // --- HANDLE PASSWORD UPDATE ---
    if (isset($_POST['update_password']) && isset($_POST['afdp_password_nonce'])) {
        if (wp_verify_nonce(sanitize_key(wp_unslash($_POST['afdp_password_nonce'])), 'afdp_update_password_action')) {
            $current_pass = isset($_POST['current_password']) ? wp_unslash($_POST['current_password']) : '';
            $new_pass     = isset($_POST['new_password']) ? wp_unslash($_POST['new_password']) : '';
            $confirm_pass = isset($_POST['confirm_password']) ? wp_unslash($_POST['confirm_password']) : '';

            if (!wp_check_password($current_pass, $current_user->user_pass, $user_id)) {
                $error_msg = 'Current password is incorrect.';
            } elseif ($new_pass !== $confirm_pass) {
                $error_msg = 'New passwords do not match.';
            } elseif (strlen($new_pass) < 6) {
                $error_msg = 'Password must be at least 6 characters.';
            } else {
                wp_set_password($new_pass, $user_id);
                $success_msg = 'Password updated successfully!';
                wp_set_auth_cookie($user_id); 
            }
        }
    }

    $user_phone   = get_user_meta($user_id, 'phone', true);
    $user_address = get_user_meta($user_id, 'address', true);

    ob_start();
    ?>

    <style>
        .afdp-dashboard-wrapper { font-family: 'Plus Jakarta Sans', sans-serif; margin-bottom: 50px; }
        .afdp-nav-column .nav-link { color: #64748B; font-weight: 700; padding: 14px 20px; border-radius: 12px; margin-bottom: 8px; border: none; text-align: left; transition: 0.3s; }
        .afdp-nav-column .nav-link:hover { background: #f1f5f9; color: #0f172a; }
        .afdp-nav-column .nav-link.active { background: #FF385C !important; color: #fff !important; box-shadow: 0 4px 12px rgba(255, 56, 92, 0.2); }
        .afdp-content-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 24px; padding: 35px; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.04); }
        .afdp-status-badge { padding: 5px 12px; border-radius: 8px; font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px; }
        .afdp-status-pending { background: #FEF3C7; color: #D97706; }
        .afdp-status-processing { background: #DBEAFE; color: #2563EB; }
        .afdp-status-completed { background: #DCFCE7; color: #166534; }
        .afdp-btn-red-action { background: #0F172A; color: #fff; border: none; padding: 14px 28px; border-radius: 12px; font-weight: 700; text-decoration: none; display: inline-block; cursor: pointer; transition: 0.3s; border: 1px solid transparent; }
        .afdp-btn-red-action:hover { background: #FF385C; color: #fff; transform: translateY(-2px); }
        .afdp-form-control-custom { border-radius: 12px; border: 1px solid #E2E8F0; padding: 12px 18px; background: #fcfdfe; transition: 0.3s; }
        .afdp-form-control-custom:focus { border-color: #FF385C; background: #fff; box-shadow: 0 0 0 4px rgba(255, 56, 92, 0.05); outline: none; }
        .afdp-order-table th { border-top: none; color: #94a3b8; font-weight: 600; text-transform: uppercase; font-size: 12px; }
    </style>

    <div class="container my-5 afdp-dashboard-wrapper">
        <div class="row">
            <div class="col-lg-3 col-md-4 mb-4">
                <div class="afdp-nav-column nav flex-column nav-pills" id="afdp-v-pills-tab" role="tablist">
                    <button class="nav-link active" data-bs-toggle="pill" data-bs-target="#afdp-content-dashboard" type="button" role="tab">👋 Dashboard</button>
                    <button class="nav-link" data-bs-toggle="pill" data-bs-target="#afdp-content-orders" type="button" role="tab">📦 My Orders</button>
                    <button class="nav-link" data-bs-toggle="pill" data-bs-target="#afdp-content-profile" type="button" role="tab">👤 Edit Profile</button>
                    <button class="nav-link" data-bs-toggle="pill" data-bs-target="#afdp-content-password" type="button" role="tab">🔒 Security</button>
                    <a class="nav-link text-danger mt-3" href="<?php echo esc_url(wp_logout_url(home_url())); ?>">Logout</a>
                </div>
            </div>

            <div class="col-lg-9 col-md-8">
                <div class="tab-content afdp-content-card">

                    <div class="tab-pane fade show active" id="afdp-content-dashboard" role="tabpanel">
                        <h3 class="fw-bold mb-3">Hello, <?php echo esc_html($current_user->first_name ?: $current_user->display_name); ?>!</h3>
                        <p class="text-muted mb-4">Welcome back to your kitchen dashboard. Track your cravings and manage your delivery details here.</p>
                        <div class="row">
                            <div class="col-md-6">
                                <div style="background: #f8fafc; padding: 20px; border-radius: 15px; border: 1px dashed #cbd5e1;">
                                    <h6 class="fw-bold mb-1">Saved Address</h6>
                                    <p class="small text-muted mb-0"><?php echo $user_address ? esc_html($user_address) : 'No address saved yet.'; ?></p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="afdp-content-orders" role="tabpanel">
                        <h3 class="fw-bold mb-4">Order History</h3>
                        <?php
                        // Updated Query: Looking for orders where user is the AUTHOR or CUSTOMER ID
                        $orders = get_posts([
                            'post_type'      => 'afdp_food_order',
                            'author'         => $user_id, // Fetch by logged in user ID
                            'posts_per_page' => -1,
                            'post_status'    => 'publish',
                        ]);

                        if($orders): ?>
                            <div class="table-responsive">
                                <table class="table align-middle afdp-order-table">
                                    <thead>
                                        <tr>
                                            <th>ORDER</th>
                                            <th>DATE</th>
                                            <th>STATUS</th>
                                            <th>TOTAL</th>
                                            <th>ACTIONS</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach($orders as $order):
                                            $order_status = get_post_meta($order->ID, 'afdp_order_status', true) ?: 'pending';
                                            $total        = get_post_meta($order->ID, 'afdp_total_price', true) ?: 0;
                                        ?>
                                        <tr>
                                            <td><strong>#<?php echo esc_html( $order->ID ); ?></strong></td>
                                            <td class="small text-muted"><?php echo esc_html( get_the_date( 'j M, Y', $order->ID ) ); ?></td>
                                            <td><span class="afdp-status-badge afdp-status-<?php echo esc_attr($order_status); ?>"><?php echo esc_html($order_status); ?></span></td>
                                            <td class="fw-bold"><?php echo esc_html($currency . number_format((float)$total, 2)); ?></td>
                                            <td>
                                                <a href="<?php echo esc_url( home_url( '/afdp-thanks/?order_id=' . $order->ID ) ); ?>" class="btn btn-sm btn-outline-dark" style="border-radius: 8px; font-weight:700; font-size:11px;">VIEW DETAILS</a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-5">
                                <p class="text-muted">You haven't placed any orders yet.</p>
                                <a href="<?php echo esc_url(home_url('/')); ?>" class="afdp-btn-red-action">Browse Menu</a>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="tab-pane fade" id="afdp-content-profile" role="tabpanel">
                        <h3 class="fw-bold mb-4">Profile Details</h3>
                        <?php if($success_msg && isset($_POST['update_profile'])) echo '<div class="alert alert-success py-2" style="border-radius:12px;">'.esc_html($success_msg).'</div>'; ?>
                        <form method="post">
                            <?php wp_nonce_field('afdp_update_profile_action', 'afdp_profile_nonce'); ?>
                            <div class="row mb-3">
                                <div class="col-md-6"><label class="small fw-bold">First Name</label><input type="text" name="first_name" class="form-control afdp-form-control-custom" value="<?php echo esc_attr($current_user->first_name); ?>"></div>
                                <div class="col-md-6"><label class="small fw-bold">Last Name</label><input type="text" name="last_name" class="form-control afdp-form-control-custom" value="<?php echo esc_attr($current_user->last_name); ?>"></div>
                            </div>
                            <div class="mb-3"><label class="small fw-bold">Display Name</label><input type="text" name="full_name" class="form-control afdp-form-control-custom" value="<?php echo esc_attr($current_user->display_name); ?>"></div>
                            <div class="mb-3"><label class="small fw-bold">Phone</label><input type="text" name="phone" class="form-control afdp-form-control-custom" value="<?php echo esc_attr($user_phone); ?>"></div>
                            <div class="mb-4"><label class="small fw-bold">Delivery Address</label><textarea name="address" rows="3" class="form-control afdp-form-control-custom"><?php echo esc_textarea($user_address); ?></textarea></div>
                            <button type="submit" name="update_profile" class="afdp-btn-red-action">Save Changes</button>
                        </form>
                    </div>

                    <div class="tab-pane fade" id="afdp-content-password" role="tabpanel">
                        <h3 class="fw-bold mb-4">Security Settings</h3>
                        <?php if($error_msg) echo '<div class="alert alert-danger py-2" style="border-radius:12px;">'.esc_html($error_msg).'</div>'; ?>
                        <?php if($success_msg && isset($_POST['update_password'])) echo '<div class="alert alert-success py-2" style="border-radius:12px;">'.esc_html($success_msg).'</div>'; ?>
                        <form method="post">
                            <?php wp_nonce_field('afdp_update_password_action', 'afdp_password_nonce'); ?>
                            <div class="mb-3"><label class="small fw-bold">Current Password</label><input type="password" name="current_password" class="form-control afdp-form-control-custom" required></div>
                            <div class="mb-3"><label class="small fw-bold">New Password</label><input type="password" name="new_password" class="form-control afdp-form-control-custom" required></div>
                            <div class="mb-4"><label class="small fw-bold">Confirm New Password</label><input type="password" name="confirm_password" class="form-control afdp-form-control-custom" required></div>
                            <button type="submit" name="update_password" class="afdp-btn-red-action">Update Password</button>
                        </form>
                    </div>

                </div>
            </div>
        </div>
    </div>

    <?php
    return ob_get_clean();
}