<?php
session_start();
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/EmailService.php';

$error = '';
$success = '';
$page_title = 'Forgot Password — Interior Design';
$step = isset($_POST['step']) ? $_POST['step'] : 1;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($step == 1) {
        // Step 1: Get email
        $email = trim($_POST['email'] ?? '');

        if (!$email) {
            $error = 'Email is required';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Invalid email format';
        } else {
            // Check if user exists
            $stmt = $conn->prepare('SELECT id, name FROM users WHERE email = ?');
            $stmt->bind_param('s', $email);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows === 1) {
                $user = $result->fetch_assoc();
                
                // Generate OTP
                $otp = EmailService::generateOTP(6);
                
                // Save OTP - use SQL to add 10 minutes to database NOW()
                $otp_stmt = $conn->prepare('INSERT INTO otp_verification (email, otp_code, purpose, expires_at) VALUES (?, ?, ?, DATE_ADD(NOW(), INTERVAL 10 MINUTE))');
                $purpose = 'password_reset';
                $otp_stmt->bind_param('sss', $email, $otp, $purpose);
                
                if ($otp_stmt->execute()) {
                    // Send OTP email
                    if (EmailService::sendEmailVerificationOTP($email, $user['name'], $otp)) {
                        $_SESSION['reset_email'] = $email;
                        $success = 'OTP sent to your email! Please verify to reset your password.';
                        $step = 2;
                    } else {
                        $error = 'Failed to send OTP. Please try again.';
                    }
                } else {
                    $error = 'Error generating OTP. Please try again.';
                }
                $otp_stmt->close();
            } else {
                $error = 'Email not found. Please register first.';
            }
            $stmt->close();
        }
    } elseif ($step == 2) {
        // Step 2: Verify OTP
        $otp_entered = trim($_POST['otp'] ?? '');
        $email = $_SESSION['reset_email'] ?? '';

        if (!$otp_entered) {
            $error = 'Please enter the OTP';
        } else {
            // Clean up the entered OTP - remove all whitespace
            $otp_entered = preg_replace('/\s+/', '', $otp_entered);
            
            // Verify OTP
            $otp_stmt = $conn->prepare('SELECT id, otp_code FROM otp_verification WHERE email = ? AND purpose = ? AND expires_at > NOW()');
            $purpose = 'password_reset';
            $otp_stmt->bind_param('ss', $email, $purpose);
            $otp_stmt->execute();
            $otp_result = $otp_stmt->get_result();

            $otp_found = false;
            if ($otp_result->num_rows > 0) {
                // Check OTP manually in case of whitespace issues
                while ($row = $otp_result->fetch_assoc()) {
                    $stored_otp = trim($row['otp_code']);
                    if ($otp_entered === $stored_otp) {
                        $otp_found = true;
                        break;
                    }
                }
            }

            if ($otp_found) {
                $_SESSION['reset_verified'] = true;
                $success = 'OTP verified! Now you can reset your password.';
                $step = 3;
            } else {
                $error = 'Invalid or expired OTP. Please try again.';
            }
            $otp_stmt->close();
        }
    } elseif ($step == 3) {
        // Step 3: Reset password
        $new_password = $_POST['new_password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';
        $email = $_SESSION['reset_email'] ?? '';

        if (!$new_password || !$confirm_password) {
            $error = 'All fields are required';
        } elseif (strlen($new_password) < 6) {
            $error = 'Password must be at least 6 characters';
        } elseif ($new_password !== $confirm_password) {
            $error = 'Passwords do not match';
        } else {
            // Update password
            $password_hash = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare('UPDATE users SET password = ?, password_changed_at = NOW() WHERE email = ?');
            $stmt->bind_param('ss', $password_hash, $email);

            if ($stmt->execute()) {
                // Clear session
                unset($_SESSION['reset_email']);
                unset($_SESSION['reset_verified']);
                $success = 'Password reset successfully! You can now login with your new password.';
                
                // Redirect after 2 seconds
                echo "<script>setTimeout(() => { window.location.href = 'login.php'; }, 2000);</script>";
            } else {
                $error = 'Failed to reset password. Please try again.';
            }
            $stmt->close();
        }
    }
}

include 'header.php';
?>

<style>
    .main-auth-content {
        flex: 1;
        background: linear-gradient(135deg, #1a1a1a 0%, #2d2416 50%, #3d2817 100%);
        min-height: calc(100vh - 300px);
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        overflow: hidden;
    }
    .main-auth-content::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -50%;
        width: 100%;
        height: 100%;
        background: radial-gradient(circle, rgba(212,165,116,0.1) 0%, transparent 70%);
        animation: float 20s ease-in-out infinite;
        pointer-events: none;
    }
    @keyframes float {
        0%, 100% { transform: translate(0, 0); }
        50% { transform: translate(50px, 50px); }
    }
    .reset-wrapper {
        width: 100%;
        max-width: 500px;
        padding: 20px;
        position: relative;
        z-index: 1;
    }
    .reset-container {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);
        border-radius: 15px;
        box-shadow: 0 20px 60px rgba(212, 165, 116, 0.2), 0 0 1px rgba(212, 165, 116, 0.5);
        padding: 50px 40px;
        border: 1px solid rgba(212, 165, 116, 0.3);
    }
    .reset-header {
        text-align: center;
        margin-bottom: 35px;
    }
    .reset-header .logo {
        font-size: 32px;
        font-weight: 700;
        color: #D4A574;
        margin-bottom: 15px;
        letter-spacing: 1px;
    }
    .reset-header h2 {
        color: #1a1a1a;
        font-weight: 700;
        font-size: 28px;
        margin-bottom: 10px;
    }
    .reset-header p {
        color: #999;
        font-size: 14px;
        font-weight: 500;
    }
    .form-group {
        margin-bottom: 20px;
    }
    .form-group label {
        display: block;
        color: #333;
        font-size: 13px;
        font-weight: 600;
        margin-bottom: 7px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    .form-control {
        width: 100%;
        height: 48px;
        border: 2px solid #e0e0e0;
        border-radius: 8px;
        padding: 12px 16px;
        font-size: 14px;
        font-family: 'DM Sans', sans-serif;
        transition: all 0.3s ease;
        background: #f9f9f9;
    }
    .form-control:focus {
        outline: none;
        border-color: #D4A574;
        background: white;
        box-shadow: 0 0 0 3px rgba(212, 165, 116, 0.1);
    }
    .btn-reset {
        width: 100%;
        height: 50px;
        background: linear-gradient(135deg, #D4A574 0%, #b8905a 100%);
        color: white;
        border: none;
        border-radius: 8px;
        font-weight: 700;
        font-size: 16px;
        cursor: pointer;
        transition: all 0.3s ease;
        text-transform: uppercase;
        letter-spacing: 1px;
        margin-bottom: 15px;
        box-shadow: 0 10px 30px rgba(212, 165, 116, 0.3);
    }
    .btn-reset:hover {
        transform: translateY(-2px);
        box-shadow: 0 15px 40px rgba(212, 165, 116, 0.4);
    }
    .alert {
        margin-bottom: 20px;
        padding: 14px 16px;
        border-radius: 8px;
        font-size: 14px;
        border-left: 4px solid #dc3545;
    }
    .alert-danger {
        background-color: #fff5f5;
        color: #721c24;
        border-left-color: #dc3545;
    }
    .alert-success {
        background-color: #f0fdf4;
        color: #155724;
        border-left-color: #28a745;
    }
    .back-link {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 30px;
        color: #D4A574;
        text-decoration: none;
        font-weight: 600;
        font-size: 14px;
        transition: all 0.3s ease;
    }
    .back-link:hover {
        gap: 12px;
        color: #b8905a;
    }
    .step-indicator {
        display: flex;
        gap: 10px;
        margin-bottom: 30px;
    }
    .step-item {
        flex: 1;
        height: 4px;
        background: #e0e0e0;
        border-radius: 2px;
    }
    .step-item.active {
        background: linear-gradient(135deg, #D4A574 0%, #b8905a 100%);
    }
</style>

<div class="main-auth-content">
    <div class="reset-wrapper">
        <a href="login.php" class="back-link"><i class="fas fa-arrow-left"></i> Back to Login</a>
        
        <div class="reset-container">
            <div class="reset-header">
                <div class="logo">FAREN</div>
                <h2><?php echo $step == 1 ? 'Forgot Password' : ($step == 2 ? 'Verify OTP' : 'Reset Password'); ?></h2>
                <p><?php echo $step == 1 ? 'Enter your email to reset password' : ($step == 2 ? 'Enter the code sent to your email' : 'Create a new password'); ?></p>
            </div>

            <div class="step-indicator">
                <div class="step-item <?php echo $step >= 1 ? 'active' : ''; ?>"></div>
                <div class="step-item <?php echo $step >= 2 ? 'active' : ''; ?>"></div>
                <div class="step-item <?php echo $step >= 3 ? 'active' : ''; ?>"></div>
            </div>

            <?php if ($error): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success); ?>
                </div>
            <?php endif; ?>

            <?php if ($step == 1): ?>
                <form method="POST" action="">
                    <input type="hidden" name="step" value="1">
                    
                    <div class="form-group">
                        <label for="email"><i class="fas fa-envelope"></i> Email Address</label>
                        <input type="email" id="email" class="form-control" name="email" placeholder="your@email.com" required>
                    </div>

                    <button type="submit" class="btn-reset">Send Reset Code</button>
                </form>
            <?php elseif ($step == 2): ?>
                <form method="POST" action="">
                    <input type="hidden" name="step" value="2">
                    
                    <div style="background: #f0fdf4; padding: 15px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #28a745;">
                        <p style="margin: 0; color: #155724; font-size: 13px;">
                            <i class="fas fa-info-circle"></i> Check your email for the 6-digit code
                        </p>
                    </div>

                    <div class="form-group">
                        <label for="otp"><i class="fas fa-key"></i> Enter OTP Code</label>
                        <input type="text" id="otp" class="form-control" name="otp" placeholder="000000" maxlength="6" pattern="[0-9]{6}" required>
                    </div>

                    <button type="submit" class="btn-reset">Verify Code</button>
                </form>
            <?php elseif ($step == 3): ?>
                <form method="POST" action="">
                    <input type="hidden" name="step" value="3">
                    
                    <div class="form-group">
                        <label for="new_password"><i class="fas fa-lock"></i> New Password</label>
                        <input type="password" id="new_password" class="form-control" name="new_password" placeholder="Min 6 characters" required>
                    </div>

                    <div class="form-group">
                        <label for="confirm_password"><i class="fas fa-lock"></i> Confirm Password</label>
                        <input type="password" id="confirm_password" class="form-control" name="confirm_password" placeholder="••••••••" required>
                    </div>

                    <button type="submit" class="btn-reset">Reset Password</button>
                </form>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
