<?php
/**
 * صفحة الحساب الشخصي - Roz Skin E-Commerce
 * Modern App Store / macOS Inspired Design
 */

session_start();
require_once '../includes/product-card.php';
require_once '../config/database.php';
require_once '../models/user.php';
require_once '../models/order.php';
require_once '../models/wishlist.php';

$database = new Database();
$db = $database->getConnection();

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$user = new User($db);
$order = new Order($db);
$wishlist = new Wishlist($db);

// Get user data
$user_data = $user->getUserById($_SESSION['user_id']);
if (!$user_data) {
    header('Location: login.php');
    exit;
}

// Get user orders
$orders = $order->getUserOrders($_SESSION['user_id']);

// Get user wishlist
$wishlist_items = $wishlist->getUserWishlist($_SESSION['user_id']);

// جلب إعدادات الموقع
try {
    $query = "SELECT setting_key, setting_value FROM settings 
              WHERE setting_key IN ('site_name', 'logo_text', 'default_currency')";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

    $site_name = $settings['site_name'] ?? 'Roz Skin';
    $logo_text = $settings['logo_text'] ?? 'Roz Skin';
    $currency = $settings['default_currency'] ?? 'EGP';
} catch (PDOException $e) {
    $site_name = 'Roz Skin';
    $logo_text = 'Roz Skin';
    $currency = 'EGP';
}

$currency_symbols = ['EGP' => 'ج.م', 'USD' => '$', 'EUR' => '€', 'SAR' => 'ر.س', 'AED' => 'د.إ'];
$currency_symbol = $currency_symbols[$currency] ?? 'ج.م';

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_profile'])) {
        $profile_picture_path = $user_data['profile_picture'] ?? null;
        if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = 'uploads/users/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            $file_extension = pathinfo($_FILES['profile_picture']['name'], PATHINFO_EXTENSION);
            $file_name = 'profile_' . $_SESSION['user_id'] . '_' . time() . '.' . $file_extension;
            $target_path = $upload_dir . $file_name;

            $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
            if (in_array(strtolower($file_extension), $allowed_types)) {
                if (move_uploaded_file($_FILES['profile_picture']['tmp_name'], $target_path)) {
                    $profile_picture_path = $target_path;
                }
            }
        }

        if ($user->updateProfile($_SESSION['user_id'], $_POST['name'], $_POST['phone'], $_POST['address'])) {
            if ($profile_picture_path && $profile_picture_path !== ($user_data['profile_picture'] ?? null)) {
                $user->updateProfilePicture($_SESSION['user_id'], $profile_picture_path);
            }
            $_SESSION['user_name'] = $_POST['name'];
            $message = 'تم تحديث البيانات بنجاح!';
            $user_data = $user->getUserById($_SESSION['user_id']);
        }
    } elseif (isset($_POST['change_password'])) {
        if (password_verify($_POST['current_password'], $user_data['password'])) {
            if ($_POST['new_password'] === $_POST['confirm_password']) {
                if ($user->updatePassword($_SESSION['user_id'], $_POST['new_password'])) {
                    $message = 'تم تغيير كلمة المرور بنجاح!';
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>حسابي - <?php echo htmlspecialchars($site_name); ?></title>
    
    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        /* ═══════════════════════════════════════════════════════════
           Modern App Store / macOS Design System
           ═══════════════════════════════════════════════════════════ */
        
        :root {
            /* Colors - macOS inspired */
            --primary: #E57393;
            --primary-dark: #D1537A;
            --bg-primary: #FFFFFF;
            --bg-secondary: #F5F5F7;
            --bg-tertiary: #FAFAFA;
            --text-primary: #1D1D1F;
            --text-secondary: #86868B;
            --border: #D2D2D7;
            --shadow-sm: 0 2px 8px rgba(0,0,0,0.04);
            --shadow-md: 0 4px 16px rgba(0,0,0,0.08);
            --shadow-lg: 0 8px 32px rgba(0,0,0,0.12);
            --radius: 18px;
            --transition: cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Tajawal', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: var(--bg-secondary);
            color: var(--text-primary);
            line-height: 1.6;
            -webkit-font-smoothing: antialiased;
        }
        
        /* Navigation - Minimal & Clean */
        .nav {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
            background: rgba(255, 255, 255, 0.8);
            backdrop-filter: saturate(180%) blur(20px);
            border-bottom: 1px solid rgba(0,0,0,0.05);
        }
        
        .nav-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 16px 24px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .logo {
            font-size: 22px;
            font-weight: 600;
            color: var(--text-primary);
            text-decoration: none;
            letter-spacing: -0.5px;
        }
        
        .nav-actions {
            display: flex;
            gap: 12px;
        }
        
        .icon-btn {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            border: none;
            background: transparent;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.2s var(--transition);
        }
        
        .icon-btn:hover {
            background: rgba(0,0,0,0.05);
        }
        
        /* Container */
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 100px 24px 60px;
        }
        
        /* Header */
        .header {
            text-align: center;
            margin-bottom: 48px;
        }
        
        .header h1 {
            font-size: 48px;
            font-weight: 700;
            letter-spacing: -1px;
            margin-bottom: 12px;
        }
        
        .header p {
            font-size: 21px;
            color: var(--text-secondary);
            font-weight: 400;
        }
        
        /* Grid Layout */
        .grid {
            display: grid;
            grid-template-columns: 280px 1fr;
            gap: 24px;
        }
        
        /* Sidebar - macOS style */
        .sidebar {
            background: var(--bg-primary);
            border-radius: var(--radius);
            padding: 12px;
            box-shadow: var(--shadow-sm);
            height: fit-content;
            position: sticky;
            top: 100px;
        }
        
        .sidebar-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 10px;
            color: var(--text-primary);
            text-decoration: none;
            font-size: 15px;
            font-weight: 500;
            transition: all 0.2s var(--transition);
            cursor: pointer;
        }
        
        .sidebar-item:hover {
            background: var(--bg-secondary);
        }
        
        .sidebar-item.active {
            background: var(--primary);
            color: white;
        }
        
        .sidebar-item svg {
            width: 20px;
            height: 20px;
            opacity: 0.8;
        }
        
        /* Main Content */
        .main {
            background: var(--bg-primary);
            border-radius: var(--radius);
            padding: 48px;
            box-shadow: var(--shadow-sm);
            min-height: 600px;
        }
        
        .section {
            display: none;
        }
        
        .section.active {
            display: block;
            animation: fadeIn 0.3s var(--transition);
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .section-title {
            font-size: 32px;
            font-weight: 700;
            letter-spacing: -0.5px;
            margin-bottom: 32px;
        }
        
        /* Profile Card - App Store style */
        .profile-card {
            background: linear-gradient(135deg, #F5F5F7 0%, #FAFAFA 100%);
            border-radius: var(--radius);
            padding: 32px;
            margin-bottom: 32px;
            border: 1px solid var(--border);
        }
        
        .profile-header {
            display: flex;
            align-items: center;
            gap: 24px;
        }
        
        .avatar {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 40px;
            font-weight: 600;
            box-shadow: 0 8px 24px rgba(229, 115, 147, 0.3);
            overflow: hidden;
        }
        
        .avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .profile-info h3 {
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 4px;
        }
        
        .profile-info p {
            color: var(--text-secondary);
            font-size: 17px;
        }
        
        /* Buttons - macOS style */
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 12px 24px;
            border-radius: 10px;
            font-size: 15px;
            font-weight: 500;
            border: none;
            cursor: pointer;
            transition: all 0.2s var(--transition);
            text-decoration: none;
        }
        
        .btn-primary {
            background: var(--primary);
            color: white;
        }
        
        .btn-primary:hover {
            background: var(--primary-dark);
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(229, 115, 147, 0.3);
        }
        
        .btn-secondary {
            background: var(--bg-secondary);
            color: var(--text-primary);
        }
        
        .btn-secondary:hover {
            background: #E8E8ED;
        }
        
        /* Form - Clean & Modern */
        .form-group {
            margin-bottom: 24px;
        }
        
        .form-label {
            display: block;
            font-size: 15px;
            font-weight: 500;
            margin-bottom: 8px;
            color: var(--text-primary);
        }
        
        .form-input {
            width: 100%;
            padding: 14px 16px;
            border: 1px solid var(--border);
            border-radius: 10px;
            font-size: 15px;
            font-family: inherit;
            transition: all 0.2s var(--transition);
            background: var(--bg-primary);
        }
        
        .form-input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(229, 115, 147, 0.1);
        }
        
        /* Cards - Minimal */
        .card {
            background: var(--bg-tertiary);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 16px;
            border: 1px solid var(--border);
            transition: all 0.2s var(--transition);
        }
        
        .card:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }
        
        /* Status Badge */
        .badge {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 6px;
            font-size: 13px;
            font-weight: 500;
        }
        
        .badge-success { background: #D1FAE5; color: #065F46; }
        .badge-warning { background: #FEF3C7; color: #D97706; }
        .badge-info { background: #DBEAFE; color: #2563EB; }
        .badge-danger { background: #FEE2E2; color: #DC2626; }
        
        /* Message */
        .message {
            background: #D1FAE5;
            color: #065F46;
            padding: 16px 20px;
            border-radius: 10px;
            margin-bottom: 24px;
            font-size: 15px;
            font-weight: 500;
        }
        
        /* Mobile Responsive */
        @media (max-width: 768px) {
            .grid {
                grid-template-columns: 1fr;
            }
            
            .sidebar {
                position: static;
                order: 2;
            }
            
            .main {
                order: 1;
                padding: 24px;
            }
            
            .header h1 {
                font-size: 36px;
            }
            
            .header p {
                font-size: 17px;
            }
            
            .profile-header {
                flex-direction: column;
                text-align: center;
            }
        }
    </style>
    <link rel="stylesheet" href="../assets/css/product-cards.css">
</head>
<body>

    <!-- Navigation -->
    <nav class="nav">
        <div class="nav-content">
            <a href="index.php" class="logo"><?php echo htmlspecialchars($logo_text); ?></a>
            <div class="nav-actions">
                <button class="icon-btn" onclick="window.location.href='wishlist.php'">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
                    </svg>
                </button>
                <button class="icon-btn" onclick="window.location.href='cart.php'">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="9" cy="21" r="1"></circle>
                        <circle cx="20" cy="21" r="1"></circle>
                        <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
                    </svg>
                </button>
            </div>
        </div>
    </nav>

    <!-- Main Container -->
    <div class="container">
        <!-- Header -->
        <div class="header">
            <h1>مرحباً، <?php echo htmlspecialchars($user_data['name'] ?? 'المستخدم'); ?></h1>
            <p>إدارة حسابك ومتابعة طلباتك</p>
        </div>

        <!-- Grid Layout -->
        <div class="grid">
            <!-- Sidebar -->
            <div class="sidebar">
                <div class="sidebar-item active" data-section="profile">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                        <circle cx="12" cy="7" r="4"></circle>
                    </svg>
                    الملف الشخصي
                </div>
                <div class="sidebar-item" data-section="orders">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"></path>
                        <rect x="8" y="2" width="8" height="4" rx="1"></rect>
                    </svg>
                    الطلبات
                </div>
                <div class="sidebar-item" data-section="wishlist">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
                    </svg>
                    المفضلة
                </div>
                <div class="sidebar-item" data-section="password">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <rect x="3" y="11" width="18" height="11" rx="2"></rect>
                        <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                    </svg>
                    الأمان
                </div>
                <a href="logout.php" class="sidebar-item" style="color: #DC2626;">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
                        <polyline points="16 17 21 12 16 7"></polyline>
                        <line x1="21" y1="12" x2="9" y2="12"></line>
                    </svg>
                    تسجيل الخروج
                </a>
            </div>

            <!-- Main Content -->
            <div class="main">
                <?php if ($message): ?>
                    <div class="message"><?php echo $message; ?></div>
                <?php endif; ?>

                <!-- Profile Section -->
                <div id="profile" class="section active">
                    <h2 class="section-title">الملف الشخصي</h2>
                    
                    <div class="profile-card">
                        <div class="profile-header">
                            <div class="avatar">
                                <?php if ($user_data['profile_picture']): ?>
                                    <img src="<?php echo htmlspecialchars($user_data['profile_picture']); ?>" alt="Profile">
                                <?php else: ?>
                                    <?php echo mb_substr($user_data['name'], 0, 1); ?>
                                <?php endif; ?>
                            </div>
                            <div class="profile-info">
                                <h3><?php echo htmlspecialchars($user_data['name']); ?></h3>
                                <p><?php echo htmlspecialchars($user_data['phone']); ?></p>
                                <button class="btn btn-primary" onclick="toggleEdit()" style="margin-top: 12px;">
                                    تعديل البيانات
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Edit Form -->
                    <div id="editForm" style="display: none;">
                        <form method="POST" enctype="multipart/form-data">
                            <div class="form-group">
                                <label class="form-label">الاسم الكامل</label>
                                <input type="text" name="name" class="form-input" value="<?php echo htmlspecialchars($user_data['name']); ?>" required>
                            </div>
                            <div class="form-group">
                                <label class="form-label">رقم الهاتف</label>
                                <input type="tel" name="phone" class="form-input" value="<?php echo htmlspecialchars($user_data['phone']); ?>" required>
                            </div>
                            <div class="form-group">
                                <label class="form-label">العنوان</label>
                                <textarea name="address" class="form-input" rows="3" required><?php echo htmlspecialchars($user_data['address'] ?? ''); ?></textarea>
                            </div>
                            <div class="form-group">
                                <label class="form-label">الصورة الشخصية</label>
                                <input type="file" name="profile_picture" class="form-input" accept="image/*">
                            </div>
                            <div style="display: flex; gap: 12px;">
                                <button type="submit" name="update_profile" class="btn btn-primary">حفظ التغييرات</button>
                                <button type="button" class="btn btn-secondary" onclick="toggleEdit()">إلغاء</button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Orders Section -->
                <div id="orders" class="section">
                    <h2 class="section-title">الطلبات</h2>
                    <?php if (!empty($orders)): ?>
                        <?php foreach ($orders as $order_item): ?>
                            <div class="card">
                                <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 16px;">
                                    <div>
                                        <strong style="font-size: 17px;">طلب #<?php echo $order_item['id']; ?></strong>
                                        <p style="color: var(--text-secondary); font-size: 14px; margin-top: 4px;">
                                            <?php echo date('Y-m-d', strtotime($order_item['created_at'])); ?>
                                        </p>
                                    </div>
                                    <span class="badge badge-<?php 
                                        echo match($order_item['status']) {
                                            'delivered' => 'success',
                                            'shipped' => 'info',
                                            'processing' => 'warning',
                                            'cancelled' => 'danger',
                                            default => 'warning'
                                        };
                                    ?>">
                                        <?php 
                                        $status_ar = [
                                            'pending' => 'قيد الانتظار',
                                            'processing' => 'قيد المعالجة',
                                            'shipped' => 'تم الشحن',
                                            'delivered' => 'تم التسليم',
                                            'cancelled' => 'ملغي'
                                        ];
                                        echo $status_ar[$order_item['status']] ?? $order_item['status'];
                                        ?>
                                    </span>
                                </div>
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <strong style="font-size: 19px; color: var(--primary);">
                                        <?php echo $currency_symbol; ?> <?php echo number_format($order_item['total'], 2); ?>
                                    </strong>
                                    <button class="btn btn-secondary" onclick="window.location.href='order-success.php?order_id=<?php echo $order_item['id']; ?>'">
                                        عرض التفاصيل
                                    </button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div style="text-align: center; padding: 60px 20px; color: var(--text-secondary);">
                            <p style="font-size: 17px; margin-bottom: 20px;">لا توجد طلبات</p>
                            <a href="products.php" class="btn btn-primary">تسوق الآن</a>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Wishlist Section -->
                <div id="wishlist" class="section">
                    <h2 class="section-title">المفضلة</h2>
                    <?php if (!empty($wishlist_items)): ?>
                        <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 16px;">
                            <?php foreach ($wishlist_items as $item): ?>
                                <div class="card">
                                    <div style="display: flex; gap: 16px;">
                                        <div style="width: 80px; height: 80px; border-radius: 10px; background: var(--bg-secondary); overflow: hidden;">
                                            <?php if ($item['image']): ?>
                                                <img src="<?php echo htmlspecialchars($item['image']); ?>" style="width: 100%; height: 100%; object-fit: cover;">
                                            <?php endif; ?>
                                        </div>
                                        <div style="flex: 1;">
                                            <h4 style="font-size: 15px; font-weight: 600; margin-bottom: 8px;">
                                                <?php echo htmlspecialchars($item['name']); ?>
                                            </h4>
                                            <p style="color: var(--primary); font-weight: 600; font-size: 17px; margin-bottom: 12px;">
                                                <?php echo $currency_symbol; ?> <?php echo number_format($item['price'], 0); ?>
                                            </p>
                                            <a href="product.php?id=<?php echo $item['product_id']; ?>" class="btn btn-primary" style="font-size: 14px; padding: 8px 16px;">
                                                عرض المنتج
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div style="text-align: center; padding: 60px 20px; color: var(--text-secondary);">
                            <p style="font-size: 17px; margin-bottom: 20px;">قائمة المفضلة فارغة</p>
                            <a href="products.php" class="btn btn-primary">اكتشف المنتجات</a>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Password Section -->
                <div id="password" class="section">
                    <h2 class="section-title">تغيير كلمة المرور</h2>
                    <form method="POST">
                        <div class="form-group">
                            <label class="form-label">كلمة المرور الحالية</label>
                            <input type="password" name="current_password" class="form-input" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">كلمة المرور الجديدة</label>
                            <input type="password" name="new_password" class="form-input" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">تأكيد كلمة المرور</label>
                            <input type="password" name="confirm_password" class="form-input" required>
                        </div>
                        <button type="submit" name="change_password" class="btn btn-primary">تغيير كلمة المرور</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Tab switching
        document.querySelectorAll('.sidebar-item[data-section]').forEach(item => {
            item.addEventListener('click', function() {
                document.querySelectorAll('.sidebar-item').forEach(i => i.classList.remove('active'));
                document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
                
                this.classList.add('active');
                document.getElementById(this.dataset.section).classList.add('active');
            });
        });

        // Toggle edit form
        function toggleEdit() {
            const form = document.getElementById('editForm');
            const card = document.querySelector('.profile-card');
            
            if (form.style.display === 'none') {
                form.style.display = 'block';
                card.style.display = 'none';
            } else {
                form.style.display = 'none';
                card.style.display = 'block';
            }
        }
    </script>
</body>
</html>
