<?php
// reset_password.php - Reset Password with Token
// File location: /bidwheels.net/user/reset_password.php

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

$token = isset($_GET['token']) ? sanitize($_GET['token']) : '';
$error = '';
$success = '';

if (empty($token)) {
    redirect('/user/login.php');
}

// Check if token is valid
$reset = fetchOne("
    SELECT * FROM password_resets 
    WHERE token = '$token' AND expires_at > NOW() AND used = 0
");

if (!$reset) {
    $error = "Invalid or expired reset link. Please request a new one.";
} else {
    $user = fetchOne("SELECT id, name FROM users WHERE id = {$reset['user_id']}");
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && $reset) {
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    
    if (strlen($password) < 6) {
        $error = "Password must be at least 6 characters.";
    } elseif ($password !== $confirm_password) {
        $error = "Passwords do not match.";
    } else {
        // Update password
        update('users', ['password' => md5($password)], "id = {$reset['user_id']}");
        
        // Mark token as used
        update('password_resets', ['used' => 1], "id = {$reset['id']}");
        
        $success = "Password has been reset successfully!";
        
        // Redirect after 3 seconds
        header("refresh:3;url=login.php");
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset Password - <?php echo SITE_NAME; ?></title>
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        .reset-page {
            min-height: calc(100vh - 200px);
            background: linear-gradient(135deg, #EFEBE0 0%, #e5e0d4 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 60px 24px;
        }
        
        .reset-container {
            max-width: 500px;
            width: 100%;
            background: white;
            border-radius: 32px;
            overflow: hidden;
            box-shadow: 0 25px 50px rgba(0,0,0,0.1);
        }
        
        .reset-header {
            background: linear-gradient(135deg, #1a1a1a 0%, #2a2a2a 100%);
            padding: 40px;
            text-align: center;
        }
        
        .reset-header img {
            height: 50px;
            width: auto;
            margin-bottom: 20px;
        }
        
        .reset-header h1 {
            font-size: 28px;
            font-weight: 700;
            color: white;
            margin-bottom: 10px;
        }
        
        .reset-header p {
            color: #aaa;
            font-size: 14px;
        }
        
        .reset-body {
            padding: 40px;
        }
        
        .form-group {
            margin-bottom: 24px;
        }
        
        .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 {
            width: 100%;
            padding: 14px 16px 14px 48px;
            border: 2px solid #f0f0f0;
            border-radius: 16px;
            font-size: 14px;
            transition: all 0.3s;
            background: #f8f8f8;
        }
        
        .input-wrapper input:focus {
            outline: none;
            border-color: #FF8C3E;
            background: white;
        }
        
        .password-toggle {
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #aaa;
            background: none;
            border: none;
            font-size: 16px;
        }
        
        .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%;
            transition: width 0.3s, background 0.3s;
        }
        
        .strength-text {
            font-size: 11px;
            color: #888;
            min-width: 60px;
        }
        
        .btn-submit {
            width: 100%;
            padding: 16px;
            background: linear-gradient(135deg, #FF8C3E, #e67a22);
            border: none;
            border-radius: 50px;
            color: white;
            font-weight: 700;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        
        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(255,140,62,0.3);
        }
        
        .alert {
            padding: 14px 18px;
            border-radius: 16px;
            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;
        }
        
        @media (max-width: 576px) {
            .reset-page {
                padding: 40px 16px;
            }
            
            .reset-header {
                padding: 30px 20px;
            }
            
            .reset-header h1 {
                font-size: 24px;
            }
            
            .reset-body {
                padding: 30px 20px;
            }
        }
    </style>
</head>
<body>

<div class="reset-page">
    <div class="reset-container">
        <div class="reset-header">
            <img src="<?php echo SITE_URL . SITE_LOGO; ?>" alt="<?php echo SITE_NAME; ?>">
            <h1>Reset Password</h1>
            <p>Create a new password for your account</p>
        </div>
        
        <div class="reset-body">
            <?php if ($error): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <span><?php echo $error; ?></span>
                </div>
            <?php endif; ?>
            
            <?php if ($success): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i>
                    <span><?php echo $success; ?> Redirecting to login...</span>
                </div>
            <?php endif; ?>
            
            <?php if ($reset && !$success): ?>
                <p style="margin-bottom: 20px; color: #666;">Reset password for: <strong><?php echo htmlspecialchars($user['name']); ?></strong></p>
                
                <form method="POST" action="" id="resetForm">
                    <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="password" id="password" placeholder="Enter new password" required>
                            <button type="button" class="password-toggle" onclick="togglePassword('password')">
                                <i class="fas fa-eye-slash"></i>
                            </button>
                        </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="confirmPassword" placeholder="Confirm new password" required>
                            <button type="button" class="password-toggle" onclick="togglePassword('confirmPassword')">
                                <i class="fas fa-eye-slash"></i>
                            </button>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn-submit">
                        <i class="fas fa-key"></i> Reset Password
                    </button>
                </form>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// Password toggle function
function togglePassword(fieldId) {
    const input = document.getElementById(fieldId);
    const icon = input.parentElement.querySelector('.password-toggle i');
    
    if (input.type === 'password') {
        input.type = 'text';
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    } else {
        input.type = 'password';
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
    }
}

// Password strength checker
const password = document.getElementById('password');
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;
        document.getElementById('strengthFill').style.width = percentage + '%';
        document.getElementById('strengthFill').style.background = color;
        document.getElementById('strengthText').textContent = text;
        document.getElementById('strengthText').style.color = color;
    });
}

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

// Form submission validation
const resetForm = document.getElementById('resetForm');
if (resetForm) {
    resetForm.addEventListener('submit', function(e) {
        if (password.value !== confirmPassword.value) {
            e.preventDefault();
            alert('Passwords do not match');
            return false;
        }
        return true;
    });
}
</script>

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