<?php
// ========================================
// پروفایل کاربر — موبایل فرست
// ========================================
require_once 'config/database.php';
require_once 'config/settings.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';

Auth::requireLogin();
Auth::checkSessionTimeout();

$pageTitle = 'پروفایل | کیف‌لند';
$db   = Database::getInstance()->getConnection();
$user = Auth::currentUser();
$success = ''; $error = '';

// آپدیت پروفایل
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    if (!Auth::verifyCSRFToken($_POST['csrf_token'] ?? '')) { $error = 'خطای امنیتی.'; }
    else {
        $fullName = sanitize($_POST['full_name']);
        $phone    = sanitize($_POST['phone']);
        $email    = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
        if (Auth::updateUserProfile($_SESSION['user_id'], ['full_name'=>$fullName,'phone'=>$phone,'email'=>$email])) {
            $success = 'اطلاعات با موفقیت به‌روز شد';
            $_SESSION['full_name'] = $fullName;
            $user = Auth::currentUser();
        } else { $error = 'خطا در به‌روزرسانی اطلاعات'; }
    }
}

// تغییر رمز عبور
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    if (!Auth::verifyCSRFToken($_POST['csrf_token'] ?? '')) { $error = 'خطای امنیتی.'; }
    else {
        $cur = $_POST['current_password'];
        $new = $_POST['new_password'];
        $con = $_POST['confirm_password'];
        $stmt = $db->prepare("SELECT password FROM users WHERE id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $ud = $stmt->fetch();
        if (!password_verify($cur, $ud['password'])) { $error = 'رمز عبور فعلی اشتباه است'; }
        elseif ($new !== $con)     { $error = 'رمز عبور جدید با تکرارش مطابقت ندارد'; }
        elseif (strlen($new) < 8) { $error = 'رمز عبور باید حداقل ۸ کاراکتر باشد'; }
        else {
            if (Auth::updateUserPassword($_SESSION['user_id'], $new)) $success = 'رمز عبور تغییر کرد';
            else $error = 'خطا در تغییر رمز عبور';
        }
    }
}

// سفارشات
$stmt = $db->prepare("SELECT o.*, COUNT(oi.id) as item_count, GROUP_CONCAT(oi.product_name SEPARATOR '||') as product_names FROM orders o LEFT JOIN order_items oi ON o.id = oi.order_id WHERE o.user_id = ? GROUP BY o.id ORDER BY o.created_at DESC");
$stmt->execute([$_SESSION['user_id']]);
$orders = $stmt->fetchAll();

$total_orders     = count($orders);
$total_spent      = array_sum(array_column($orders, 'final_amount'));
$completed_orders = count(array_filter($orders, fn($o) => $o['status'] === 'delivered'));

// موجودی کیف پول
$walStmt = $db->prepare("SELECT wallet_balance FROM users WHERE id = ?");
$walStmt->execute([$_SESSION['user_id']]);
$walletBalance = (int)$walStmt->fetchColumn();

$csrfToken = Auth::generateCSRFToken();
include 'includes/header.php';
?>

<div class="profile-wrap">

    <?php if($success): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?></div><?php endif; ?>
    <?php if($error):   ?><div class="alert alert-danger" ><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?></div><?php endif; ?>

    <!-- کارت کاربر بالا -->
    <div class="user-hero-card">
        <div class="uhc-bg"></div>
        <div class="uhc-inner">
            <div class="uhc-avatar"><?= mb_substr($user['full_name'],0,1) ?></div>
            <div class="uhc-info">
                <h2><?= htmlspecialchars($user['full_name']) ?></h2>
                <p><?= htmlspecialchars($user['email']) ?></p>
            </div>
        </div>
        <!-- آمار سریع -->
        <div class="uhc-stats">
            <div class="uhc-stat">
                <span class="uhc-stat-num"><?= $total_orders ?></span>
                <span class="uhc-stat-lbl">سفارش</span>
            </div>
            <div class="uhc-stat-divider"></div>
            <div class="uhc-stat">
                <span class="uhc-stat-num"><?= $completed_orders ?></span>
                <span class="uhc-stat-lbl">تحویل‌شده</span>
            </div>
            <div class="uhc-stat-divider"></div>
            <div class="uhc-stat">
                <span class="uhc-stat-num"><?= number_format($total_spent/1000) ?>K</span>
                <span class="uhc-stat-lbl">خرید (ت)</span>
            </div>
            <div class="uhc-stat-divider"></div>
            <div class="uhc-stat">
                <span class="uhc-stat-num" style="font-size:0.9rem;"><?= number_format($walletBalance/1000) ?>K</span>
                <span class="uhc-stat-lbl">کیف پول</span>
            </div>
        </div>
    </div>

    <!-- دسترسی سریع موبایل -->
    <div class="quick-access">
        <a href="wallet.php" class="qa-item">
            <div class="qa-icon" style="background:rgba(139,92,246,0.12);color:var(--primary);">
                <i class="fas fa-wallet"></i>
            </div>
            <span>کیف پول</span>
            <small><?= number_format($walletBalance) ?> ت</small>
        </a>
        <a href="#orders" class="qa-item" onclick="showTab('orders')">
            <div class="qa-icon" style="background:rgba(59,130,246,0.12);color:#8b5cf6;">
                <i class="fas fa-shopping-bag"></i>
            </div>
            <span>سفارشات</span>
            <small><?= $total_orders ?> عدد</small>
        </a>
        <a href="messages.php" class="qa-item">
            <div class="qa-icon" style="background:rgba(139,92,246,0.12);color:#8b5cf6;">
                <i class="fas fa-headset"></i>
            </div>
            <span>پشتیبانی</span>
            <small>تماس با ما</small>
        </a>
        <a href="#settings" class="qa-item" onclick="showTab('settings')">
            <div class="qa-icon" style="background:rgba(245,158,11,0.12);color:#f59e0b;">
                <i class="fas fa-cog"></i>
            </div>
            <span>تنظیمات</span>
            <small>ویرایش</small>
        </a>
    </div>

    <!-- تب‌ها -->
    <div class="profile-tabs">
        <button class="ptab active" onclick="showTab('orders',this)" id="tab-btn-orders">
            <i class="fas fa-shopping-bag"></i> سفارشات
        </button>
        <button class="ptab" onclick="showTab('settings',this)" id="tab-btn-settings">
            <i class="fas fa-user-edit"></i> اطلاعات
        </button>
        <button class="ptab" onclick="showTab('security',this)" id="tab-btn-security">
            <i class="fas fa-key"></i> رمز عبور
        </button>
    </div>

    <!-- سفارشات -->
    <div class="tab-panel active" id="tab-orders">
        <?php if(count($orders) > 0): ?>
        <div class="orders-list">
            <?php foreach($orders as $order):
                $statusMap = [
                    'pending'    => ['label'=>'در انتظار پرداخت','color'=>'#f59e0b','icon'=>'fa-clock',           'bg'=>'rgba(245,158,11,0.1)'],
                    'processing' => ['label'=>'پرداخت تأیید شد', 'color'=>'#3b82f6','icon'=>'fa-check-double',    'bg'=>'rgba(59,130,246,0.1)'],
                    'shipped'    => ['label'=>'ارسال شده',        'color'=>'#8b5cf6','icon'=>'fa-truck',           'bg'=>'rgba(139,92,246,0.1)'],
                    'delivered'  => ['label'=>'تحویل شد',         'color'=>'#8b5cf6','icon'=>'fa-check-circle',    'bg'=>'rgba(139,92,246,0.1)'],
                    'cancelled'  => ['label'=>'لغو شده',          'color'=>'#ef4444','icon'=>'fa-times-circle',    'bg'=>'rgba(239,68,68,0.1)'],
                    'refunded'   => ['label'=>'مرجوع شد',         'color'=>'#6366f1','icon'=>'fa-undo',            'bg'=>'rgba(99,102,241,0.1)'],
                ];
                // وضعیت پرداخت
                $payStatusMap = [
                    'unpaid'   => ['label'=>'پرداخت نشده',    'color'=>'#ef4444'],
                    'partial'  => ['label'=>'پرداخت جزئی',   'color'=>'#f59e0b'],
                    'paid'     => ['label'=>'پرداخت شده ✓',  'color'=>'#8b5cf6'],
                    'refunded' => ['label'=>'عودت شده',       'color'=>'#6366f1'],
                ];
                $st = $statusMap[$order['status']] ?? ['label'=>$order['status'],'color'=>'#94a3b8','icon'=>'fa-question','bg'=>'rgba(148,163,184,0.1)'];
                $productNames = $order['product_names'] ? explode('||',$order['product_names']) : [];
            ?>
            <div class="order-mob-card">
                <!-- هدر سفارش -->
                <div class="omc-header">
                    <div>
                        <div class="omc-num">#<?= htmlspecialchars($order['order_number']) ?></div>
                        <div class="omc-date"><i class="far fa-calendar-alt"></i> <?= date('Y/m/d', strtotime($order['created_at'])) ?></div>
                    </div>
                    <div style="display:flex;flex-direction:column;align-items:flex-end;gap:5px;">
                        <div class="omc-status" style="background:<?= $st['bg'] ?>;color:<?= $st['color'] ?>;">
                            <i class="fas <?= $st['icon'] ?>"></i> <?= $st['label'] ?>
                        </div>
                        <?php
                        $ps = $payStatusMap[$order['payment_status']] ?? ['label'=>$order['payment_status'],'color'=>'#94a3b8'];
                        ?>
                        <div style="font-size:0.7rem;color:<?= $ps['color'] ?>;font-weight:600;">
                            <?= $ps['label'] ?>
                        </div>
                    </div>
                </div>

                <!-- timeline -->
                <div class="omc-timeline">
                    <?php
                    $steps = ['pending'=>0,'processing'=>1,'shipped'=>2,'delivered'=>3];
                    $cur   = $order['status'] === 'cancelled' ? -1 : ($steps[$order['status']] ?? 0);
                    $labels = ['ثبت','پردازش','ارسال','تحویل'];
                    $icons  = ['fa-receipt','fa-cog','fa-truck','fa-check'];
                    foreach($labels as $i => $lbl):
                    ?>
                    <div class="tl-step <?= $cur >= $i ? 'done' : '' ?> <?= $cur === $i ? 'active' : '' ?>">
                        <div class="tl-dot"><i class="fas <?= $icons[$i] ?>"></i></div>
                        <div class="tl-lbl"><?= $lbl ?></div>
                        <?php if($i < 3): ?><div class="tl-line <?= $cur > $i ? 'done' : '' ?>"></div><?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                </div>

                <!-- محصولات -->
                <div class="omc-products">
                    <?php foreach(array_slice($productNames,0,2) as $pname): ?>
                    <span class="omc-product-tag"><?= htmlspecialchars(trim($pname)) ?></span>
                    <?php endforeach; ?>
                    <?php if(count($productNames) > 2): ?>
                    <span class="omc-product-tag" style="color:var(--primary);">+<?= count($productNames)-2 ?> بیشتر</span>
                    <?php endif; ?>
                </div>

                <!-- فوتر -->
                <div class="omc-footer">
                    <div class="omc-price"><?= formatPrice($order['final_amount']) ?></div>
                    <div style="display:flex;gap:8px;align-items:center;">
                        <?php if($order['tracking_code']): ?>
                        <span style="font-size:0.75rem;background:rgba(99,102,241,0.1);color:#6366F1;padding:4px 10px;border-radius:6px;border:1px solid rgba(99,102,241,0.2);">
                            <i class="fas fa-barcode"></i> <?= htmlspecialchars($order['tracking_code']) ?>
                        </span>
                        <?php endif; ?>
                        <?php if($order['payment_status']==='unpaid' && $order['status']!=='cancelled'): ?>
                        <a href="checkout.php?reorder=<?= $order['id'] ?>" class="btn btn-sm" style="background:var(--warning);color:#fff;border:none;padding:6px 12px;font-size:0.8rem;">
                            <i class="fas fa-redo"></i> پرداخت
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
        <div class="empty-tab">
            <i class="fas fa-shopping-bag"></i>
            <h3>هنوز سفارشی ثبت نکرده‌اید</h3>
            <p>محصولات کیف‌لند را کشف کنید!</p>
            <a href="products.php" class="btn btn-primary"><i class="fas fa-store"></i> خرید کنید</a>
        </div>
        <?php endif; ?>
    </div>

    <!-- اطلاعات -->
    <div class="tab-panel" id="tab-settings">
        <div class="profile-card">
            <h3><i class="fas fa-user-edit"></i> ویرایش اطلاعات</h3>
            <form method="POST" data-single-submit>
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">
                <div class="pf-grid">
                    <div class="pf-group">
                        <label>نام و نام خانوادگی</label>
                        <input type="text" name="full_name" value="<?= htmlspecialchars($user['full_name']) ?>" required>
                    </div>
                    <div class="pf-group">
                        <label>نام کاربری</label>
                        <input type="text" value="<?= htmlspecialchars($user['username']) ?>" disabled>
                    </div>
                    <div class="pf-group">
                        <label>ایمیل</label>
                        <input type="email" name="email" value="<?= htmlspecialchars($user['email']) ?>" required>
                    </div>
                    <div class="pf-group">
                        <label>شماره موبایل</label>
                        <input type="tel" name="phone" value="<?= htmlspecialchars($user['phone']??'') ?>" placeholder="09xxxxxxxxx">
                    </div>
                </div>
                <button type="submit" name="update_profile" class="btn btn-primary">
                    <i class="fas fa-save"></i> ذخیره تغییرات
                </button>
            </form>
        </div>
    </div>

    <!-- رمز عبور -->
    <div class="tab-panel" id="tab-security">
        <div class="profile-card">
            <h3><i class="fas fa-key"></i> تغییر رمز عبور</h3>
            <form method="POST" style="max-width:420px;" data-single-submit>
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">
                <div class="pf-group" style="margin-bottom:14px;">
                    <label>رمز عبور فعلی</label>
                    <div class="pass-wrap">
                        <input type="password" name="current_password" id="p1" required>
                        <button type="button" onclick="tp('p1',this)"><i class="fas fa-eye"></i></button>
                    </div>
                </div>
                <div class="pf-group" style="margin-bottom:14px;">
                    <label>رمز عبور جدید</label>
                    <div class="pass-wrap">
                        <input type="password" name="new_password" id="p2" required minlength="8">
                        <button type="button" onclick="tp('p2',this)"><i class="fas fa-eye"></i></button>
                    </div>
                </div>
                <div class="pf-group" style="margin-bottom:20px;">
                    <label>تکرار رمز جدید</label>
                    <div class="pass-wrap">
                        <input type="password" name="confirm_password" id="p3" required>
                        <button type="button" onclick="tp('p3',this)"><i class="fas fa-eye"></i></button>
                    </div>
                </div>
                <button type="submit" name="change_password" class="btn btn-primary">
                    <i class="fas fa-lock"></i> تغییر رمز عبور
                </button>
            </form>
        </div>
    </div>

    <!-- خروج -->
    <div style="padding:0 0 20px;text-align:center;">
        <a href="logout.php" style="color:var(--danger);font-size:0.9rem;display:inline-flex;align-items:center;gap:6px;text-decoration:none;">
            <i class="fas fa-sign-out-alt"></i> خروج از حساب
        </a>
    </div>
</div>

<style>
.profile-wrap { max-width:820px; margin:0 auto; padding:20px 4% 100px; }

/* کارت کاربر */
.user-hero-card {
    background: linear-gradient(135deg,#8b5cf6,#4f46e5);
    border-radius: 20px;
    padding: 24px;
    color: #fff;
    margin-bottom: 16px;
    position: relative;
    overflow: hidden;
}
.uhc-bg { position:absolute;top:-40px;right:-40px;width:180px;height:180px;background:rgba(255,255,255,0.07);border-radius:50%; }
.uhc-inner { display:flex;align-items:center;gap:16px;margin-bottom:20px;position:relative;z-index:1; }
.uhc-avatar { width:58px;height:58px;background:rgba(255,255,255,0.2);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.6rem;font-weight:800;border:2px solid rgba(255,255,255,0.35);flex-shrink:0; }
.uhc-info h2 { font-size:1.15rem;font-weight:700;margin-bottom:4px; }
.uhc-info p  { font-size:0.82rem;opacity:0.75; }
.uhc-stats { display:flex;align-items:center;justify-content:space-around;background:rgba(255,255,255,0.1);border-radius:14px;padding:14px;position:relative;z-index:1; }
.uhc-stat { text-align:center; }
.uhc-stat-num { display:block;font-size:1.2rem;font-weight:800; }
.uhc-stat-lbl { display:block;font-size:0.7rem;opacity:0.75;margin-top:2px; }
.uhc-stat-divider { width:1px;height:32px;background:rgba(255,255,255,0.2); }

/* دسترسی سریع */
.quick-access { display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:16px; }
.qa-item { background:var(--glass-bg-light);border:1px solid var(--glass-border);border-radius:14px;padding:14px 10px;text-align:center;text-decoration:none;color:var(--text-primary);transition:all 0.2s;display:flex;flex-direction:column;align-items:center;gap:6px; }
.qa-item:hover { transform:translateY(-3px);border-color:var(--primary); }
.qa-icon { width:42px;height:42px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:1.1rem;margin-bottom:2px; }
.qa-item span { font-size:0.78rem;font-weight:600;color:var(--text-primary); }
.qa-item small { font-size:0.68rem;color:var(--text-secondary); }

/* تب‌ها */
.profile-tabs { display:flex;gap:6px;background:var(--glass-bg);border:1px solid var(--glass-border);border-radius:14px;padding:6px;margin-bottom:16px; }
.ptab { flex:1;padding:10px;border:none;border-radius:10px;background:transparent;color:var(--text-secondary);font-family:inherit;font-size:0.82rem;font-weight:600;cursor:pointer;transition:all 0.2s;display:flex;align-items:center;justify-content:center;gap:6px; }
.ptab.active { background:var(--primary);color:#fff;box-shadow:0 4px 12px var(--primary-glow); }

/* پنل‌ها */
.tab-panel { display:none; }
.tab-panel.active { display:block; }

/* کارت سفارش موبایل */
.order-mob-card { background:var(--glass-bg-light);border:1px solid var(--glass-border);border-radius:16px;margin-bottom:12px;overflow:hidden;transition:all 0.2s; }
.order-mob-card:hover { border-color:rgba(139,92,246,0.3);box-shadow:0 4px 20px rgba(0,0,0,0.15); }
.omc-header { display:flex;justify-content:space-between;align-items:flex-start;padding:16px;border-bottom:1px solid var(--glass-border); }
.omc-num  { font-family:monospace;font-weight:700;font-size:1rem;color:var(--text-primary); }
.omc-date { font-size:0.75rem;color:var(--text-secondary);margin-top:4px;display:flex;align-items:center;gap:4px; }
.omc-status { display:inline-flex;align-items:center;gap:5px;padding:5px 12px;border-radius:20px;font-size:0.75rem;font-weight:700; }

/* timeline */
.omc-timeline { display:flex;align-items:flex-start;justify-content:center;padding:16px 12px;gap:0; }
.tl-step { display:flex;flex-direction:column;align-items:center;gap:5px;position:relative;flex:1; }
.tl-dot { width:32px;height:32px;border-radius:50%;border:2px solid var(--glass-border);background:var(--glass-bg);display:flex;align-items:center;justify-content:center;font-size:0.75rem;color:var(--text-secondary);transition:all 0.3s;z-index:1; }
.tl-step.done .tl-dot  { background:rgba(139,92,246,0.15);border-color:var(--primary);color:var(--primary); }
.tl-step.active .tl-dot { background:var(--primary);border-color:var(--primary);color:#fff;box-shadow:0 0 0 3px var(--primary-glow); }
.tl-lbl { font-size:0.65rem;color:var(--text-secondary);text-align:center; }
.tl-step.done .tl-lbl,
.tl-step.active .tl-lbl { color:var(--primary); }
.tl-line { position:absolute;top:16px;right:calc(50% + 16px);left:calc(-50% + 16px);height:2px;background:var(--glass-border);z-index:0; }
.tl-line.done { background:var(--primary); }

.omc-products { padding:0 16px 12px;display:flex;flex-wrap:wrap;gap:6px; }
.omc-product-tag { font-size:0.75rem;background:var(--glass-bg);border:1px solid var(--glass-border);padding:4px 10px;border-radius:20px;color:var(--text-secondary); }
.omc-footer { display:flex;justify-content:space-between;align-items:center;padding:12px 16px;background:rgba(0,0,0,0.04);border-top:1px solid var(--glass-border); }
.omc-price { font-weight:700;color:var(--primary);font-size:1rem; }

/* پروفایل فرم */
.profile-card { background:var(--glass-bg-light);border:1px solid var(--glass-border);border-radius:16px;padding:20px;margin-bottom:12px; }
.profile-card h3 { margin:0 0 18px;font-size:1rem;display:flex;align-items:center;gap:8px; }
.pf-grid { display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:18px; }
.pf-group { display:flex;flex-direction:column;gap:6px; }
.pf-group label { font-size:0.82rem;font-weight:600;color:var(--text-secondary); }
.pf-group input { padding:10px 14px;background:var(--glass-bg);border:1px solid var(--glass-border);border-radius:10px;font-family:inherit;font-size:0.9rem;color:var(--text-primary);transition:0.2s; }
.pf-group input:focus { outline:none;border-color:var(--primary);box-shadow:0 0 0 3px var(--primary-glow); }
.pf-group input:disabled { opacity:0.5;cursor:not-allowed; }
.pass-wrap { position:relative; }
.pass-wrap input { width:100%;padding-left:44px; }
.pass-wrap button { position:absolute;left:12px;top:50%;transform:translateY(-50%);background:none;border:none;color:var(--text-secondary);cursor:pointer;font-size:0.9rem; }
.pass-wrap button:hover { color:var(--primary); }

.empty-tab { text-align:center;padding:50px 20px;color:var(--text-secondary); }
.empty-tab i { font-size:3.5rem;opacity:0.2;display:block;margin-bottom:14px; }
.empty-tab h3 { margin-bottom:8px; }
.empty-tab p  { margin-bottom:18px; }

@media(max-width:600px) {
    .quick-access { grid-template-columns:repeat(2,1fr); }
    .pf-grid { grid-template-columns:1fr; }
    .ptab span { display:none; }
    .ptab { font-size:1rem; }
}
</style>

<script>
function showTab(id, btn) {
    document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
    document.querySelectorAll('.ptab').forEach(b => b.classList.remove('active'));
    document.getElementById('tab-' + id)?.classList.add('active');
    if (btn) btn.classList.add('active');
    else document.getElementById('tab-btn-' + id)?.classList.add('active');
    return false;
}
function tp(id, btn) {
    const inp = document.getElementById(id);
    if (inp.type === 'password') { inp.type='text'; btn.innerHTML='<i class="fas fa-eye-slash"></i>'; }
    else { inp.type='password'; btn.innerHTML='<i class="fas fa-eye"></i>'; }
}
// hash
const h = window.location.hash.replace('#','');
if (h) showTab(h);
</script>

<?php include 'includes/footer.php'; ?>