<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
include "../config/db.php";
require_once "../php-api-server/services/MailService.php";


$success = '';
$error = '';
$step = isset($_GET['step']) ? $_GET['step'] : 1;

// Create password_resets table if it doesn't exist
$table_check = mysqli_query($conn, "SHOW TABLES LIKE 'password_resets'");
if(mysqli_num_rows($table_check) == 0) {
    $create_table = "CREATE TABLE password_resets (
        id INT PRIMARY KEY AUTO_INCREMENT,
        email VARCHAR(100) NOT NULL,
        token VARCHAR(100) NOT NULL,
        expires_at DATETIME NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_token (token),
        INDEX idx_email (email)
    )";
    mysqli_query($conn, $create_table);
}

// Step 1: Request password reset
if (isset($_POST['request_reset'])) {
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    
    // Check if email exists
    $query = "SELECT * FROM users WHERE email='$email'";
    $result = mysqli_query($conn, $query);
    
    if (mysqli_num_rows($result) == 1) {
        $user = mysqli_fetch_assoc($result);
        
        // Generate reset token
        $token = bin2hex(random_bytes(50));
        // Delete old tokens for this user
        mysqli_query($conn, "DELETE FROM password_resets WHERE email='$email'");
        
        // Insert new token using MySQL's clock to prevent timezone bugs
        $insert_query = "INSERT INTO password_resets (email, token, expires_at) 
                         VALUES ('$email', '$token', DATE_ADD(NOW(), INTERVAL 1 HOUR))";
        
        if(mysqli_query($conn, $insert_query)) {
            // Send reset email via MailService
            $mailSent = MailService::sendPasswordReset($email, $token);
            
            if ($mailSent) {
                $success = "A password reset link has been sent to $email. Please check your inbox (and spam folder).";
                $step = 1; // Stay on step 1 with success message
            } else {
                // Even if mail() fails, in development we can check the log
                $success = "Password reset initiated. Please check your email (or the server logs in development).";
                $step = 1;
            }
            
            // Clear any sensitive link from session
            unset($_SESSION['reset_link']);
        } else {
            $error = "Error generating reset token. Please try again.";
        }
    } else {
        $error = "Email not found in our system.";
    }
}

// Step 2: Reset password
if (isset($_POST['reset_password'])) {
    $token = mysqli_real_escape_string($conn, $_POST['token']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    
    if ($password !== $confirm_password) {
        $error = "Passwords do not match!";
    } elseif (strlen($password) < 6) {
        $error = "Password must be at least 6 characters long!";
    } else {
        // Check if token exists and is valid
        $query = "SELECT * FROM password_resets WHERE token='$token' AND expires_at > NOW()";
        $result = mysqli_query($conn, $query);
        
        if (mysqli_num_rows($result) == 1) {
            $reset_request = mysqli_fetch_assoc($result);
            $email = $reset_request['email'];
            
            // Hash new password
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            
            // Update password
            $update_query = "UPDATE users SET password='$hashed_password' WHERE email='$email'";
            
            if (mysqli_query($conn, $update_query)) {
                // Delete used token
                mysqli_query($conn, "DELETE FROM password_resets WHERE token='$token'");
                
                // Clear session
                unset($_SESSION['reset_token']);
                unset($_SESSION['reset_email']);
                unset($_SESSION['reset_link']);
                
                $success = "Password reset successfully! You can now login with your new password.";
                $step = 3; // Success step
            } else {
                $error = "Error updating password. Please try again.";
            }
        } else {
            $error = "Invalid or expired reset token. Please request a new password reset.";
            $step = 1;
        }
    }
}

// Check if token is provided in URL
if(isset($_GET['token']) && $step == 2) {
    $token = mysqli_real_escape_string($conn, $_GET['token']);
    
    // Verify token from database
    $query = "SELECT * FROM password_resets WHERE token='$token' AND expires_at > NOW()";
    $result = mysqli_query($conn, $query);
    
    if(mysqli_num_rows($result) == 0) {
        $error = "Invalid or expired reset token.";
        $step = 1;
    } else {
        $reset_request = mysqli_fetch_assoc($result);
        $_SESSION['reset_token'] = $token;
        $_SESSION['reset_email'] = $reset_request['email'];
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot Password - StyleHub</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="../assets/css/style.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(rgba(255,255,255,0.9), rgba(255,255,255,0.9)), 
                        url('../assets/images/fabric-bg.jpg');
            background-size: cover;
            background-attachment: fixed;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            min-height: 100vh;
            display: flex;
            align-items: center;
        }
        
        .forgot-container {
            width: 100%;
            padding: 20px;
        }
        
        .forgot-card {
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 15px 50px rgba(0,0,0,0.1);
            width: 100%;
            max-width: 500px;
            margin: 0 auto;
            border-top: 5px solid #ff6b35;
        }
        
        .forgot-header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .forgot-header i {
            font-size: 3rem;
            color: #ff6b35;
            margin-bottom: 15px;
        }
        
        .btn-orange {
            background: linear-gradient(45deg, #ff6b35, #ff8e53);
            border: none;
            color: white;
            padding: 12px 30px;
            border-radius: 25px;
            font-weight: 600;
            transition: all 0.3s;
            width: 100%;
        }
        
        .btn-orange:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255, 107, 53, 0.3);
            color: white;
        }
        
        .reset-link-box {
            background: #f8f9fa;
            border: 2px dashed #ff6b35;
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
            word-break: break-all;
        }
        
        .copy-btn {
            cursor: pointer;
            background: #3498db;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            margin-top: 10px;
        }
        
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;
        }
        
        .step {
            text-align: center;
            flex: 1;
        }
        
        .step-circle {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: #e0e0e0;
            color: #666;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 10px;
            font-weight: bold;
        }
        
        .step.active .step-circle {
            background: #ff6b35;
            color: white;
        }
        
        .step.completed .step-circle {
            background: #28a745;
            color: white;
        }
    </style>
</head>
<body>
    <div class="forgot-container">
        <div class="forgot-card">
            <!-- Step Indicator -->
            <div class="step-indicator">
                <div class="step <?php echo $step == 1 || $step == 1.5 ? 'active' : ''; ?> <?php echo $step > 1 ? 'completed' : ''; ?>">
                    <div class="step-circle">1</div>
                    <div class="step-text">Enter Email</div>
                </div>
                <div class="step <?php echo $step == 2 ? 'active' : ''; ?> <?php echo $step > 2 ? 'completed' : ''; ?>">
                    <div class="step-circle">2</div>
                    <div class="step-text">Reset Password</div>
                </div>
                <div class="step <?php echo $step == 3 ? 'active' : ''; ?>">
                    <div class="step-circle">3</div>
                    <div class="step-text">Complete</div>
                </div>
            </div>
            
            <div class="forgot-header">
                <i class="fas fa-key"></i>
                <h2 style="color: #2c3e50;">
                    <?php 
                    if($step == 1 || $step == 1.5) echo "Forgot Password";
                    elseif($step == 2) echo "Reset Your Password";
                    else echo "Password Reset Complete";
                    ?>
                </h2>
                <p class="text-muted">
                    <?php 
                    if($step == 1) echo "Enter your email to reset password";
                    elseif($step == 1.5) echo "Copy the reset link below";
                    elseif($step == 2) echo "Create a new password";
                    else echo "Your password has been reset successfully";
                    ?>
                </p>
            </div>

            <!-- Display Messages -->
            <?php if($success): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle me-2"></i>
                    <?php echo $success; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if($error): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-circle me-2"></i>
                    <?php echo $error; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- Step 1: Request Reset -->
            <?php if($step == 1): ?>
            <form method="POST" id="requestForm">
                <div class="mb-4">
                    <label class="form-label fw-bold">
                        <i class="fas fa-envelope me-2"></i>Email Address
                    </label>
                    <input type="email" 
                           name="email" 
                           class="form-control form-control-lg"
                           placeholder="Enter your registered email"
                           required
                           value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>">
                    <small class="text-muted">We'll generate a password reset link for you</small>
                </div>
                
                <button type="submit" name="request_reset" class="btn btn-orange btn-lg">
                    <i class="fas fa-paper-plane me-2"></i>Generate Reset Link
                </button>
                
                <div class="text-center mt-4">
                    <p class="text-muted">
                        Remember your password? 
                        <a href="login.php" style="color: #ff6b35; font-weight: 600;">
                            Back to Login
                        </a>
                    </p>
                </div>
            </form>
            <?php endif; ?>


            <!-- Step 2: Reset Password -->
            <?php if($step == 2 && isset($_GET['token'])): 
                $token = $_GET['token'];
            ?>
            <form method="POST" id="resetForm">
                <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">
                
                <div class="mb-4">
                    <label class="form-label fw-bold">
                        <i class="fas fa-lock me-2"></i>New Password
                    </label>
                    <input type="password" 
                           name="password" 
                           id="password"
                           class="form-control form-control-lg"
                           placeholder="Enter new password (min 6 characters)"
                           required>
                    <div class="progress mt-2" style="height: 5px;">
                        <div class="progress-bar" id="strengthBar" role="progressbar"></div>
                    </div>
                </div>
                
                <div class="mb-4">
                    <label class="form-label fw-bold">
                        <i class="fas fa-lock me-2"></i>Confirm Password
                    </label>
                    <input type="password" 
                           name="confirm_password" 
                           id="confirm_password"
                           class="form-control form-control-lg"
                           placeholder="Confirm new password"
                           required>
                    <div class="mt-2" id="passwordMatch"></div>
                </div>
                
                <button type="submit" name="reset_password" class="btn btn-orange btn-lg">
                    <i class="fas fa-save me-2"></i>Reset Password
                </button>
                
                <div class="text-center mt-4">
                    <a href="login.php" class="text-decoration-none" style="color: #ff6b35; font-weight: 600;">
                        <i class="fas fa-arrow-left me-1"></i>Back to Login
                    </a>
                </div>
            </form>
            <?php elseif($step == 2 && !isset($_GET['token'])): ?>
                <div class="alert alert-warning text-center">
                    <i class="fas fa-exclamation-triangle fa-2x mb-3"></i>
                    <h4>Invalid Reset Link</h4>
                    <p class="mb-3">The reset link is invalid or has expired.</p>
                    <a href="forgot-password.php" class="btn btn-orange">
                        <i class="fas fa-redo me-2"></i>Request New Reset
                    </a>
                </div>
            <?php endif; ?>

            <!-- Step 3: Success -->
            <?php if($step == 3): ?>
            <div class="text-center">
                <div class="mb-4">
                    <i class="fas fa-check-circle fa-4x" style="color: #28a745;"></i>
                </div>
                <h4 class="mb-3">Password Reset Successful!</h4>
                <p class="text-muted mb-4">Your password has been updated successfully. You can now login with your new password.</p>
                
                <div class="d-grid gap-2">
                    <a href="login.php" class="btn btn-orange btn-lg">
                        <i class="fas fa-sign-in-alt me-2"></i>Go to Login
                    </a>
                    <a href="../index.php" class="btn btn-outline-secondary">
                        <i class="fas fa-home me-2"></i>Back to Home
                    </a>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // Copy reset link to clipboard
        function copyResetLink() {
            const resetLink = document.getElementById('resetLink').textContent;
            navigator.clipboard.writeText(resetLink).then(() => {
                const message = document.getElementById('copyMessage');
                message.style.display = 'inline';
                setTimeout(() => {
                    message.style.display = 'none';
                }, 2000);
            });
        }
        
        // Password strength checker
        document.getElementById('password')?.addEventListener('input', function() {
            const password = this.value;
            const strengthBar = document.getElementById('strengthBar');
            
            let strength = 0;
            
            // Length check
            if(password.length >= 6) strength += 25;
            if(password.length >= 8) strength += 15;
            
            // Complexity checks
            if(/[A-Z]/.test(password)) strength += 20;
            if(/[a-z]/.test(password)) strength += 20;
            if(/[0-9]/.test(password)) strength += 20;
            if(/[^A-Za-z0-9]/.test(password)) strength += 20;
            
            // Cap at 100
            strength = Math.min(strength, 100);
            
            // Update progress bar
            strengthBar.style.width = strength + '%';
            
            // Color based on strength
            if(strength < 40) {
                strengthBar.className = 'progress-bar bg-danger';
            } else if(strength < 70) {
                strengthBar.className = 'progress-bar bg-warning';
            } else {
                strengthBar.className = 'progress-bar bg-success';
            }
        });
        
        // Password match checker
        document.getElementById('confirm_password')?.addEventListener('input', function() {
            const password = document.getElementById('password').value;
            const confirm = this.value;
            const matchDiv = document.getElementById('passwordMatch');
            
            if(confirm === '') {
                matchDiv.innerHTML = '';
                matchDiv.className = '';
            } else if(password === confirm) {
                matchDiv.innerHTML = '<i class="fas fa-check text-success me-1"></i>Passwords match';
                matchDiv.className = 'text-success';
            } else {
                matchDiv.innerHTML = '<i class="fas fa-times text-danger me-1"></i>Passwords do not match';
                matchDiv.className = 'text-danger';
            }
        });
        
        // Form validation
        document.getElementById('resetForm')?.addEventListener('submit', function(e) {
            const password = document.getElementById('password').value;
            const confirm = document.getElementById('confirm_password').value;
            
            if(password.length < 6) {
                e.preventDefault();
                alert('Password must be at least 6 characters long!');
                return false;
            }
            
            if(password !== confirm) {
                e.preventDefault();
                alert('Passwords do not match!');
                return false;
            }
            
            return true;
        });
        
        // Auto-hide alerts
        setTimeout(() => {
            document.querySelectorAll('.alert').forEach(alert => {
                const bsAlert = bootstrap.Alert.getOrCreateInstance(alert);
                bsAlert.close();
            });
        }, 5000);
    </script>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>