<?php
require_once 'config.php';
require_once 'otp_handler.php';
session_start();

// Redirect if not in reset flow
if (!isset($_SESSION['reset_email'])) {
    header('Location: forgot_password.php');
    exit();
}

$error = '';
$success = '';
$step = $_SESSION['reset_step'] ?? 1;
$email = $_SESSION['reset_email'] ?? '';

// Step 1: Verify OTP
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $step == 1) {
    $otp = trim($_POST['otp'] ?? '');
    
    if (empty($otp)) {
        $error = 'Please enter the OTP code.';
    } else {
        $otpHandler = new OTPHandler($conn);
        
        if ($otpHandler->verifyOTP($email, $otp, 'password_reset')) {
            $_SESSION['reset_step'] = 2;
            $step = 2;
            $success = 'OTP verified! Please enter your new password.';
        } else {
            $error = 'Invalid or expired OTP. Please try again.';
        }
    }
}

// Step 2: Reset password
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $step == 2) {
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    if (empty($new_password) || empty($confirm_password)) {
        $error = 'Please enter both password fields.';
    } elseif (strlen($new_password) < 6) {
        $error = 'Password must be at least 6 characters.';
    } elseif ($new_password !== $confirm_password) {
        $error = 'Passwords do not match.';
    } else {
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
        
        $stmt = $conn->prepare('UPDATE users SET password = ? WHERE email = ?');
        $stmt->bind_param('ss', $hashed_password, $email);
        
        if ($stmt->execute()) {
            // Clear session
            unset($_SESSION['reset_email']);
            unset($_SESSION['reset_step']);
            
            $success = 'Password reset successfully! Redirecting to login...';
            echo '<meta http-equiv="refresh" content="2; url=login.php">';
        } else {
            $error = 'Failed to reset password. Please try again.';
        }
        $stmt->close();
    }
}

// Handle resend OTP
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['resend_otp']) && $step == 1) {
    $otpHandler = new OTPHandler($conn);
    
    if ($otpHandler->resendOTP($email, 'password_reset')) {
        $success = 'OTP resent to your email!';
    } else {
        $error = 'Failed to resend OTP. Please try again.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset Password - Cleaning Service</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        .reset-page-wrapper { min-height: calc(100vh - 400px); display: flex; align-items: center; justify-content: center; padding: 40px 20px; background: #f8f9fa; }
        .reset-form-container { width: 100%; max-width: 450px; background: white; padding: 40px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1); }
        .reset-form-header { text-align: center; margin-bottom: 30px; }
        .reset-form-header h2 { font-size: 28px; color: #063A41; margin-bottom: 10px; }
        .reset-form-header p { color: #5E5C78; font-size: 14px; }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 8px; color: #063A41; font-weight: 500; }
        .form-group input { width: 100%; padding: 12px 14px; border: 1px solid #CDD5D6; border-radius: 8px; font-size: 14px; }
        .form-group input:focus { outline: none; border-color: #0984e3; box-shadow: 0 0 0 3px rgba(9, 132, 227, 0.1); }
        .form-submit-btn { width: 100%; padding: 14px; background: linear-gradient(85deg, #FF9800 0%, #FF6B35 72%); color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; margin-top: 10px; }
        .form-submit-btn:hover { opacity: 0.9; }
        .resend-btn { width: 100%; padding: 10px; background: #f0f0f0; color: #FF9800; border: 1px solid #FF9800; border-radius: 8px; font-weight: 600; cursor: pointer; margin-top: 10px; }
        .resend-btn:hover { background: #ffe8d6; }
        .reset-links { margin-top: 20px; text-align: center; font-size: 14px; }
        .reset-links a { color: #0984e3; text-decoration: none; font-weight: 600; }
        .error { background-color: #fee; color: #c33; padding: 12px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #c33; }
        .success { background-color: #efe; color: #093; padding: 12px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #093; }
        .step-indicator { text-align: center; margin-bottom: 30px; }
        .step-indicator span { font-size: 14px; color: #5E5C78; font-weight: 500; }
        .step-indicator .active { color: #FF9800; font-weight: 600; }
        .otp-input { font-size: 18px; text-align: center; letter-spacing: 10px; }
        .countdown { text-align: center; color: #666; margin-top: 15px; font-size: 14px; }
        .countdown-timer { color: #FF9800; font-weight: bold; font-size: 16px; }
    </style>
</head>
<body>
    
    <?php include 'header.php'; ?>
    
    <div class="reset-page-wrapper">
        <div class="reset-form-container">
            <div class="reset-form-header">
                <h2><?php echo $step == 1 ? 'Verify Your Email 📧' : 'New Password 🔑'; ?></h2>
                <p><?php echo $step == 1 ? 'Enter the OTP code sent to your email' : 'Create a new password for your account'; ?></p>
            </div>

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

            <?php if ($success): ?>
                <div class="success"><?php echo htmlspecialchars($success); ?></div>
            <?php endif; ?>

            <!-- STEP 1: OTP Verification -->
            <?php if ($step == 1): ?>
            <form method="POST" action="">
                <div class="step-indicator">
                    <span class="active">Step 1 (OTP Verification)</span> → <span>Step 2</span>
                </div>

                <div class="form-group">
                    <label for="otp">Enter OTP Code</label>
                    <input type="text" id="otp" name="otp" class="otp-input" placeholder="000000" maxlength="6" pattern="[0-9]{6}" required>
                    <p style="color: #666; font-size: 13px; margin-top: 8px;">A 6-digit code has been sent to <strong><?php echo htmlspecialchars($email); ?></strong></p>
                </div>

                <div class="countdown">
                    ⏱️ Code expires in <span class="countdown-timer">10:00</span>
                </div>

                <button type="submit" class="form-submit-btn">Verify OTP</button>

                <button type="submit" name="resend_otp" value="1" class="resend-btn">Didn't receive OTP? Resend</button>

                <div class="reset-links">
                    <p><a href="forgot_password.php">Try another email</a></p>
                </div>
            </form>

            <!-- STEP 2: New Password -->
            <?php else: ?>
            <form method="POST" action="">
                <div class="step-indicator">
                    <span class="active">Step 1 ✓</span> → <span>Step 2 (Password)</span>
                </div>

                <div class="form-group">
                    <label for="new_password">New Password</label>
                    <input type="password" id="new_password" name="new_password" placeholder="Create a strong password" required>
                    <small style="color: #666;">At least 6 characters</small>
                </div>

                <div class="form-group">
                    <label for="confirm_password">Confirm Password</label>
                    <input type="password" id="confirm_password" name="confirm_password" placeholder="Confirm your password" required>
                </div>

                <button type="submit" class="form-submit-btn">Reset Password</button>

                <div class="reset-links">
                    <p><a href="login.php">Back to Login</a></p>
                </div>
            </form>

            <script>
                // Countdown timer
                let timeLeft = 600; // 10 minutes in seconds
                function updateTimer() {
                    const minutes = Math.floor(timeLeft / 60);
                    const seconds = timeLeft % 60;
                    document.querySelector('.countdown-timer').textContent = 
                        String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0');
                    
                    if (timeLeft > 0) {
                        timeLeft--;
                        setTimeout(updateTimer, 1000);
                    }
                }
                updateTimer();

                // Auto-format OTP input
                document.getElementById('otp').addEventListener('input', function(e) {
                    this.value = this.value.replace(/[^0-9]/g, '').slice(0, 6);
                });
            </script>
            <?php endif; ?>
        </div>
    </div>

    <?php include 'footer.php'; ?>
    <script src="assets/js/vendor/jquery-3.7.1.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
</body>
</html>
