<?php
namespace WTC_CHECKOUT\Modules\Dashboard\Frontend;
use WTC_CHECKOUT\Modules\Dashboard\Services\DashboardDataService;
use WTC_CHECKOUT\Core\Helpers\SvgIconHelper;
defined('ABSPATH') || exit;
class DashboardHandler {
    private static $instance = null;
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    public function __construct() {
        add_shortcode('wtc_dashboard', [$this, 'render_shortcode']);
        add_action('wp_ajax_wtc_filter_orders', [$this, 'ajax_filter_orders']);
    }
    public function render_shortcode($atts) {
        if (!is_user_logged_in()) {
            return do_shortcode('[woocommerce_my_account]');
        }
        ob_start();
        $this->render_layout();
        return ob_get_clean();
    }
    private function render_layout() {
        global $wp_query;
        $current_endpoint = WC()->query->get_current_endpoint();
        $points_endpoint = get_option('wtc_point_endpoint', 'puanlarim');
        $coupon_endpoint = get_option('wtc_coupon_endpoint', 'kuponlarim');
        if (empty($current_endpoint)) {
            if (isset($wp_query->query_vars[$points_endpoint])) {
                $current_endpoint = $points_endpoint;
            } elseif (isset($wp_query->query_vars[$coupon_endpoint])) {
                $current_endpoint = $coupon_endpoint;
            } else {
                $current_endpoint = 'dashboard';
            }
        }
        ?>
        <div class="wtc-dashboard-container">
            <?php $this->render_sidebar($current_endpoint); ?>
            <div class="wtc-dashboard-content">
                <?php 
                if ($current_endpoint === 'dashboard') {
                    $this->render_modern_dashboard_content();
                } 
                elseif ($current_endpoint === $points_endpoint) { 
                    if (class_exists('WTC_CHECKOUT\Modules\Points\Frontend\PointsMyAccountHandler')) {
                        echo '<div class="woocommerce-MyAccount-content">';
                        \WTC_CHECKOUT\Modules\Points\Frontend\PointsMyAccountHandler::get_instance()->render_points_content();
                        echo '</div>';
                    }
                }
                elseif ($current_endpoint === $coupon_endpoint) {
                    if (class_exists('WTC_CHECKOUT\Modules\Coupons\Frontend\CouponAccountHandler')) {
                        echo '<div class="woocommerce-MyAccount-content">';
                        \WTC_CHECKOUT\Modules\Coupons\Frontend\CouponAccountHandler::get_instance()->render_coupons_content();
                        echo '</div>';
                    }
                }
                else {
                    echo '<div class="woocommerce-MyAccount-content">';
                    do_action('woocommerce_account_content');
                    echo '</div>';
                }
                ?>
            </div>
        </div>
        <?php
    }
    private function render_sidebar($current_endpoint) {
        $menu_items = wc_get_account_menu_items();
        ?>
        <div class="wtc-sidebar">
            <div class="wtc-sidebar-header">
                <span class="wtc-sidebar-title"><?php esc_html_e('Menü', 'wtc-checkout'); ?></span>
            </div>
            <ul class="wtc-nav-list">
                <?php foreach ($menu_items as $endpoint => $label) : 
                    $link = wc_get_account_endpoint_url($endpoint);
                    if($endpoint === 'dashboard') $link = wc_get_page_permalink('myaccount');
                    $is_active = ($endpoint === $current_endpoint);
                    $icon_class = $this->get_icon_for_endpoint($endpoint);
                ?>
                <li class="wtc-nav-item <?php echo $is_active ? 'active' : ''; ?>">
                    <a href="<?php echo esc_url($link); ?>" class="wtc-nav-link">
                        <?php SvgIconHelper::render( $icon_class ); ?>
                        <?php echo esc_html($label); ?>
                    </a>
                </li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php
    }
    private function render_modern_dashboard_content() {
        $user_id = get_current_user_id();
        $service = DashboardDataService::get_instance();
        $stats = $service->get_stats($user_id); 
        $points_active = get_option('wtc_points_enabled', 'no') === 'yes';
        $coupons_active = get_option('wtc_coupons_enabled', 'no') === 'yes';
        $point_label = get_option('wtc_point_label', __('Puan', 'wtc-checkout'));
        $chart_enabled    = get_option('wtc_dashboard_chart_enabled', 'no') === 'yes';
        $show_coupon_card = get_option('wtc_dashboard_show_coupon_card', 'yes');
        $show_points_card = get_option('wtc_dashboard_show_points_card', 'yes');
        $show_spent_card  = get_option('wtc_dashboard_show_total_spent_card', 'yes');
        $show_orders_card = get_option('wtc_dashboard_show_order_count_card', 'yes');
        $user = wp_get_current_user();
        $first_name = $user->first_name;
        $last_name  = $user->last_name;
        $initials   = '';
        $display_name = '';
        if (!empty($first_name) || !empty($last_name)) {
            $display_name = trim($first_name . ' ' . $last_name);
            $f_init = !empty($first_name) ? mb_substr($first_name, 0, 1, 'UTF-8') : '';
            $l_init = !empty($last_name) ? mb_substr($last_name, 0, 1, 'UTF-8') : '';
            $initials = mb_strtoupper($f_init . $l_init, 'UTF-8');
        } else {
            $display_name = $user->user_login;
            $initials = mb_strtoupper(mb_substr($user->user_login, 0, 1, 'UTF-8'), 'UTF-8');
        }
        ?>
        <div class="wtc-dash-header">
        <?php if ($chart_enabled): ?>
            <div class="wtc-chart-container">
                <canvas id="wtcSpendingChart"></canvas>
            </div>
        <?php else: ?>
            <div class="wtc-header-spacer"></div>
        <?php endif; ?>
            <div class="wtc-user-info">
                <div class="wtc-user-text">
                    <span class="wtc-welcome"><?php esc_html_e('Tekrar Hoşgeldin,', 'wtc-checkout'); ?></span>
                    <h2 class="wtc-username"><?php echo esc_html($display_name); ?></h2>
                </div>
                <div class="wtc-avatar-circle">
                    <?php echo esc_html($initials); ?>
                </div>
            </div>
        </div>
        <div class="wtc-stat-grid">
            <?php if ($show_spent_card === 'yes'): ?>
            <div class="wtc-stat-card card-spend">
                <div class="wtc-icon-box"><?php SvgIconHelper::render( 'cart' ); ?></div>
                <div class="wtc-card-info">
                    <span class="wtc-label"><?php esc_html_e('Toplam Sipariş', 'wtc-checkout'); ?></span>
                    <span class="wtc-value"><?php echo esc_html(wp_strip_all_tags(wc_price($stats['total_spent']))); ?></span>
                </div>
            </div>
            <?php endif; ?>
            <?php if ($show_orders_card === 'yes'): ?>
            <div class="wtc-stat-card card-orders">
                <div class="wtc-icon-box"><?php SvgIconHelper::render( 'list' ); ?></div>
                <div class="wtc-card-info">
                    <span class="wtc-label"><?php esc_html_e('Siparişler', 'wtc-checkout'); ?></span>
                    <span class="wtc-value"><?php echo esc_html($stats['order_count']); ?></span>
                </div>
            </div>
            <?php endif; ?>
            <?php if ($points_active && $show_points_card === 'yes'): ?>
            <div class="wtc-stat-card card-points">
                <div class="wtc-icon-box"><?php SvgIconHelper::render( 'star' ); ?></div>
                <div class="wtc-card-info">
                    <span class="wtc-label"><?php echo esc_html($point_label); ?></span>
                    <span class="wtc-value"><?php echo number_format($stats['points'], 2); ?></span>
                </div>
            </div>
            <?php endif; ?>
            <?php if ($coupons_active && $show_coupon_card === 'yes'): ?>
            <div class="wtc-stat-card card-coupons">
                <div class="wtc-icon-box"><?php SvgIconHelper::render( 'ticket' ); ?></div>
                <div class="wtc-card-info">
                    <span class="wtc-label"><?php esc_html_e('Kuponlar', 'wtc-checkout'); ?></span>
                    <span class="wtc-value"><?php echo esc_html($stats['coupons']); ?></span>
                </div>
            </div>
            <?php endif; ?>
        </div>
        <div class="wtc-orders-section">
            <div class="wtc-orders-header">
                <h3><?php esc_html_e('Son Siparişler', 'wtc-checkout'); ?></h3>
                <div class="wtc-filters">
                    <div class="wtc-status-tabs">
                        <button class="wtc-tab active" data-status="all"><?php esc_html_e('Tümü', 'wtc-checkout'); ?></button>
                        <button class="wtc-tab" data-status="active"><?php esc_html_e('Devam Eden', 'wtc-checkout'); ?></button>
                        <button class="wtc-tab" data-status="completed"><?php esc_html_e('Tamamlanan', 'wtc-checkout'); ?></button>
                        <button class="wtc-tab" data-status="refunded"><?php esc_html_e('İade', 'wtc-checkout'); ?></button>
                    </div>
                    <select id="wtc-date-filter" class="wtc-select">
                        <option value="all"><?php esc_html_e('Tüm Zamanlar', 'wtc-checkout'); ?></option>
                        <option value="30_days"><?php esc_html_e('Son 30 Gün', 'wtc-checkout'); ?></option>
                        <option value="6_months"><?php esc_html_e('Son 6 Ay', 'wtc-checkout'); ?></option>
                        <option value="1_year"><?php esc_html_e('Son 1 Yıl', 'wtc-checkout'); ?></option>
                    </select>
                </div>
            </div>
            <div id="wtc-orders-container">
                <?php 
                $orders = $service->get_filtered_orders($user_id);
                $this->render_orders_list($orders, 1); 
                ?>
            </div>
        </div>
        <?php
    }
    public function render_orders_list($data, $current_page = 1) {
        $orders = $data->orders;
        $max_pages = $data->max_num_pages;
        if (empty($orders)) {
            echo '<div class="wtc-no-orders">' . SvgIconHelper::get( 'info' ) . ' ' . esc_html__('Kriterlere uygun sipariş bulunamadı.', 'wtc-checkout') . '</div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG is internal and safe.
            return;
        }
        echo '<div class="wtc-orders-list">';
        foreach ($orders as $order) {
            $item_count = $order->get_item_count();
            $items = $order->get_items();
            $first_item = reset($items);
            $product = $first_item ? $first_item->get_product() : null;
            $image_url = ($product && $product->get_image_id()) ? wp_get_attachment_image_url($product->get_image_id(), 'thumbnail') : wc_placeholder_img_src();
            $more_count = $item_count > 1 ? '+' . ($item_count - 1) : '';
            $status_class = 'status-' . $order->get_status();
            ?>
            <div class="wtc-order-row">
                <div class="wtc-order-thumb">
                    <img src="<?php echo esc_url($image_url); ?>" alt="Product">
                    <?php if($more_count): ?>
                        <span class="wtc-more-badge"><?php echo esc_html($more_count); ?></span>
                    <?php endif; ?>
                </div>
                <div class="wtc-order-details">
                    <span class="wtc-order-id">
                        <a href="<?php echo esc_url($order->get_view_order_url()); ?>">#<?php echo esc_html($order->get_order_number()); ?></a>
                    </span>
                    <span class="wtc-order-date"><?php echo esc_html(wc_format_datetime($order->get_date_created())); ?></span>
                </div>
                <div class="wtc-order-status">
                    <span class="wtc-status-badge <?php echo esc_attr($status_class); ?>">
                        <?php echo esc_html(wc_get_order_status_name($order->get_status())); ?>
                    </span>
                </div>
                <div class="wtc-order-total">
                    <?php echo wp_kses_post($order->get_formatted_order_total()); ?>
                </div>
                <div class="wtc-order-actions">
                    <a href="<?php echo esc_url($order->get_view_order_url()); ?>" class="wtc-btn-view">
                        <?php SvgIconHelper::render( 'chevron-right' ); ?>
                    </a>
                </div>
            </div>
            <?php
        }
        echo '</div>';
        if ($max_pages > 1) {
            echo '<div class="wtc-pagination">';
            for ($i = 1; $i <= $max_pages; $i++) {
                $class = ($i === $current_page) ? 'current' : '';
                echo '<button class="wtc-page-link ' . esc_attr($class) . '" data-page="' . esc_attr($i) . '">' . esc_html($i) . '</button>';
            }
            echo '</div>';
        }
    }
    private function get_icon_for_endpoint($endpoint) {
        $points_endpoint = get_option('wtc_point_endpoint', 'puanlarim');
        $coupon_endpoint = get_option('wtc_coupon_endpoint', 'kuponlarim');
        $icons = [
            'dashboard'       => 'dashboard',
            'orders'          => 'list',
            'downloads'       => 'download',
            'edit-address'    => 'location',
            'edit-account'    => 'user',
            'customer-logout' => 'logout',
            'wishlist'        => 'heart',
            $points_endpoint  => 'star',
            $coupon_endpoint  => 'ticket',
        ];
        return isset($icons[$endpoint]) ? $icons[$endpoint] : 'cog';
    }
    public function ajax_filter_orders() {
        check_ajax_referer('wtc_dashboard_nonce', 'nonce');
        $user_id = get_current_user_id();
        $status = isset($_POST['status']) ? sanitize_text_field(wp_unslash($_POST['status'])) : 'all';
        $date_range = isset($_POST['date_range']) ? sanitize_text_field(wp_unslash($_POST['date_range'])) : 'all';
        $paged = isset($_POST['paged']) ? intval(wp_unslash($_POST['paged'])) : 1;
        $service = DashboardDataService::get_instance();
        $data = $service->get_filtered_orders($user_id, $status, $date_range, $paged);
        ob_start();
        $this->render_orders_list($data, $paged);
        $html = ob_get_clean();
        wp_send_json_success(['html' => $html]);
    }
}