<?php
ob_start();

// profile.php - User Profile Management
// File location: /bidwheels.net/user/profile.php

require_once '../includes/auth.php';
require_once '../includes/functions.php';
require_once '../includes/header.php';

requireLogin();

$user_id = $_SESSION['user_id'];
$user = fetchOne("SELECT * FROM users WHERE id = $user_id");

$success = '';
$error = '';

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_profile'])) {
    $name = sanitize($_POST['name']);
    $phone = sanitize($_POST['phone']);
    $address = sanitize($_POST['address']);
    
    if (empty($name)) {
        $error = 'Name is required.';
    } else {
        update('users', [
            'name' => $name,
            'phone' => $phone,
            'address' => $address
        ], "id = $user_id");
        
        $_SESSION['user_name'] = $name;
        $success = 'Profile updated successfully!';
        $user = fetchOne("SELECT * FROM users WHERE id = $user_id");
    }
}

// Handle password change
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['change_password'])) {
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    
    if (md5($current_password) != $user['password']) {
        $error = 'Current password is incorrect.';
    } elseif (strlen($new_password) < 6) {
        $error = 'New password must be at least 6 characters.';
    } elseif ($new_password != $confirm_password) {
        $error = 'New passwords do not match.';
    } else {
        update('users', ['password' => md5($new_password)], "id = $user_id");
        $success = 'Password changed successfully!';
    }
}

// Get user statistics
$total_bids = getCount('bids', "user_id = $user_id");
$total_comments = getCount('comments', "user_id = $user_id");
$total_won = fetchOne("
    SELECT COUNT(*) as total FROM bids b
    WHERE b.user_id = $user_id 
    AND b.amount = (SELECT MAX(amount) FROM bids WHERE product_id = b.product_id)
    AND (SELECT end_time FROM products WHERE id = b.product_id) < NOW()
");
$won_count = $total_won['total'] ?? 0;

// Get recent bids
$recent_bids = fetchAll("
    SELECT b.*, p.name as product_name, p.id as product_id
    FROM bids b
    LEFT JOIN products p ON b.product_id = p.id
    WHERE b.user_id = $user_id
    ORDER BY b.created_at DESC
    LIMIT 5
");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Profile - <?php echo SITE_NAME; ?></title>
    
    <style>
        .profile-page {
            background: linear-gradient(135deg, #EFEBE0 0%, #e5e0d4 100%);
            min-height: 100vh;
            padding: 40px 0;
        }
        
        .profile-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 24px;
        }
        
        /* Header */
        .profile-header {
            margin-bottom: 30px;
        }
        
        .profile-header h1 {
            font-size: 32px;
            font-weight: 800;
            background: linear-gradient(135deg, #1a1a1a 0%, #FF8C3E 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 8px;
        }
        
        .profile-header p {
            color: #666;
            font-size: 14px;
        }
        
        /* Profile Layout */
        .profile-grid {
            display: grid;
            grid-template-columns: 300px 1fr;
            gap: 30px;
        }
        
        /* Sidebar */
        .profile-sidebar {
            background: white;
            border-radius: 24px;
            padding: 25px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            position: sticky;
            top: 100px;
        }
        
        .avatar {
            width: 120px;
            height: 120px;
            background: linear-gradient(135deg, #FF8C3E, #e67a22);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
        }
        
        .avatar i {
            font-size: 60px;
            color: white;
        }
        
        .sidebar-name {
            font-size: 20px;
            font-weight: 700;
            color: #1a1a1a;
            margin-bottom: 5px;
        }
        
        .sidebar-email {
            font-size: 13px;
            color: #888;
            margin-bottom: 20px;
            word-break: break-all;
        }
        
        .sidebar-stats {
            display: flex;
            justify-content: center;
            gap: 25px;
            margin-bottom: 25px;
            padding: 15px 0;
            border-top: 1px solid #f0f0f0;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .sidebar-stat {
            text-align: center;
        }
        
        .sidebar-stat .number {
            font-size: 20px;
            font-weight: 800;
            color: #FF8C3E;
        }
        
        .sidebar-stat .label {
            font-size: 11px;
            color: #888;
        }
        
        .member-since {
            font-size: 12px;
            color: #888;
            margin-bottom: 20px;
        }
        
        .member-since i {
            color: #FF8C3E;
            margin-right: 5px;
        }
        
        /* Main Content */
        .profile-main {
            background: white;
            border-radius: 24px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }
        
        /* Form Sections */
        .form-section {
            margin-bottom: 35px;
            padding-bottom: 25px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .form-section:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
        
        .section-title {
            font-size: 18px;
            font-weight: 700;
            color: #1a1a1a;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .section-title i {
            color: #FF8C3E;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            font-size: 13px;
            color: #333;
        }
        
        .form-group label i {
            color: #FF8C3E;
            margin-right: 6px;
        }
        
        .input-wrapper {
            position: relative;
        }
        
        .input-wrapper i {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            color: #aaa;
            font-size: 16px;
        }
        
        .input-wrapper input,
        .input-wrapper textarea {
            width: 100%;
            padding: 12px 16px 12px 45px;
            border: 2px solid #f0f0f0;
            border-radius: 14px;
            font-size: 14px;
            transition: all 0.3s;
            background: #f8f8f8;
            font-family: inherit;
        }
        
        .input-wrapper textarea {
            padding-top: 12px;
            resize: vertical;
            min-height: 80px;
        }
        
        .input-wrapper input:focus,
        .input-wrapper textarea:focus {
            outline: none;
            border-color: #FF8C3E;
            background: white;
        }
        
        .input-wrapper input:disabled {
            background: #f0f0f0;
            color: #888;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        
        /* Password Strength */
        .password-strength {
            margin-top: 8px;
            display: flex;
            gap: 8px;
            align-items: center;
        }
        
        .strength-bar {
            flex: 1;
            height: 4px;
            background: #f0f0f0;
            border-radius: 4px;
            overflow: hidden;
        }
        
        .strength-fill {
            height: 100%;
            width: 0%;
            background: #dc3545;
            transition: width 0.3s, background 0.3s;
        }
        
        .strength-text {
            font-size: 11px;
            color: #888;
            min-width: 60px;
        }
        
        /* Buttons */
        .btn-submit {
            background: linear-gradient(135deg, #FF8C3E, #e67a22);
            border: none;
            border-radius: 40px;
            color: white;
            padding: 12px 28px;
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(255,140,62,0.3);
        }
        
        .btn-secondary {
            background: #f0f0f0;
            color: #666;
            border: none;
            border-radius: 40px;
            padding: 12px 28px;
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        /* Recent Bids Table */
        .recent-bids-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }
        
        .recent-bids-table th,
        .recent-bids-table td {
            padding: 12px 8px;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
            font-size: 13px;
        }
        
        .recent-bids-table th {
            color: #888;
            font-weight: 500;
        }
        
        .recent-bids-table a {
            color: #1a1a1a;
            text-decoration: none;
        }
        
        .recent-bids-table a:hover {
            color: #FF8C3E;
        }
        
        .bid-amount {
            color: #FF8C3E;
            font-weight: 700;
        }
        
        .view-all-link {
            display: inline-block;
            margin-top: 15px;
            color: #FF8C3E;
            text-decoration: none;
            font-size: 13px;
            font-weight: 600;
        }
        
        /* Alerts */
        .alert {
            padding: 14px 18px;
            border-radius: 14px;
            margin-bottom: 24px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 13px;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border-left: 4px solid #28a745;
        }
        
        .alert-danger {
            background: #f8d7da;
            color: #721c24;
            border-left: 4px solid #dc3545;
        }
        
        .alert i {
            font-size: 18px;
        }
        
        /* Responsive */
        @media (max-width: 992px) {
            .profile-grid {
                grid-template-columns: 1fr;
            }
            
            .profile-sidebar {
                position: static;
                max-width: 400px;
                margin: 0 auto;
            }
        }
        
        @media (max-width: 768px) {
            .profile-container {
                padding: 0 16px;
            }
            
            .profile-header h1 {
                font-size: 28px;
            }
            
            .profile-main {
                padding: 20px;
            }
            
            .form-row {
                grid-template-columns: 1fr;
                gap: 15px;
            }
            
            .recent-bids-table {
                display: block;
                overflow-x: auto;
            }
        }
        
        @media (max-width: 480px) {
            .sidebar-stats {
                gap: 15px;
            }
            
            .sidebar-stat .number {
                font-size: 18px;
            }
        }
    </style>
</head>
<body>

<div class="profile-page">
    <div class="profile-container">
        <div class="profile-header">
            <h1>My Profile</h1>
            <p>Manage your account information and preferences</p>
        </div>
        
        <div class="profile-grid">
            <!-- Sidebar -->
            <div class="profile-sidebar">
                <div class="avatar">
                    <i class="fas fa-user-circle"></i>
                </div>
                <div class="sidebar-name"><?php echo htmlspecialchars($user['name'] ?? ''); ?></div>
                <div class="sidebar-email"><?php echo htmlspecialchars($user['email'] ?? ''); ?></div>
                <div class="sidebar-stats">
                    <div class="sidebar-stat">
                        <div class="number"><?php echo $total_bids; ?></div>
                        <div class="label">Bids</div>
                    </div>
                    <div class="sidebar-stat">
                        <div class="number"><?php echo $won_count; ?></div>
                        <div class="label">Won</div>
                    </div>
                    <div class="sidebar-stat">
                        <div class="number"><?php echo $total_comments; ?></div>
                        <div class="label">Comments</div>
                    </div>
                </div>
                <div class="member-since">
                    <i class="fas fa-calendar-alt"></i> Member since <?php echo date('F d, Y', strtotime($user['created_at'])); ?>
                </div>
            </div>
            
            <!-- Main Content -->
            <div class="profile-main">
                <?php if ($success): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i>
                        <span><?php echo $success; ?></span>
                    </div>
                <?php endif; ?>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle"></i>
                        <span><?php echo $error; ?></span>
                    </div>
                <?php endif; ?>
                
                <!-- Profile Information Form -->
                <form method="POST" action="" class="form-section">
                    <div class="section-title">
                        <i class="fas fa-user-edit"></i> Profile Information
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-user"></i> Full Name *</label>
                        <div class="input-wrapper">
                            <i class="fas fa-user"></i>
                            <input type="text" name="name" value="<?php echo htmlspecialchars($user['name'] ?? ''); ?>" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-envelope"></i> Email Address</label>
                        <div class="input-wrapper">
                            <i class="fas fa-envelope"></i>
                            <input type="email" value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>" disabled>
                        </div>
                        <small style="color: #888;">Email cannot be changed</small>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label><i class="fas fa-phone"></i> Phone Number</label>
                            <div class="input-wrapper">
                                <i class="fas fa-phone"></i>
                                <input type="tel" name="phone" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>" placeholder="+1 234 567 8900">
                            </div>
                        </div>
                        <div class="form-group">
                            <label><i class="fas fa-map-marker-alt"></i> Address</label>
                            <div class="input-wrapper">
                                <i class="fas fa-map-marker-alt"></i>
                                <textarea name="address" placeholder="Your address"><?php echo htmlspecialchars($user['address'] ?? ''); ?></textarea>
                            </div>
                        </div>
                    </div>
                    <button type="submit" name="update_profile" class="btn-submit">
                        <i class="fas fa-save"></i> Save Changes
                    </button>
                </form>
                
                <!-- Change Password Form -->
                <form method="POST" action="">
                    <div class="section-title">
                        <i class="fas fa-key"></i> Change Password
                    </div>
                    <div class="form-group">
                        <label><i class="fas fa-lock"></i> Current Password</label>
                        <div class="input-wrapper">
                            <i class="fas fa-lock"></i>
                            <input type="password" name="current_password" placeholder="Enter current password" required>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label><i class="fas fa-lock"></i> New Password</label>
                            <div class="input-wrapper">
                                <i class="fas fa-lock"></i>
                                <input type="password" name="new_password" id="new_password" placeholder="Min. 6 characters" required>
                            </div>
                            <div class="password-strength">
                                <div class="strength-bar">
                                    <div class="strength-fill" id="strengthFill"></div>
                                </div>
                                <span class="strength-text" id="strengthText">Weak</span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label><i class="fas fa-check-circle"></i> Confirm Password</label>
                            <div class="input-wrapper">
                                <i class="fas fa-check-circle"></i>
                                <input type="password" name="confirm_password" id="confirm_password" placeholder="Confirm new password" required>
                            </div>
                        </div>
                    </div>
                    <button type="submit" name="change_password" class="btn-submit">
                        <i class="fas fa-key"></i> Update Password
                    </button>
                </form>
                
                <!-- Recent Bids -->
                <?php if (count($recent_bids) > 0): ?>
                <div class="form-section" style="margin-top: 30px; padding-top: 20px;">
                    <div class="section-title">
                        <i class="fas fa-history"></i> Recent Bids
                    </div>
                    <table class="recent-bids-table">
                        <thead>
                            <tr><th>Product</th><th>Bid Amount</th><th>Date</th></tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recent_bids as $bid): ?>
                            <tr>
                                <td><a href="<?php echo SITE_URL; ?>/product/detail.php?id=<?php echo $bid['product_id']; ?>"><?php echo htmlspecialchars($bid['product_name'] ?? ''); ?></a></td>
                                <td class="bid-amount"><?php echo formatPrice($bid['amount']); ?></td>
                                <td><?php echo date('M d, Y', strtotime($bid['created_at'])); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <a href="my_bids.php" class="view-all-link">View All Bids <i class="fas fa-arrow-right"></i></a>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
// Password strength checker
const password = document.getElementById('new_password');
const strengthFill = document.getElementById('strengthFill');
const strengthText = document.getElementById('strengthText');

if (password) {
    password.addEventListener('input', function() {
        const value = this.value;
        let strength = 0;
        let color = '#dc3545';
        let text = 'Weak';
        
        if (value.length >= 6) strength += 1;
        if (value.length >= 8) strength += 1;
        if (/[A-Z]/.test(value)) strength += 1;
        if (/[0-9]/.test(value)) strength += 1;
        if (/[^A-Za-z0-9]/.test(value)) strength += 1;
        
        if (strength >= 4) {
            color = '#28a745';
            text = 'Strong';
        } else if (strength >= 2) {
            color = '#ffc107';
            text = 'Medium';
        } else {
            color = '#dc3545';
            text = 'Weak';
        }
        
        const percentage = (strength / 5) * 100;
        strengthFill.style.width = percentage + '%';
        strengthFill.style.background = color;
        strengthText.textContent = text;
        strengthText.style.color = color;
    });
}

// Password confirmation validation
const confirmPassword = document.getElementById('confirm_password');
if (confirmPassword) {
    confirmPassword.addEventListener('input', function() {
        if (this.value !== password.value) {
            this.setCustomValidity('Passwords do not match');
        } else {
            this.setCustomValidity('');
        }
    });
}
</script>

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