<?php
// Get current user information
$current_user = wp_get_current_user();

// Get user's first and last name
$first_name = $current_user->first_name;
$last_name = $current_user->last_name;

// If first name is empty, use display name instead
if (empty($first_name)) {
    $first_name = $current_user->display_name;
    $last_name = '';
}

// Get user's avatar URL
$avatar_url = kavehboard_get_user_avatar_url($current_user->ID);

// Get user's order statistics if WooCommerce is active
$order_stats = array(
    'processing' => 0,
    'completed' => 0,
    'refunded' => 0,
    'cancelled' => 0,
    'total' => 0
);

if (function_exists('wc_get_orders') && is_user_logged_in()) {
    $user_id = get_current_user_id();

    // Get processing orders
    $processing_orders = wc_get_orders(array(
        'customer' => $user_id,
        'status' => array('wc-processing', 'wc-pending', 'wc-on-hold'),
        'limit' => -1
    ));
    $order_stats['processing'] = count($processing_orders);

    // Get completed orders
    $completed_orders = wc_get_orders(array(
        'customer' => $user_id,
        'status' => 'wc-completed',
        'limit' => -1
    ));
    $order_stats['completed'] = count($completed_orders);

    // Get refunded orders
    $refunded_orders = wc_get_orders(array(
        'customer' => $user_id,
        'status' => 'wc-refunded',
        'limit' => -1
    ));
    $order_stats['refunded'] = count($refunded_orders);

    // Get cancelled orders
    $cancelled_orders = wc_get_orders(array(
        'customer' => $user_id,
        'status' => array('wc-cancelled', 'wc-failed'),
        'limit' => -1
    ));
    $order_stats['cancelled'] = count($cancelled_orders);

    // Calculate total orders
    $order_stats['total'] = $order_stats['processing'] + $order_stats['completed'] + $order_stats['refunded'] + $order_stats['cancelled'];
}

// Get dashboard header text from admin options
$kavehboard_options = get_option('kavehboard_options');
$header_text = $kavehboard_options['kavehboard_header_text'][0] ?? array();
$page_name = $header_text['page_name'] ?? 'داشبورد';
$description_text = $header_text['description'] ?? 'این یک پیام است که میتواند هرچه را دوست داشته باشد بنویسد 👋';
?>
            
            <div class="row row-dashboard">

                <!-- Start Orders -->
                <div class="col-lg-6 order-1 order-lg-2">
                    <div class="dashboard-kaveh-orders">
                        <!-- Start Heading -->
                        <div class="dashboard-kaveh-orders-heading d-flex align-items-center">
                            <div class="dashboard-kaveh-orders-heading-title d-flex align-items-center gap-2">
                                <i class="icon-fast-car lh-1"></i>
                                <span class="text fw-normal"><?php _e('My Orders', 'kavehTheme'); ?></span>
                                <span class="badge badge-warning rounded-pill"> <?= $order_stats['total']; ?> </span>
                            </div>
                            <a href="<?php echo esc_url(get_permalink() . 'orders/'); ?>" class="dashboard-kaveh-link d-flex align-items-center justify-content-center fw-bold ms-auto">
                                <?php _e('View More', 'kavehTheme'); ?>
                                <i class="icon-arrow-left-9 lh-1 fw-normal"></i>
                            </a>
                        </div>
                        <!-- End Heading -->
                        <!-- Start Info Orders -->
                        <div class="dashboard-kaveh-orders-info-orders">
                            <div class="row">
                                <!-- Start Info Orders Item -->
                                <div class="col-6">
                                    <div class="dashboard-kaveh-orders-info-orders-item bg-white position-relative d-flex align-items-center">
                                        <div class="image d-flex align-items-center justify-content-center position-relative">
                                            <img src="<?= KAVEHBOARD_URL ?>/assets/images/dashboard/stat-01.png" alt="stat" width="32" height="32" class="d-block">
                                        </div>
                                        <div>
                                            <div class="value fw-bold"> <?= $order_stats['processing']; ?> <?php _e('items', 'kavehTheme'); ?></div>
                                            <div class="sub-value fw-normal"><?php _e('Current Orders', 'kavehTheme'); ?></div>
                                        </div>
                                        <a href="<?php echo esc_url(get_permalink() . 'orders/'); ?>" class="more position-absolute">
                                            <i class="icon-arrow-left-9 lh-1"></i>
                                        </a>
                                    </div>
                                </div>
                                <!-- End Info Orders Item -->
                                <!-- Start Info Orders Item -->
                                <div class="col-6">
                                    <div class="dashboard-kaveh-orders-info-orders-item bg-white position-relative d-flex align-items-center">
                                        <div class="image d-flex align-items-center justify-content-center position-relative">
                                            <img src="<?= KAVEHBOARD_URL ?>/assets/images/dashboard/stat-02.png" alt="stat" width="32" height="32" class="d-block">
                                        </div>
                                        <div>
                                            <div class="value fw-bold"> <?= $order_stats['completed']; ?> <?php _e('items', 'kavehTheme'); ?></div>
                                            <div class="sub-value fw-normal"><?php _e('Delivered', 'kavehTheme'); ?></div>
                                        </div>
                                        <a href="<?php echo esc_url(get_permalink() . 'orders/'); ?>" class="more position-absolute">
                                            <i class="icon-arrow-left-9 lh-1"></i>
                                        </a>
                                    </div>
                                </div>
                                <!-- End Info Orders Item -->
                                <!-- Start Info Orders Item -->
                                <div class="col-6">
                                    <div class="dashboard-kaveh-orders-info-orders-item bg-white position-relative d-flex align-items-center">
                                        <div class="image d-flex align-items-center justify-content-center position-relative">
                                            <img src="<?= KAVEHBOARD_URL ?>/assets/images/dashboard/stat-03.png" alt="stat" width="32" height="32" class="d-block">
                                        </div>
                                        <div>
                                            <div class="value fw-bold"> <?= $order_stats['refunded']; ?> <?php _e('items', 'kavehTheme'); ?></div>
                                            <div class="sub-value fw-normal"><?php _e('Returned', 'kavehTheme'); ?></div>
                                        </div>
                                        <a href="<?php echo esc_url(get_permalink() . 'orders/'); ?>" class="more position-absolute">
                                            <i class="icon-arrow-left-9 lh-1"></i>
                                        </a>
                                    </div>
                                </div>
                                <!-- End Info Orders Item -->
                                <!-- Start Info Orders Item -->
                                <div class="col-6">
                                    <div class="dashboard-kaveh-orders-info-orders-item bg-white position-relative d-flex align-items-center">
                                        <div class="image d-flex align-items-center justify-content-center position-relative">
                                            <img src="<?= KAVEHBOARD_URL ?>/assets/images/dashboard/stat-04.png" alt="stat" width="32" height="32" class="d-block">
                                        </div>
                                        <div>
                                            <div class="value fw-bold"> <?= $order_stats['cancelled']; ?> <?php _e('items', 'kavehTheme'); ?></div>
                                            <div class="sub-value fw-normal"><?php _e('Cancelled', 'kavehTheme'); ?></div>
                                        </div>
                                        <a href="<?php echo esc_url(get_permalink() . 'orders/'); ?>" class="more position-absolute">
                                            <i class="icon-arrow-left-9 lh-1"></i>
                                        </a>
                                    </div>
                                </div>
                                <!-- End Info Orders Item -->
                            </div>
                        </div>
                        <!-- End Info Orders -->
                    </div>
                </div>
                <!-- End Orders -->
                <!-- Start Carousel -->
                <div class="col-lg-6 order-5 order-lg-3">
                    <div class="dashboard-kaveh-carousel">
                        <div class="swiper swiper-carousel-dashboard overflow-visible position-relative">
                            <div class="swiper-wrapper">
                                <?php
                                // Get carousel slides from admin options
                                $carousel_slides = get_option('kavehboard_options')['kavehboard_dashboard_carousel'] ?? array();
                                
                                // If no slides configured, use default
                                if (empty($carousel_slides)) {
                                    $carousel_slides = array(
                                        array(
                                            'image' => array('url' => KAVEHBOARD_URL . '/assets/images/dashboard/carousel.png'),
                                            'title' => 'Default Slide 1',
                                            'link' => '#',
                                            'link_target' => '_self'
                                        ),
                                        array(
                                            'image' => array('url' => KAVEHBOARD_URL . '/assets/images/dashboard/carousel.png'),
                                            'title' => 'Default Slide 2',
                                            'link' => '#',
                                            'link_target' => '_self'
                                        )
                                    );
                                }
                                
                                foreach ($carousel_slides as $slide):
                                    $image_url = $slide['image']['url'] ?? KAVEHBOARD_URL . '/assets/images/dashboard/carousel.png';
                                    $title = $slide['title'] ?? 'carousel';
                                    $link = $slide['link'] ?? '#';
                                    $link_target = $slide['link_target'] ?? '_self';
                                ?>
                                <!-- Start Slide -->
                                <div class="swiper-slide">
                                    <a href="<?php echo esc_url($link); ?>" class="slide d-block w-100" target="<?php echo esc_attr($link_target); ?>">
                                        <img src="<?php echo esc_url($image_url); ?>" alt="<?php echo esc_attr($title); ?>" width="493" height="302" class="d-block w-100">
                                    </a>
                                </div>
                                <!-- End Slide -->
                                <?php endforeach; ?>
                            </div>
                            <!-- Start Pagination -->
                            <div class="swiper-pagination d-none d-lg-flex align-items-center flex-column top-50 end-0 m-0 w-auto h-auto start-100"></div>
                            <!-- End Pagination -->
                        </div>
                    </div>
                </div>
                <!-- End Carousel -->
                <div class="col-lg-6 order-3 order-lg-4">
                    <?php
                    // Get discount code settings from admin options
                    $kavehboard_options = get_option('kavehboard_options');
                    if (is_array($kavehboard_options) && 
                        isset($kavehboard_options['kavehboard_discount_code']) && 
                        is_array($kavehboard_options['kavehboard_discount_code']) && 
                        isset($kavehboard_options['kavehboard_discount_code'][0])):
                        
                        $discount_options = $kavehboard_options['kavehboard_discount_code'][0];
                        if (is_array($discount_options) && 
                            isset($discount_options['enable']) && 
                            $discount_options['enable'] === '1' &&
                            isset($discount_options['image']['url'], $discount_options['code'], $discount_options['description'])):
                            
                            $discount_image = $discount_options['image']['url'];
                            $discount_code = $discount_options['code'];
                            $discount_description = $discount_options['description'];
                    ?>
                    <!-- Start Discount Code -->
                    <div class="dashboard-kaveh-discount-code d-flex align-items-center overflow-hidden mb-3">
                        <div class="image position-relative flex-fill flex-grow-0 flex-shrink-0 d-flex align-items-center justify-content-center">
                            <img src="<?php echo esc_url($discount_image); ?>" alt="gift" width="124" height="124">
                        </div>
                        <div class="detail w-100 flex-fill flex-grow-0 flex-shrink-0 position-relative">
                            <div class="code"> <?php echo esc_html($discount_code); ?> </div>
                            <div class="description"> <?php echo esc_html($discount_description); ?> </div>
                        </div>
                    </div>
                    <!-- End Discount Code -->
                    <?php endif; endif; ?>
                    <!-- Start Info User -->
                    <div class="dashboard-kaveh-info-user">
                        <!-- Start Heading -->
                        <div class="dashboard-kaveh-info-user-heading d-flex align-items-center justify-content-between mb-4">
                            <div class="dashboard-kaveh-info-user-heading-text d-flex align-items-center gap-2">
                                <i class="icon-user-octagon lh-1"></i>
                                <span class="fw-normal"><?php _e('Personal Information', 'kavehTheme'); ?></span>
                            </div>
                            <a href="<?php echo esc_url(get_permalink() . 'woo-edit-account/'); ?>" class="dashboard-kaveh-link d-flex align-items-center fw-bold">
                                <?php _e('Edit Information', 'kavehTheme'); ?>
                                <i class="icon-arrow-left-9 lh-1"></i>
                            </a>
                        </div>
                        <!-- End Heading -->
                        <!-- Start Info -->
                        <ul class="dashboard-kaveh-info-user-info d-flex flex-column">
                            <?php
                            // Get current user information
                            if (is_user_logged_in()) {
                                $current_user = wp_get_current_user();
                                $user_id = get_current_user_id();
                                
                                // Get user's full name
                                $first_name = get_user_meta($user_id, 'first_name', true);
                                $last_name = get_user_meta($user_id, 'last_name', true);
                                $full_name = trim($first_name . ' ' . $last_name);
                                if (empty($full_name)) {
                                    $full_name = $current_user->display_name;
                                }
                                
                                // Get user's email
                                $user_email = $current_user->user_email;
                                
                                // Get user's phone number from WooCommerce billing data
                                $user_phone = '';
                                if (function_exists('get_user_meta')) {
                                    $user_phone = get_user_meta($user_id, 'billing_phone', true);
                                }
                            } else {
                                $full_name = __('Guest', 'kavehTheme');
                                $user_email = '';
                                $user_phone = '';
                            }
                            ?>
                            <li class="d-flex align-items-center">
                                <i class="icon-user-octagon lh-1"></i>
                                <span class="label fw-bold"><?php _e('Name:', 'kavehTheme'); ?></span>
                                <span class="value fw-normal"> <?php echo esc_html($full_name); ?> </span>
                            </li>
                            <?php if (!empty($user_phone)): ?>
                            <li class="d-flex align-items-center">
                                <i class="icon-phone-6 lh-1"></i>
                                <span class="label fw-bold"><?php _e('Phone:', 'kavehTheme'); ?></span>
                                <span class="value fw-normal"> <?php echo esc_html($user_phone); ?> </span>
                            </li>
                            <?php endif; ?>
                            <?php if (!empty($user_email)): ?>
                            <li class="d-flex align-items-center">
                                <i class="icon-sms lh-1"></i>
                                <span class="label fw-bold"><?php _e('Email:', 'kavehTheme'); ?></span>
                                <span class="value fw-normal"> <?php echo esc_html($user_email); ?> </span>
                            </li>
                            <?php endif; ?>
                        </ul>
                        <!-- End Info -->
                    </div>
                    <!-- End Info User -->
                    
            
                </div>
                <!-- Start Latest products purchased -->
                <div class="col-lg-6 order-4 order-lg-5">
                    <div class="dashboard-kaveh-latest-products-purchased">
                        <!-- Start Heading -->
                        <div class="dashboard-kaveh-latest-products-purchased-heading d-flex align-items-center justify-content-between gap-2 bg-white">
                            <div class="dashboard-kaveh-latest-products-purchased-heading-title">
                                <i class="icon-fast-car lh-1"></i>
                                <span class="text fw-normal"><?php _e('Latest Purchased Products', 'kavehTheme'); ?></span>
                                <span class="badge badge-warning rounded-pill"> <?= $order_stats['total']; ?> </span>
                            </div>
                            <a href="<?php echo esc_url(get_permalink() . 'orders/'); ?>" class="dashboard-kaveh-link d-flex align-items-center fw-bold flex-fill flex-grow-0 flex-shrink-0">
                                <?php _e('View More', 'kavehTheme'); ?>
                                <i class="icon-arrow-left-9 lh-1"></i>
                            </a>
                        </div>
                        <!-- End Heading -->
                        <!-- Start Products -->
                        <ul class="dashboard-kaveh-latest-products-purchased-products d-flex flex-column scrollbar position-relative">
                        <?php
                        // Get recent orders for current user
                        if (function_exists('wc_get_orders') && is_user_logged_in()) {
                            $user_id = get_current_user_id();
                            
                            // Get all user orders
                            $customer_orders = wc_get_orders(array(
                                'customer' => $user_id,
                                'limit' => 6, // Show only 6 most recent orders
                                'orderby' => 'date',
                                'order' => 'DESC',
                            ));
                            
                            if (!empty($customer_orders)) {
                                foreach ($customer_orders as $order) {
                                    // Get order details
                                    $order_id = $order->get_id();
                                    $order_date = $order->get_date_created();
                                    $order_date_formatted = $order_date ? $order_date->date_i18n('Y/m/d') : '';
                                    $order_total = $order->get_total();
                                    $order_status = $order->get_status();
                                    
                                    // Get order items
                                    $items = $order->get_items();
                                    
                                    // Display each item in the order
                                    foreach ($items as $item) {
                                        $product_id = $item->get_product_id();
                                        $product = wc_get_product($product_id);
                                        
                                        if ($product) {
                                            $product_name = $item->get_name();
                                            $product_quantity = $item->get_quantity();
                                            $product_total = $item->get_total();
                                            $product_image = wp_get_attachment_image_src(get_post_thumbnail_id($product_id), 'thumbnail');
                                            $product_image_url = $product_image ? $product_image[0] : KAVEHBOARD_URL . '/assets/images/dashboard/product.png';
                                            $product_permalink = get_permalink($product_id);
                                            
                                            // Format price in Persian style
                                            $formatted_price = number_format($product_total, 0, '.', ',');
                                            ?>
                                            <!-- Start Product -->
                                            <li class="bg-white">
                                                <div class="info d-flex align-items-center">
                                                    <a href="<?php echo esc_url($product_permalink); ?>" class="image flex-fill flex-grow-0 flex-shrink-0">
                                                        <img src="<?php echo esc_url($product_image_url); ?>" alt="<?php echo esc_attr($product_name); ?>" width="60" height="60">
                                                    </a>
                                                    <a href="<?php echo esc_url($product_permalink); ?>" class="title me-3"><?php echo esc_html($product_name); ?></a>
                                                    <a href="<?php echo esc_url(get_permalink() . 'order-details/' . $order_id . '/'); ?>" class="icon position-relative rounded-circle ms-auto me-3 d-flex align-items-center justify-content-center flex-fill flex-grow-0 flex-shrink-0">
                                                        <i class="icon-box-time lh-1 d-flex align-items-center justify-content-center"></i>
                                                    </a>
                                                    <a href="<?php echo esc_url($product_permalink); ?>" class="go d-flex align-items-center justify-content-center">
                                                        <i class="icon-arrow-left-9 lh-1"></i>
                                                    </a>
                                                </div>
                                                <div class="bottom d-flex align-items-center f-iransans flex-wrap">
                                                    <div class="count"><?php _e('Quantity:', 'kavehTheme'); ?> <?php echo esc_html($product_quantity); ?></div>
                                                    <div class="date"><?php _e('Date:', 'kavehTheme'); ?> <?php echo esc_html($order_date_formatted); ?></div>
                                                    <div class="code"> #<?php echo esc_html($order_id); ?> </div>
                                                    <div class="price fw-normal">
                                                        <span class="fw-bold"> <?php echo esc_html($formatted_price); ?> </span>
                                                        <?php _e('Toman', 'kavehTheme'); ?>
                                                    </div>
                                                </div>
                                            </li>
                                            <!-- End Product -->
                                            <?php
                                        }
                                    }
                                }
                            } else {
                                // No orders found
                                echo '<li class="bg-white text-center py-4">' . __('No products have been purchased.', 'kavehTheme') . '</li>';
                            }
                        } else {
                            // WooCommerce not active or user not logged in
                            echo '<li class="bg-white text-center py-4">' . __('Please log in to view purchased products.', 'kavehTheme') . '</li>';
                        }
                        ?>
                        </ul>
                        <!-- End Products -->
                    </div>
                </div>
                <!-- End Latest products purchased -->
            </div>