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

// Redirect if already logged in
if (isset($_SESSION['user_id'])) {
    header('Location: dashboard.php');
    exit;
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($step == 1) {
        // Step 1: Collect user info and send OTP
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';

        // Validation
        if (!$name || !$email || !$phone || !$password || !$confirm_password) {
            $error = 'All fields are required';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Invalid email format';
        } elseif (strlen($phone) < 10) {
            $error = 'Phone number must be at least 10 digits';
        } 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 already registered';
            } else {
                // 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 = 'email_verification';
                $otp_stmt->bind_param('sss', $email, $otp, $purpose);
                
                if ($otp_stmt->execute()) {
                    // Send OTP email
                    if (EmailService::sendEmailVerificationOTP($email, $name, $otp)) {
                        // Store data in session for step 2
                        $_SESSION['reg_name'] = $name;
                        $_SESSION['reg_email'] = $email;
                        $_SESSION['reg_phone'] = $phone;
                        $_SESSION['reg_password'] = $password;
                        
                        $success = 'OTP sent to your email! Please verify to complete registration.';
                        $step = 2;
                    } else {
                        $error = 'Failed to send OTP. Please try again.';
                    }
                } else {
                    $error = 'Error generating OTP. Please try again.';
                }
                $otp_stmt->close();
            }
            $stmt->close();
        }
    } elseif ($step == 2) {
        // Step 2: Verify OTP and create account
        $otp_entered = trim($_POST['otp'] ?? '');
        $email = $_SESSION['reg_email'] ?? '';
        
        if (!$otp_entered) {
            $error = 'Please enter the OTP';
            $step = 2;
        } else {
            // Debug: Log what we're checking
            error_log("OTP Verification - Email: $email, OTP Entered: '$otp_entered'");
            
            // Clean up the entered OTP - remove all whitespace
            $otp_entered = preg_replace('/\s+/', '', $otp_entered);
            error_log("OTP After cleaning: '$otp_entered'");
            
            // Verify OTP - simplified query
            $otp_stmt = $conn->prepare('SELECT id, otp_code FROM otp_verification WHERE email = ? AND purpose = ? AND expires_at > NOW()');
            $purpose = 'email_verification';
            $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']);
                    error_log("Comparing '$otp_entered' with stored '$stored_otp'");
                    if ($otp_entered === $stored_otp) {
                        $otp_found = true;
                        break;
                    }
                }
            }

            if ($otp_found) {
                // OTP verified, create account
                $name = $_SESSION['reg_name'];
                $phone = $_SESSION['reg_phone'];
                $password = $_SESSION['reg_password'];
                $password_hash = password_hash($password, PASSWORD_DEFAULT);
                $email_verified = 1;
                $verified_at = date('Y-m-d H:i:s');

                // Insert user with only columns that exist in users table
                $stmt = $conn->prepare('INSERT INTO users (name, email, phone, password, email_verified, created_at) VALUES (?, ?, ?, ?, ?, NOW())');
                $stmt->bind_param('ssssi', $name, $email, $phone, $password_hash, $email_verified);

                if ($stmt->execute()) {
                    // Clear session data
                    unset($_SESSION['reg_name']);
                    unset($_SESSION['reg_email']);
                    unset($_SESSION['reg_phone']);
                    unset($_SESSION['reg_password']);
                    
                    $success = 'Registration successful! Redirecting to login...';
                    echo "<script>setTimeout(() => { window.location.href = 'login.php?success=registered'; }, 2000);</script>";
                } else {
                    $error = 'Failed to create account. Please try again.';
                    error_log("Registration insert error: " . $stmt->error);
                    $step = 2;
                }
                $stmt->close();
            } else {
                $error = 'Invalid or expired OTP. Please try again.';
                $step = 2;
            }
            $otp_stmt->close();
        }
    }
}

include 'header.php';
?>
    <style>
        * {
            box-sizing: border-box;
        }

        .main-auth-content {
            flex: 1;
            background: linear-gradient(135deg, #0f0f0f 0%, #1a1410 50%, #2a1f18 100%);
            min-height: calc(100vh - 300px);
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            overflow: hidden;
            padding: 20px;
        }

        .main-auth-content::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 100%;
            height: 100%;
            background: radial-gradient(circle at 80% 20%, rgba(212, 165, 116, 0.15) 0%, transparent 50%),
                        radial-gradient(circle at 20% 80%, rgba(169, 132, 94, 0.1) 0%, transparent 50%);
            animation: float 20s ease-in-out infinite;
            pointer-events: none;
        }

        @keyframes float {
            0%, 100% { transform: translate(0, 0); }
            50% { transform: translate(30px, 30px); }
        }

        .register-wrapper {
            width: 100%;
            max-width: 520px;
            padding: 15px;
            position: relative;
            z-index: 1;
        }

        .register-container {
            background: rgba(20, 16, 13, 0.85);
            backdrop-filter: blur(20px);
            border-radius: 50px;
            box-shadow: 0 25px 80px rgba(0, 0, 0, 0.4),
                        inset 0 1px 0 rgba(212, 165, 116, 0.2);
            padding: 45px 35px;
            border: 1px solid rgba(212, 165, 116, 0.15);
            position: relative;
        }

        .register-container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 1px;
            background: linear-gradient(90deg, 
                transparent 0%, 
                rgba(212, 165, 116, 0.3) 50%, 
                transparent 100%);
        }

        .register-header {
            text-align: center;
            margin-bottom: 35px;
        }

        .register-header .logo {
            font-size: 32px;
            font-weight: 800;
            background: linear-gradient(135deg, #D4A574 0%, #E8D5C4 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 15px;
            letter-spacing: 2px;
            text-transform: uppercase;
        }

        .register-header h2 {
            color: #f0f0f0;
            font-weight: 700;
            font-size: 28px;
            margin-bottom: 8px;
            letter-spacing: 0.5px;
        }

        .register-header p {
            color: #a8a8a8;
            font-size: 14px;
            font-weight: 400;
            margin: 0;
        }

        .form-group {
            margin-bottom: 22px;
        }

        .form-group label {
            display: block;
            color: #d0d0d0;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 8px;
            text-transform: uppercase;
            letter-spacing: 0.8px;
        }

        .form-control {
            width: 100%;
            height: 50px;
            border: 2px solid rgba(212, 165, 116, 0.2);
            border-radius: 10px;
            padding: 12px 18px;
            font-size: 15px;
            font-family: 'DM Sans', -apple-system, BlinkMacSystemFont, sans-serif;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            background: rgba(255, 255, 255, 0.05);
            color: #f0f0f0;
        }

        .form-control:focus {
            outline: none;
            border-color: #D4A574;
            background: rgba(212, 165, 116, 0.08);
            box-shadow: 0 0 0 4px rgba(212, 165, 116, 0.1),
                        inset 0 1px 2px rgba(0, 0, 0, 0.1);
        }

        .form-control::placeholder {
            color: #666;
        }

        .btn-register {
            width: 100%;
            height: 52px;
            background: linear-gradient(135deg, #D4A574 0%, #c29860 100%);
            color: #1a1a1a;
            border: none;
            border-radius: 10px;
            font-weight: 700;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            text-transform: uppercase;
            letter-spacing: 1.2px;
            margin-bottom: 12px;
            margin-top: 8px;
            box-shadow: 0 15px 40px rgba(212, 165, 116, 0.25);
            position: relative;
            overflow: hidden;
        }

        .btn-register::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.2);
            transition: left 0.5s ease;
        }

        .btn-register:active {
            transform: translateY(-1px);
            box-shadow: 0 10px 30px rgba(212, 165, 116, 0.35);
        }

        .alert {
            margin-bottom: 20px;
            padding: 14px 16px;
            border-radius: 10px;
            font-size: 13px;
            border-left: 4px solid;
            background: rgba(255, 255, 255, 0.05);
            backdrop-filter: blur(10px);
        }

        .alert-danger {
            background-color: rgba(220, 53, 69, 0.1);
            color: #ff8a8a;
            border-left-color: #dc3545;
        }

        .alert-success {
            background-color: rgba(40, 167, 69, 0.1);
            color: #66ff99;
            border-left-color: #28a745;
        }

        .alert-success a {
            color: #66ff99;
            font-weight: 700;
            text-decoration: none;
        }

        .alert-success a:hover {
            text-decoration: underline;
        }

        .divider {
            text-align: center;
            margin: 28px 0;
            position: relative;
            color: #666;
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .divider::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 1px;
            background: linear-gradient(90deg, 
                transparent 0%, 
                rgba(212, 165, 116, 0.2) 50%, 
                transparent 100%);
        }

        .divider span {
            background: rgba(20, 16, 13, 0.85);
            padding: 0 12px;
            position: relative;
        }

        .footer-text {
            text-align: center;
            color: #999;
            font-size: 14px;
        }

        .footer-text a {
            color: #D4A574;
            text-decoration: none;
            font-weight: 700;
            transition: all 0.3s ease;
        }

        .footer-text a:hover {
            color: #E8D5C4;
            text-decoration: underline;
        }

        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 30px;
            color: #D4A574;
            text-decoration: none;
            font-weight: 600;
            font-size: 13px;
            transition: all 0.3s ease;
            padding: 8px 0;
        }

        .back-link:active {
            gap: 10px;
            color: #E8D5C4;
        }

        .back-link i {
            font-size: 15px;
        }

        .step-indicator {
            display: flex;
            gap: 8px;
            margin-bottom: 28px;
        }

        .step-item {
            flex: 1;
            height: 3px;
            background: rgba(212, 165, 116, 0.15);
            border-radius: 2px;
            transition: all 0.4s ease;
        }

        .step-item.active {
            background: linear-gradient(90deg, #D4A574 0%, #E8D5C4 100%);
            box-shadow: 0 0 10px rgba(212, 165, 116, 0.4);
        }

        /* Mobile Styles (320px - 480px) */
        @media (max-width: 480px) {
            .main-auth-content {
                min-height: 100vh;
                padding: 10px;
            }

            .register-wrapper {
                padding: 10px;
            }

            .register-container {
                padding: 35px 22px;
                border-radius: 16px;
            }

            .register-header {
                margin-bottom: 28px;
            }

            .register-header .logo {
                font-size: 26px;
                margin-bottom: 12px;
                letter-spacing: 1.5px;
            }

            .register-header h2 {
                font-size: 22px;
                margin-bottom: 6px;
            }

            .register-header p {
                font-size: 12px;
            }

            .form-group {
                margin-bottom: 18px;
            }

            .form-group label {
                font-size: 11px;
                margin-bottom: 6px;
                letter-spacing: 0.6px;
            }

            .form-control {
                height: 45px;
                padding: 10px 14px;
                font-size: 16px;
                border-radius: 8px;
            }

            .btn-register {
                height: 48px;
                font-size: 14px;
                margin-bottom: 10px;
                margin-top: 6px;
                letter-spacing: 1px;
            }

            .alert {
                padding: 11px 13px;
                font-size: 12px;
                margin-bottom: 15px;
            }

            .divider {
                margin: 22px 0;
                font-size: 11px;
            }

            .footer-text {
                font-size: 12px;
            }

            .back-link {
                margin-bottom: 22px;
                font-size: 12px;
            }

            .step-indicator {
                gap: 6px;
                margin-bottom: 22px;
            }

            .step-item {
                height: 2px;
            }

            .main-auth-content::before {
                display: none;
            }
        }

        /* Tablet Styles (481px - 768px) */
        @media (min-width: 481px) and (max-width: 768px) {
            .main-auth-content {
                padding: 15px;
            }

            .register-wrapper {
                max-width: 500px;
                padding: 12px;
            }

            .register-container {
                padding: 42px 32px;
            }

            .register-header .logo {
                font-size: 28px;
                margin-bottom: 12px;
            }

            .register-header h2 {
                font-size: 24px;
                margin-bottom: 8px;
            }

            .register-header p {
                font-size: 13px;
            }

            .form-control {
                font-size: 15px;
                height: 48px;
            }

            .btn-register {
                font-size: 15px;
                height: 50px;
            }

            .alert {
                font-size: 13px;
            }
        }

        /* Desktop Styles (769px+) */
        @media (min-width: 769px) {
            .btn-register:hover {
                transform: translateY(-2px);
                box-shadow: 0 20px 50px rgba(212, 165, 116, 0.35);
            }

            .back-link:hover {
                gap: 12px;
                color: #E8D5C4;
            }
        }

        /* Extra Large Screens (1024px+) */
        @media (min-width: 1024px) {
            .register-container {
                padding: 20px 40px;
            }

            .register-header .logo {
                font-size: 36px;
                margin-bottom: 18px;
            }

            .register-header h2 {
                font-size: 32px;
                margin-bottom: 10px;
            }

            .register-header p {
                font-size: 15px;
            }
        }

        /* Touch Device Optimizations */
        @media (hover: none) and (pointer: coarse) {
            .form-control {
                font-size: 16px;
                height: 50px;
            }

            .btn-register {
                height: 54px;
                font-size: 15px;
            }

            .back-link,
            .footer-text a {
                padding: 12px 0;
                min-height: 44px;
                display: flex;
                align-items: center;
            }
        }

        /* Landscape Mobile */
        @media (max-height: 600px) and (max-width: 768px) {
            .register-wrapper {
                max-height: none;
            }

            .register-container {
                padding: 28px 22px;
            }

            .register-header {
                margin-bottom: 15px;
            }

            .register-header h2 {
                margin-bottom: 4px;
                font-size: 20px;
            }

            .form-group {
                margin-bottom: 14px;
            }

            .step-indicator {
                margin-bottom: 15px;
            }
        }

        /* Scrollbar Styling */
        .register-wrapper::-webkit-scrollbar {
            width: 6px;
        }

        .register-wrapper::-webkit-scrollbar-track {
            background: rgba(212, 165, 116, 0.05);
        }

        .register-wrapper::-webkit-scrollbar-thumb {
            background: rgba(212, 165, 116, 0.2);
            border-radius: 3px;
        }

        .register-wrapper::-webkit-scrollbar-thumb:hover {
            background: rgba(212, 165, 116, 0.3);
        }
    </style>
</head>
<body>
    <div class="main-auth-content">
        <div class="register-wrapper">
        <a href="../index.php" class="back-link"><i class="fas fa-arrow-left"></i> Back</a>
        
        <div class="register-container">
            <div class="register-header">
                <div class="logo">FAREN</div>
                <h2><?php echo $step == 1 ? 'Create Account' : 'Verify Email'; ?></h2>
                <p><?php echo $step == 1 ? 'Join our exclusive community' : 'Enter the code sent to your email'; ?></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>

            <?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 $success; ?>
                </div>
            <?php endif; ?>

            <?php if ($step == 1): ?>
                <form method="POST" action="">
                    <input type="hidden" name="step" value="1">
                    
                    <div class="form-group">
                        <div style="background: linear-gradient(135deg, #E8D5C4 0%, #F0E6D8 100%); padding: 12px 16px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #D4A574; display: flex; align-items: center; gap: 10px;">
                            <i class="fas fa-check-circle" style="color: #D4A574; font-size: 16px;"></i>
                            <span style="color: #333; font-size: 14px; font-weight: 500; margin: 0;">Registering as: <strong>Customer</strong></span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="name"><i class="fas fa-user"></i> Full Name</label>
                        <input type="text" id="name" class="form-control" name="name" placeholder="John Doe" required>
                    </div>

                    <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>

                    <div class="form-group">
                        <label for="phone"><i class="fas fa-phone"></i> Phone Number</label>
                        <input type="tel" id="phone" class="form-control" name="phone" placeholder="+1 (555) 000-0000" required>
                    </div>

                    <div class="form-group">
                        <label for="password"><i class="fas fa-lock"></i> Password</label>
                        <input type="password" id="password" class="form-control" name="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-register">Continue to Verification</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> A 6-digit code has been sent to <strong><?php echo htmlspecialchars($_SESSION['reg_email']); ?></strong>
                        </p>
                    </div>

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

                    <button type="submit" class="btn-register">Verify & Create Account</button>
                </form>

                <div class="divider"><span>DIDN'T GET THE CODE?</span></div>
                <div class="footer-text">
                    <a href="register.php">Start Over</a> or <a href="login.php">Login</a>
                </div>
            <?php endif; ?>

            <?php if ($step == 1): ?>
                <div class="divider"><span>ALREADY A MEMBER?</span></div>
                <div class="footer-text">
                    Sign in to your account <a href="login.php">Login here</a>
                </div>
            <?php endif; ?>
        </div>
        </div>
    </div>

<?php
include 'footer.php';
?>
<link rel="stylesheet" href="realtime-verification.css">
<script src="realtime-verification.js"></script>

<script>
    RealtimeVerification.init('#myForm');
</script>