<?php
/**
 * GlowSpace User Profile Page
 * User profile management with premium design
 */

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/db.php';

session_start();
auth()->requireLogin();

$user = auth()->getCurrentUser();
$settings = getSettings();

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!auth()->validateCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = 'Security error. Please try again.';
    } else {
        $action = $_POST['action'] ?? '';
        
        if ($action === 'update_profile') {
            $fullName = sanitize($_POST['full_name'] ?? '');
            $phone = sanitize($_POST['phone'] ?? '');
            $bio = sanitize($_POST['bio'] ?? '');
            
            if (!empty($fullName)) {
                db()->query(
                    "UPDATE users SET full_name = ? WHERE id = ?",
                    [$fullName, $user['id']]
                );
                
                db()->query(
                    "UPDATE user_profiles SET phone = ?, bio = ? WHERE user_id = ?",
                    [$phone, $bio, $user['id']]
                );
                
                $_SESSION['user_name'] = $fullName;
                $success = 'Profile updated successfully!';
                $user = auth()->getCurrentUser();
            } else {
                $error = 'Full name is required.';
            }
        }
        
        if ($action === 'upload_profile_picture') {
            if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] === UPLOAD_ERR_OK) {
                $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $mimeType = finfo_file($finfo, $_FILES['profile_picture']['tmp_name']);
                finfo_close($finfo);
                
                if (in_array($mimeType, $allowedTypes)) {
                    $ext = pathinfo($_FILES['profile_picture']['name'], PATHINFO_EXTENSION);
                    $filename = 'profiles/' . generateId('IMG') . '.' . $ext;
                    $dest = GS_UPLOADS . '/' . $filename;
                    
                    if (move_uploaded_file($_FILES['profile_picture']['tmp_name'], $dest)) {
                        db()->query(
                            "UPDATE user_profiles SET profile_picture = ? WHERE user_id = ?",
                            [$filename, $user['id']]
                        );
                        $success = 'Profile picture updated!';
                        $user = auth()->getCurrentUser();
                    } else {
                        $error = 'Failed to upload image.';
                    }
                } else {
                    $error = 'Invalid file type. Please upload JPG, PNG, GIF, or WebP.';
                }
            } else {
                $error = 'Please select an image to upload.';
            }
        }
        
        if ($action === 'upload_cover_banner') {
            if (isset($_FILES['cover_banner']) && $_FILES['cover_banner']['error'] === UPLOAD_ERR_OK) {
                $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $mimeType = finfo_file($finfo, $_FILES['cover_banner']['tmp_name']);
                finfo_close($finfo);
                
                if (in_array($mimeType, $allowedTypes)) {
                    $ext = pathinfo($_FILES['cover_banner']['name'], PATHINFO_EXTENSION);
                    $filename = 'profiles/' . generateId('IMG') . '.' . $ext;
                    $dest = GS_UPLOADS . '/' . $filename;
                    
                    if (move_uploaded_file($_FILES['cover_banner']['tmp_name'], $dest)) {
                        db()->query(
                            "UPDATE user_profiles SET cover_banner = ? WHERE user_id = ?",
                            [$filename, $user['id']]
                        );
                        $success = 'Cover banner updated!';
                        $user = auth()->getCurrentUser();
                    } else {
                        $error = 'Failed to upload image.';
                    }
                } else {
                    $error = 'Invalid file type. Please upload JPG, PNG, GIF, or WebP.';
                }
            } else {
                $error = 'Please select an image to upload.';
            }
        }
    }
}

// Get user addresses
$addresses = db()->fetchAll("SELECT * FROM user_addresses WHERE user_id = ? ORDER BY is_default DESC", [$user['id']]);

// Get user wishlist
$wishlist = db()->fetchAll(
    "SELECT w.*, p.title, p.offer_price, p.price, 
     (SELECT image_path FROM product_images WHERE product_id = p.product_id LIMIT 1) as image
     FROM wishlist w
     JOIN products p ON w.product_id = p.product_id
     WHERE w.user_id = ?",
    [$user['id']]
);

// Get recently viewed
$recentlyViewed = db()->fetchAll(
    "SELECT rv.*, p.title, p.offer_price, p.price,
     (SELECT image_path FROM product_images WHERE product_id = p.product_id LIMIT 1) as image
     FROM recently_viewed rv
     JOIN products p ON rv.product_id = p.product_id
     WHERE rv.user_id = ? OR rv.session_id = ?
     ORDER BY rv.viewed_at DESC LIMIT 10",
    [$user['id'], session_id()]
);

$currency = $settings['currency'] ?? '৳';
$primaryColor = $settings['primary_color'] ?? '#D4AF37';
$secondaryColor = $settings['secondary_color'] ?? '#F5A623';
$accentColor = $settings['accent_color'] ?? '#FF4D6D';

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Profile - GlowSpace</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .profile-header {
            background: white;
            border-radius: 20px;
            padding: 0;
            margin-bottom: 30px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .cover-banner {
            height: 200px;
            background: linear-gradient(135deg, <?php echo $primaryColor; ?> 0%, <?php echo $secondaryColor; ?> 100%);
            position: relative;
        }

        .cover-banner img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .cover-banner .upload-btn {
            position: absolute;
            bottom: 20px;
            right: 20px;
            background: rgba(255,255,255,0.9);
            border: none;
            padding: 10px 20px;
            border-radius: 30px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        .cover-banner .upload-btn:hover {
            background: white;
            transform: scale(1.05);
        }

        .profile-info {
            padding: 30px;
            position: relative;
        }

        .profile-picture {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            border: 5px solid white;
            position: absolute;
            top: -60px;
            left: 30px;
            background: white;
            overflow: hidden;
            box-shadow: 0 5px 20px rgba(0,0,0,0.2);
        }

        .profile-picture img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .profile-picture .upload-btn {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0,0,0,0.7);
            color: white;
            border: none;
            padding: 8px;
            cursor: pointer;
            font-size: 12px;
        }

        .user-details {
            margin-left: 150px;
            padding-top: 10px;
        }

        .user-details h1 {
            font-size: 28px;
            color: #333;
            margin-bottom: 5px;
        }

        .user-details p {
            color: #666;
            font-size: 14px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .stat-card {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            padding: 20px;
            border-radius: 15px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .stat-card h3 {
            font-size: 32px;
            color: <?php echo $primaryColor; ?>;
            margin-bottom: 5px;
        }

        .stat-card p {
            color: #666;
            font-size: 14px;
        }

        .content-grid {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 30px;
        }

        .card {
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }

        .card h2 {
            font-size: 24px;
            color: #333;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
        }

        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 14px;
            transition: all 0.3s;
        }

        .form-group input:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: <?php echo $primaryColor; ?>;
        }

        .btn {
            padding: 12px 30px;
            border: none;
            border-radius: 30px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary {
            background: linear-gradient(135deg, <?php echo $primaryColor; ?> 0%, <?php echo $secondaryColor; ?> 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.2);
        }

        .btn-danger {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a5a 100%);
            color: white;
        }

        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.2);
        }

        .address-item {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 15px;
            margin-bottom: 15px;
            border-left: 4px solid <?php echo $primaryColor; ?>;
        }

        .address-item.default {
            border-left-color: #28a745;
        }

        .address-item h4 {
            color: #333;
            margin-bottom: 10px;
        }

        .address-item p {
            color: #666;
            font-size: 14px;
            margin-bottom: 5px;
        }

        .address-actions {
            margin-top: 15px;
        }

        .address-actions button {
            padding: 8px 15px;
            border: none;
            border-radius: 20px;
            cursor: pointer;
            font-size: 12px;
            margin-right: 10px;
        }

        .wishlist-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 20px;
        }

        .wishlist-item {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 15px;
            text-align: center;
            transition: all 0.3s;
        }

        .wishlist-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        }

        .wishlist-item img {
            width: 100%;
            height: 150px;
            object-fit: cover;
            border-radius: 10px;
            margin-bottom: 10px;
        }

        .wishlist-item h4 {
            font-size: 14px;
            color: #333;
            margin-bottom: 5px;
        }

        .wishlist-item .price {
            font-size: 18px;
            color: <?php echo $primaryColor; ?>;
            font-weight: bold;
        }

        .alert {
            padding: 15px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .nav-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .nav-tab {
            padding: 10px 20px;
            border: none;
            border-radius: 25px;
            background: #f0f0f0;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        .nav-tab.active {
            background: linear-gradient(135deg, <?php echo $primaryColor; ?> 0%, <?php echo $secondaryColor; ?> 100%);
            color: white;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        @media (max-width: 768px) {
            .content-grid {
                grid-template-columns: 1fr;
            }

            .profile-picture {
                width: 100px;
                height: 100px;
                top: -50px;
                left: 20px;
            }

            .user-details {
                margin-left: 0;
                padding-top: 60px;
            }

            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <?php if (isset($success)): ?>
            <div class="alert alert-success"><?php echo $success; ?></div>
        <?php endif; ?>

        <?php if (isset($error)): ?>
            <div class="alert alert-error"><?php echo $error; ?></div>
        <?php endif; ?>

        <div class="profile-header">
            <div class="cover-banner">
                <?php if (!empty($user['profile']['cover_banner'])): ?>
                    <img src="<?php echo imgUrl($user['profile']['cover_banner']); ?>" alt="Cover Banner">
                <?php endif; ?>
                <form method="POST" enctype="multipart/form-data" style="display: inline;">
                    <input type="hidden" name="csrf_token" value="<?php echo auth()->getCsrfToken(); ?>">
                    <input type="hidden" name="action" value="upload_cover_banner">
                    <input type="file" name="cover_banner" accept="image/*" style="display: none;" id="coverBannerInput">
                    <button type="button" class="upload-btn" onclick="document.getElementById('coverBannerInput').click()">
                        <i class="fas fa-camera"></i> Change Cover
                    </button>
                </form>
            </div>
            <div class="profile-info">
                <div class="profile-picture">
                    <?php if (!empty($user['profile']['profile_picture'])): ?>
                        <img src="<?php echo imgUrl($user['profile']['profile_picture']); ?>" alt="Profile Picture">
                    <?php else: ?>
                        <img src="https://ui-avatars.com/api/?name=<?php echo urlencode($user['full_name']); ?>&background=<?php echo substr($primaryColor, 1); ?>&color=fff&size=200" alt="Profile Picture">
                    <?php endif; ?>
                    <form method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="csrf_token" value="<?php echo auth()->getCsrfToken(); ?>">
                        <input type="hidden" name="action" value="upload_profile_picture">
                        <input type="file" name="profile_picture" accept="image/*" style="display: none;" id="profilePictureInput">
                        <button type="button" class="upload-btn" onclick="document.getElementById('profilePictureInput').click()">
                            <i class="fas fa-camera"></i>
                        </button>
                    </form>
                </div>
                <div class="user-details">
                    <h1><?php echo htmlspecialchars($user['full_name']); ?></h1>
                    <p><i class="fas fa-envelope"></i> <?php echo htmlspecialchars($user['email']); ?></p>
                    <p><i class="fas fa-calendar"></i> Member since <?php echo date('F Y', strtotime($user['created_at'])); ?></p>
                </div>
                <div class="stats-grid">
                    <div class="stat-card">
                        <h3><?php echo $user['stats']['total_orders']; ?></h3>
                        <p>Total Orders</p>
                    </div>
                    <div class="stat-card">
                        <h3><?php echo $user['stats']['completed_orders']; ?></h3>
                        <p>Completed</p>
                    </div>
                    <div class="stat-card">
                        <h3><?php echo $user['stats']['pending_orders']; ?></h3>
                        <p>Pending</p>
                    </div>
                    <div class="stat-card">
                        <h3><?php echo $user['stats']['wishlist_count']; ?></h3>
                        <p>Wishlist</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="content-grid">
            <div class="main-content">
                <div class="card">
                    <h2>My Profile</h2>
                    <form method="POST">
                        <input type="hidden" name="csrf_token" value="<?php echo auth()->getCsrfToken(); ?>">
                        <input type="hidden" name="action" value="update_profile">
                        <div class="form-group">
                            <label>Full Name</label>
                            <input type="text" name="full_name" value="<?php echo htmlspecialchars($user['full_name']); ?>" required>
                        </div>
                        <div class="form-group">
                            <label>Email</label>
                            <input type="email" value="<?php echo htmlspecialchars($user['email']); ?>" disabled>
                        </div>
                        <div class="form-group">
                            <label>Phone</label>
                            <input type="text" name="phone" value="<?php echo htmlspecialchars($user['profile']['phone'] ?? ''); ?>">
                        </div>
                        <div class="form-group">
                            <label>Bio</label>
                            <textarea name="bio" rows="3"><?php echo htmlspecialchars($user['profile']['bio'] ?? ''); ?></textarea>
                        </div>
                        <button type="submit" class="btn btn-primary">Update Profile</button>
                    </form>
                </div>

                <div class="card">
                    <h2>Saved Addresses</h2>
                    <?php if (empty($addresses)): ?>
                        <p>No saved addresses yet.</p>
                    <?php else: ?>
                        <?php foreach ($addresses as $address): ?>
                            <div class="address-item <?php echo $address['is_default'] ? 'default' : ''; ?>">
                                <h4><?php echo htmlspecialchars($address['full_name']); ?> <?php echo $address['is_default'] ? '<span style="background: #28a745; color: white; padding: 2px 8px; border-radius: 10px; font-size: 12px;">Default</span>' : ''; ?></h4>
                                <p><i class="fas fa-phone"></i> <?php echo htmlspecialchars($address['phone']); ?></p>
                                <p><i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($address['address']); ?>, <?php echo htmlspecialchars($address['upazila']); ?>, <?php echo htmlspecialchars($address['district']); ?></p>
                                <div class="address-actions">
                                    <button style="background: #007bff; color: white;">Edit</button>
                                    <?php if (!$address['is_default']): ?>
                                        <button style="background: #28a745; color: white;">Set Default</button>
                                    <?php endif; ?>
                                    <button style="background: #dc3545; color: white;">Delete</button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    <button class="btn btn-primary" style="margin-top: 20px;">+ Add New Address</button>
                </div>
            </div>

            <div class="sidebar">
                <div class="card">
                    <h2>Quick Actions</h2>
                    <div style="display: flex; flex-direction: column; gap: 10px;">
                        <a href="dashboard.php" class="btn btn-primary" style="text-align: center; text-decoration: none;">
                            <i class="fas fa-tachometer-alt"></i> Dashboard
                        </a>
                        <a href="orders.php" class="btn btn-primary" style="text-align: center; text-decoration: none;">
                            <i class="fas fa-shopping-bag"></i> My Orders
                        </a>
                        <a href="wishlist.php" class="btn btn-primary" style="text-align: center; text-decoration: none;">
                            <i class="fas fa-heart"></i> Wishlist
                        </a>
                        <a href="settings.php" class="btn btn-primary" style="text-align: center; text-decoration: none;">
                            <i class="fas fa-cog"></i> Settings
                        </a>
                        <a href="index.php" class="btn btn-primary" style="text-align: center; text-decoration: none;">
                            <i class="fas fa-home"></i> Back to Shop
                        </a>
                    </div>
                </div>

                <div class="card">
                    <h2>Wishlist Preview</h2>
                    <?php if (empty($wishlist)): ?>
                        <p>Your wishlist is empty.</p>
                    <?php else: ?>
                        <div class="wishlist-grid">
                            <?php foreach (array_slice($wishlist, 0, 4) as $item): ?>
                                <div class="wishlist-item">
                                    <img src="<?php echo imgUrl($item['image']); ?>" alt="<?php echo htmlspecialchars($item['title']); ?>">
                                    <h4><?php echo htmlspecialchars(substr($item['title'], 0, 30)); ?>...</h4>
                                    <div class="price"><?php echo $currency; ?><?php echo number_format($item['offer_price'] ?: $item['price']); ?></div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <?php if (count($wishlist) > 4): ?>
                            <a href="wishlist.php" style="display: block; text-align: center; margin-top: 15px; color: <?php echo $primaryColor; ?>; text-decoration: none;">View All (<?php echo count($wishlist); ?>)</a>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Auto-submit forms when file is selected
        document.getElementById('profilePictureInput').addEventListener('change', function() {
            this.closest('form').submit();
        });

        document.getElementById('coverBannerInput').addEventListener('change', function() {
            this.closest('form').submit();
        });
    </script>
</body>
</html>
