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

// If user is already logged in, redirect to dashboard
if (isset($_SESSION['user_id'])) {
    header('Location: customer-dashboard.php');
    exit();
}

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

// Step 1: User submits registration form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $step == 1) {
    $fullname = trim($_POST['fullname'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    // Validation
    if (empty($fullname) || empty($email) || empty($phone) || empty($password) || empty($confirm_password)) {
        $error = 'All fields are required.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Invalid email format.';
    } elseif (strlen($password) < 6) {
        $error = 'Password must be at least 6 characters.';
    } elseif ($password !== $confirm_password) {
        $error = 'Passwords do not match.';
    } else {
        // Check if email already exists
        $stmt = $conn->prepare('SELECT id FROM users WHERE email = ?');
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $error = 'Email is already registered.';
        } else {
            // Store registration data in session
            $_SESSION['reg_fullname'] = $fullname;
            $_SESSION['reg_email'] = $email;
            $_SESSION['reg_phone'] = $phone;
            $_SESSION['reg_password'] = $password;
            
            // Generate and send OTP
            $otpHandler = new OTPHandler($conn);
            $otp = $otpHandler->generateOTP();
            
            if ($otpHandler->sendOTPEmail($email, $otp, 'registration') && $otpHandler->storeOTP($email, $otp, 'registration')) {
                $_SESSION['registration_step'] = 2;
                $success = 'OTP sent to your email! Please check your inbox.';
                $step = 2;
            } else {
                $error = 'Failed to send OTP. Please try again.';
            }
        }
        $stmt->close();
    }
}

// Step 2: User submits OTP
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $step == 2) {
    $otp = trim($_POST['otp'] ?? '');
    
    if (empty($otp)) {
        $error = 'Please enter the OTP code.';
    } else {
        $email = $_SESSION['reg_email'] ?? '';
        $otpHandler = new OTPHandler($conn);
        
        if ($otpHandler->verifyOTP($email, $otp, 'registration')) {
            // OTP verified, create user account
            $fullname = $_SESSION['reg_fullname'];
            $phone = $_SESSION['reg_phone'];
            $password = $_SESSION['reg_password'];
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            
            $stmt = $conn->prepare('INSERT INTO users (name, email, phone, password, user_type, status, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())');
            $user_type = 'customer';
            $status = 'active';
            $stmt->bind_param('ssssss', $fullname, $email, $phone, $hashed_password, $user_type, $status);
            
            if ($stmt->execute()) {
                // Clear session data
                unset($_SESSION['registration_step']);
                unset($_SESSION['reg_fullname']);
                unset($_SESSION['reg_email']);
                unset($_SESSION['reg_phone']);
                unset($_SESSION['reg_password']);
                
                $success = 'Registration successful! Redirecting to login...';
                echo '<meta http-equiv="refresh" content="2; url=login.php">';
            } else {
                $error = 'Failed to create account. Please try again.';
            }
            $stmt->close();
        } else {
            $error = 'Invalid or expired OTP. Please try again.';
        }
    }
}

// Handle OTP resend
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['resend_otp']) && $step == 2) {
    $email = $_SESSION['reg_email'] ?? '';
    $otpHandler = new OTPHandler($conn);
    
    if ($otpHandler->resendOTP($email, 'registration')) {
        $success = 'OTP resent to your email!';
    } else {
        $error = 'Failed to resend OTP. Please try again.';
    }
}
?><!doctype html>
<html class="no-js" lang="zxx">

<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Register - Cleaning Service</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="shortcut icon" href="assets/img/favicon.ico" type="image/x-icon">
    <link rel="icon" href="assets/img/favicon.ico" type="image/x-icon">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="">
    <link href="https://fonts.googleapis.com/css2?family=Fuzzy+Bubbles:wght@400;700&family=Poppins:wght@400;500;600;700;800&family=Rubik:ital,wght@0,300..900;1,300..900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/fontawesome.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        .register-page-wrapper { min-height: calc(100vh - 400px); display: flex; align-items: center; justify-content: center; padding: 40px 20px; background: #f8f9fa; }
        .register-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); }
        .register-form-header { text-align: center; margin-bottom: 30px; }
        .register-form-header h2 { font-size: 28px; color: #063A41; margin-bottom: 10px; }
        .register-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, #00b894 0%, #0984e3 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: #0984e3; border: 1px solid #0984e3; border-radius: 8px; font-weight: 600; cursor: pointer; margin-top: 10px; }
        .resend-btn:hover { background: #e8f4fd; }
        .register-links { margin-top: 20px; text-align: center; font-size: 14px; }
        .register-links p { color: #5E5C78; }
        .register-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: #0984e3; 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: #0984e3; font-weight: bold; font-size: 16px; }
    </style>
</head>

<body>
    
    <?php include 'header.php'; ?>
    <div class="register-page-wrapper">
        <div class="register-form-container">
            <div class="register-form-header">
                <h2><?php echo $step == 1 ? 'Join Us Today 🌟' : 'Verify Your Email 📧'; ?></h2>
                <p><?php echo $step == 1 ? 'Create your account and get started' : 'Enter the OTP sent to your email'; ?></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: Registration Form -->
            <?php if ($step == 1): ?>
            <form method="POST" action="">
                <div class="form-group">
                    <label for="fullname">Full Name</label>
                    <input type="text" id="fullname" name="fullname" placeholder="Enter your full name" required>
                </div>

                <div class="form-group">
                    <label for="email">Email Address</label>
                    <input type="email" id="email" name="email" placeholder="Enter your email" required>
                </div>

                <div class="form-group">
                    <label for="phone">Phone Number</label>
                    <input type="tel" id="phone" name="phone" placeholder="Enter your phone number" required>
                </div>

                <div class="form-group">
                    <label for="password">Password</label>
                    <input type="password" id="password" name="password" placeholder="Create a strong password" required>
                </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">Continue to Verification</button>

                <div class="register-links">
                    <p>Already have an account? <a href="login.php">Login here</a></p>
                </div>
            </form>

            <!-- STEP 2: OTP Verification -->
            <?php else: ?>
            <form method="POST" action="">
                <div class="step-indicator">
                    <span class="active">Step 1 ✓</span> → <span>Step 2 (OTP Verification)</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($_SESSION['reg_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 & Complete Registration</button>

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

                <div class="register-links">
                    <p><a href="register.php">Start Over</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>
    <script src="assets/js/main.js"></script>
</body>

</html>