<?php
/**
 * قالب حساب کاربری Dima Shop
 * نسخه: 1.1.0 - با Header و Footer
 */
if (!defined('ABSPATH')) exit;

if (!is_user_logged_in()) {
    wp_redirect(wp_login_url(get_permalink()));
    exit;
}

get_header();

$current_user = wp_get_current_user();
$user_id = $current_user->ID;
$active_tab = get_query_var('dima_account', 'dashboard');

global $wpdb;
$orders_count = $wpdb->get_var($wpdb->prepare(
    "SELECT COUNT(*) FROM {$wpdb->prefix}dima_orders WHERE user_id = %d",
    $user_id
));

$reward = class_exists('Dima_Reward') ? Dima_Reward::get_instance() : null;
$user_points = $reward ? $reward->get_user_points($user_id) : 0;

$wishlist = class_exists('Dima_Wishlist') ? Dima_Wishlist::get_instance() : null;
$wishlist_count = $wishlist ? $wishlist->get_count() : 0;
?>

<div class="dima-account-wrapper">
    
    <div class="account-header">
        <div class="user-welcome">
            <div class="user-avatar-large">
                <?php echo get_avatar($user_id, 80); ?>
            </div>
            <div class="user-info">
                <h1>سلام، <?php echo esc_html($current_user->display_name); ?> 👋</h1>
                <p class="user-email"><?php echo esc_html($current_user->user_email); ?></p>
            </div>
        </div>
    </div>
    
    <div class="account-layout">
        
        <aside class="account-sidebar">
            <nav class="account-nav">
                <a href="<?php echo esc_url(get_permalink(get_option('dima_account_page'))); ?>" 
                   class="nav-item <?php echo $active_tab === 'dashboard' ? 'active' : ''; ?>">
                    <span class="nav-icon">📊</span>
                    <span class="nav-text">داشبورد</span>
                </a>
                
                <a href="?dima_account=orders" 
                   class="nav-item <?php echo $active_tab === 'orders' ? 'active' : ''; ?>">
                    <span class="nav-icon">📦</span>
                    <span class="nav-text">سفارشات من</span>
                    <span class="nav-badge"><?php echo intval($orders_count); ?></span>
                </a>
                
                <a href="<?php echo esc_url(get_permalink(get_option('dima_wishlist_page'))); ?>" class="nav-item">
                    <span class="nav-icon">❤️</span>
                    <span class="nav-text">علاقه‌مندی‌ها</span>
                    <span class="nav-badge"><?php echo intval($wishlist_count); ?></span>
                </a>
                
                <a href="?dima_account=rewards" 
                   class="nav-item <?php echo $active_tab === 'rewards' ? 'active' : ''; ?>">
                    <span class="nav-icon">🎁</span>
                    <span class="nav-text">امتیازات من</span>
                    <span class="nav-badge"><?php echo intval($user_points); ?></span>
                </a>
                
                <a href="?dima_account=edit-address" 
                   class="nav-item <?php echo $active_tab === 'edit-address' ? 'active' : ''; ?>">
                    <span class="nav-icon">📍</span>
                    <span class="nav-text">ویرایش آدرس</span>
                </a>
                
                <a href="<?php echo wp_logout_url(home_url()); ?>" class="nav-item logout">
                    <span class="nav-icon">🚪</span>
                    <span class="nav-text">خروج</span>
                </a>
            </nav>
        </aside>
        
        <main class="account-content">
            
            <?php if ($active_tab === 'dashboard'): ?>
            <div class="account-section">
                <h2>📊 داشبورد</h2>
                
                <div class="dashboard-stats">
                    <div class="stat-card">
                        <div class="stat-icon">🛍️</div>
                        <div class="stat-info">
                            <div class="stat-value"><?php echo intval($orders_count); ?></div>
                            <div class="stat-label">سفارش</div>
                        </div>
                    </div>
                    
                    <div class="stat-card">
                        <div class="stat-icon">❤️</div>
                        <div class="stat-info">
                            <div class="stat-value"><?php echo intval($wishlist_count); ?></div>
                            <div class="stat-label">علاقه‌مندی</div>
                        </div>
                    </div>
                    
                    <div class="stat-card">
                        <div class="stat-icon">⭐</div>
                        <div class="stat-info">
                            <div class="stat-value"><?php echo intval($user_points); ?></div>
                            <div class="stat-label">امتیاز</div>
                        </div>
                    </div>
                </div>
                
                <h3>🕐 سفارشات اخیر</h3>
                <?php
                $recent_orders = $wpdb->get_results($wpdb->prepare(
                    "SELECT * FROM {$wpdb->prefix}dima_orders WHERE user_id = %d ORDER BY created_at DESC LIMIT 5",
                    $user_id
                ));
                
                if (empty($recent_orders)):
                ?>
                    <div class="empty-box">
                        <div class="empty-icon">📭</div>
                        <p>هنوز سفارشی ثبت نکرده‌اید</p>
                        <a href="<?php echo esc_url(get_permalink(get_option('dima_shop_page'))); ?>" class="btn btn-primary">
                            🛍️ شروع خرید
                        </a>
                    </div>
                <?php else: ?>
                    <div class="orders-list">
                        <?php 
                        $status_labels = array(
                            'pending' => 'در انتظار',
                            'processing' => 'در حال پردازش',
                            'completed' => 'تکمیل شده',
                            'failed' => 'ناموفق',
                            'cancelled' => 'لغو شده'
                        );
                        $status_colors = array(
                            'pending' => '#f59e0b',
                            'processing' => '#3b82f6',
                            'completed' => '#10b981',
                            'failed' => '#ef4444',
                            'cancelled' => '#6b7280'
                        );
                        
                        foreach ($recent_orders as $order): 
                        ?>
                        <div class="order-item">
                            <div class="order-info">
                                <span class="order-id">سفارش #<?php echo intval($order->id); ?></span>
                                <span class="order-date"><?php echo date_i18n('j F Y', strtotime($order->created_at)); ?></span>
                            </div>
                            <div class="order-status" style="background: <?php echo $status_colors[$order->status] ?? '#6b7280'; ?>">
                                <?php echo $status_labels[$order->status] ?? $order->status; ?>
                            </div>
                            <div class="order-total">
                                <?php echo number_format($order->final_amount); ?> تومان
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <a href="?dima_account=orders" class="btn btn-outline">
                        مشاهده همه سفارشات ←
                    </a>
                <?php endif; ?>
            </div>
            
            <?php elseif ($active_tab === 'orders'): ?>
            <div class="account-section">
                <h2>📦 سفارشات من</h2>
                
                <?php
                $all_orders = $wpdb->get_results($wpdb->prepare(
                    "SELECT * FROM {$wpdb->prefix}dima_orders WHERE user_id = %d ORDER BY created_at DESC",
                    $user_id
                ));
                
                if (empty($all_orders)):
                ?>
                    <div class="empty-box">
                        <div class="empty-icon">📭</div>
                        <p>هنوز سفارشی ثبت نکرده‌اید</p>
                    </div>
                <?php else: ?>
                    <div class="orders-list full">
                        <?php foreach ($all_orders as $order): ?>
                        <div class="order-item full">
                            <div class="order-info">
                                <span class="order-id">سفارش #<?php echo intval($order->id); ?></span>
                                <span class="order-date"><?php echo date_i18n('j F Y - H:i', strtotime($order->created_at)); ?></span>
                            </div>
                            <div class="order-status" style="background: <?php echo $status_colors[$order->status] ?? '#6b7280'; ?>">
                                <?php echo $status_labels[$order->status] ?? $order->status; ?>
                            </div>
                            <div class="order-total">
                                <?php echo number_format($order->final_amount); ?> تومان
                            </div>
                            <a href="?dima_account=order-view&order_id=<?php echo $order->id; ?>" class="btn btn-small">
                                مشاهده جزئیات
                            </a>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
            
            <?php elseif ($active_tab === 'rewards'): ?>
            <div class="account-section">
                <h2>🎁 امتیازات من</h2>
                
                <div class="rewards-summary">
                    <div class="rewards-points">
                        <div class="points-value"><?php echo number_format($user_points); ?></div>
                        <div class="points-label">امتیاز فعلی</div>
                    </div>
                    <div class="rewards-value">
                        <div class="value-amount"><?php echo number_format(intval($user_points / 1000) * 1000); ?></div>
                        <div class="value-label">تومان ارزش</div>
                    </div>
                </div>
                
                <?php if ($user_points >= 1000): ?>
                <div class="redeem-section">
                    <h3>تبدیل امتیاز به کوپن تخفیف</h3>
                    <p>هر ۱۰۰ امتیاز = ۱۰۰۰ تومان تخفیف</p>
                    <button class="btn btn-primary" id="redeem-points-btn" data-points="1000">
                        🎟️ تبدیل ۱۰۰۰ امتیاز به کوپن
                    </button>
                </div>
                <?php else: ?>
                <div class="empty-box">
                    <p>برای دریافت کوپن تخفیف، حداقل ۱۰۰۰ امتیاز نیاز است.</p>
                </div>
                <?php endif; ?>
            </div>
            
            <?php elseif ($active_tab === 'edit-address'): ?>
            <div class="account-section">
                <h2>📍 ویرایش آدرس</h2>
                
                <?php
                if (isset($_POST['update_address']) && check_admin_referer('dima_update_address')) {
                    update_user_meta($user_id, 'dima_phone', sanitize_text_field($_POST['phone'] ?? ''));
                    update_user_meta($user_id, 'dima_province', sanitize_text_field($_POST['province'] ?? ''));
                    update_user_meta($user_id, 'dima_city', sanitize_text_field($_POST['city'] ?? ''));
                    update_user_meta($user_id, 'dima_address', sanitize_textarea_field($_POST['address'] ?? ''));
                    update_user_meta($user_id, 'dima_postal_code', sanitize_text_field($_POST['postal_code'] ?? ''));
                    
                    echo '<div class="alert alert-success">✅ اطلاعات با موفقیت بروزرسانی شد.</div>';
                }
                ?>
                
                <form method="post">
                    <?php wp_nonce_field('dima_update_address'); ?>
                    
                    <div class="form-group">
                        <label>شماره موبایل:</label>
                        <input type="tel" name="phone" value="<?php echo esc_attr(get_user_meta($user_id, 'dima_phone', true)); ?>">
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>استان:</label>
                            <select name="province">
                                <option value="">— انتخاب استان —</option>
                                <?php
                                $provinces = array('تهران', 'اصفهان', 'فارس', 'خراسان رضوی', 'آذربایجان شرقی', 'مازندران', 'گیلان', 'البرز');
                                $current = get_user_meta($user_id, 'dima_province', true);
                                foreach ($provinces as $prov):
                                ?>
                                    <option value="<?php echo esc_attr($prov); ?>" <?php selected($current, $prov); ?>><?php echo esc_html($prov); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>شهر:</label>
                            <input type="text" name="city" value="<?php echo esc_attr(get_user_meta($user_id, 'dima_city', true)); ?>">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>آدرس کامل:</label>
                        <textarea name="address" rows="3"><?php echo esc_textarea(get_user_meta($user_id, 'dima_address', true)); ?></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label>کد پستی:</label>
                        <input type="text" name="postal_code" value="<?php echo esc_attr(get_user_meta($user_id, 'dima_postal_code', true)); ?>">
                    </div>
                    
                    <button type="submit" name="update_address" class="btn btn-primary">💾 ذخیره تغییرات</button>
                </form>
            </div>
            <?php endif; ?>
            
        </main>
    </div>
</div>

<?php get_footer(); ?>