<?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: ../index.php');
    exit;
}

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

// Check if user just registered
if (isset($_GET['success']) && $_GET['success'] === 'registered') {
    $success = 'Registration successful! Please sign in with your credentials.';
}

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($step == 1) {
        // Step 1: Email and password validation
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $user_role = 'customer'; // Customer only for this page

        if (!$email || !$password) {
            $error = 'Email and password are required';
        } else {
            // Check if user is customer
            $stmt = $conn->prepare('SELECT id, name, email, role, password, two_factor_enabled FROM users WHERE email = ? AND role = ?');
            $stmt->bind_param('ss', $email, $user_role);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows === 1) {
                $user = $result->fetch_assoc();
                if (password_verify($password, $user['password'])) {
                    // Password correct, check if 2FA enabled
                    if ($user['two_factor_enabled']) {
                        // Generate 2FA OTP
                        $otp = $email_service->generateOTP(6);
                        $expires = date('Y-m-d H:i:s', strtotime('+10 minutes'));
                        
                        // Save OTP
                        $otp_stmt = $conn->prepare('INSERT INTO otp_verification (email, otp_code, purpose, expires_at) VALUES (?, ?, ?, ?)');
                        $purpose = '2fa';
                        $otp_stmt->bind_param('ssss', $email, $otp, $purpose, $expires);
                        
                        if ($otp_stmt->execute()) {
                            // Send 2FA OTP email
                            $email_service->send2FAOTP($email, $user['name'], $otp);
                            
                            // Store user data in session temporarily
                            $_SESSION['login_user_id'] = $user['id'];
                            $_SESSION['login_user_name'] = $user['name'];
                            $_SESSION['login_user_email'] = $user['email'];
                            $_SESSION['login_user_role'] = $user['role'];
                            $_SESSION['login_email'] = $email;
                            
                            $success = '2FA code sent to your email! Enter it below.';
                            $step = 2;
                        } else {
                            $error = 'Failed to generate 2FA code. Please try again.';
                        }
                        $otp_stmt->close();
                    } else {
                        // Login successful without 2FA
                        $_SESSION['user_id'] = $user['id'];
                        $_SESSION['user_name'] = $user['name'];
                        $_SESSION['user_email'] = $user['email'];
                        $_SESSION['user_role'] = $user['role'];
                        
                        // Redirect based on user role (default)
                        $redirect_url = $user['role'] === 'admin' ? '../admin-dashboard.php' : '../index.php';
                        // Prefer `next` parameter when it's a safe, internal path
                        $next = isset($_GET['next']) ? trim($_GET['next']) : '';
                        $finalRedirect = $redirect_url;
                        if ($next) {
                            $n = $next;
                            if (strpos($n, '://') === false && strpos($n, '//') === false && preg_match('/^[\w\-\/\.\?\=\&%#]+$/', $n)) {
                                $finalRedirect = $n;
                            }
                        }
                        ?>
                        <script>
                            localStorage.setItem('userLoggedIn', 'true');
                            localStorage.setItem('userName', '<?php echo htmlspecialchars($user['name']); ?>');
                            localStorage.setItem('userRole', '<?php echo htmlspecialchars($user['role']); ?>');
                            window.location.href = '<?php echo htmlspecialchars($finalRedirect); ?>';
                        </script>
                        <?php
                        exit;
                    }
                } else {
                    $error = 'Invalid email or password';
                }
            } else {
                $error = 'Invalid email or password';
            }
            $stmt->close();
        }
    } elseif ($step == 2) {
        // Step 2: 2FA OTP verification
        $otp_entered = trim($_POST['otp'] ?? '');
        $email = $_SESSION['login_email'] ?? '';
        
        if (!$otp_entered) {
            $error = 'Please enter the 2FA code';
            $step = 2;
        } else {
            // Verify 2FA OTP
            $otp_stmt = $conn->prepare('SELECT id FROM otp_verification WHERE email = ? AND otp_code = ? AND purpose = ? AND expires_at > NOW() ORDER BY created_at DESC LIMIT 1');
            $purpose = '2fa';
            $otp_stmt->bind_param('sss', $email, $otp_entered, $purpose);
            $otp_stmt->execute();
            $otp_result = $otp_stmt->get_result();

            if ($otp_result->num_rows === 1) {
                // 2FA verified, complete login
                $_SESSION['user_id'] = $_SESSION['login_user_id'];
                $_SESSION['user_name'] = $_SESSION['login_user_name'];
                $_SESSION['user_email'] = $_SESSION['login_user_email'];
                $_SESSION['user_role'] = $_SESSION['login_user_role'];
                
                // Clear temporary session vars
                unset($_SESSION['login_user_id']);
                unset($_SESSION['login_user_name']);
                unset($_SESSION['login_user_email']);
                unset($_SESSION['login_user_role']);
                unset($_SESSION['login_email']);
                
                // Redirect based on user role (default)
                $redirect_url = $_SESSION['user_role'] === 'admin' ? '../admin-dashboard.php' : '../index.php';
                // Prefer `next` parameter when it's a safe, internal path
                $next = isset($_GET['next']) ? trim($_GET['next']) : '';
                $finalRedirect = $redirect_url;
                if ($next) {
                    $n = $next;
                    if (strpos($n, '://') === false && strpos($n, '//') === false && preg_match('/^[\w\-\/\.\?\=\&%#]+$/', $n)) {
                        $finalRedirect = $n;
                    }
                }
                ?>
                <script>
                    localStorage.setItem('userLoggedIn', 'true');
                    localStorage.setItem('userName', '<?php echo htmlspecialchars($_SESSION['user_name']); ?>');
                    localStorage.setItem('userRole', '<?php echo htmlspecialchars($_SESSION['user_role']); ?>');
                    window.location.href = '<?php echo htmlspecialchars($finalRedirect); ?>';
                </script>
                <?php
                exit;
            } else {
                $error = 'Invalid or expired 2FA code. Please try again.';
                $step = 2;
            }
            $otp_stmt->close();
        }
    }
}

?>

<?php include __DIR__ . '/../header-php.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); }
        }

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

        .login-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;
        }

        .login-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%);
        }

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

        .login-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;
        }

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

        .login-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: rgb(255 255 255);
            color: #000000;
        }

        .form-control:focus {
            color: #000000;
            outline: none;
            border-color: #D4A574;
            background: rgb(255 255 255);
            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: #000000;
        }

        .remember-section {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            font-size: 13px;
            flex-wrap: wrap;
            gap: 10px;
        }

        .remember-section input[type="checkbox"] {
            cursor: pointer;
            accent-color: #D4A574;
        }

        .remember-section label {
            margin: 0;
            cursor: pointer;
            color: #a8a8a8;
        }

        .forgot-link {
            color: #D4A574;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .forgot-link:hover {
            color: #E8D5C4;
        }

        .btn-login {
            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;
            box-shadow: 0 15px 40px rgba(212, 165, 116, 0.25);
            position: relative;
            overflow: hidden;
        }

        .btn-login::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-login: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;
        }

        .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;
        }

        .role-btn-admin,
        .role-btn-customer {
            flex: 1;
            min-width: 120px;
            padding: 14px 20px;
            border: 2px solid;
            border-radius: 10px;
            cursor: pointer;
            font-weight: 700;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            font-size: 14px;
            background: rgba(255, 255, 255, 0.05);
            color: #a8a8a8;
            border-color: rgba(212, 165, 116, 0.2);
        }

        .role-btn-admin.active,
        .role-btn-customer.active {
            background: linear-gradient(135deg, #D4A574 0%, #c29860 100%);
            color: #1a1a1a;
            border-color: #D4A574;
            box-shadow: 0 8px 25px rgba(212, 165, 116, 0.3);
            font-weight: 700;
        }

        .role-selector {
            display: flex;
            gap: 10px;
            margin-bottom: 25px;
            flex-wrap: wrap;
        }

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

            .login-wrapper {
                padding: 10px;
            }

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

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

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

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

            .login-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-login {
                height: 48px;
                font-size: 14px;
                margin-bottom: 10px;
                letter-spacing: 1px;
            }

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

            .remember-section {
                font-size: 12px;
                margin-bottom: 20px;
            }

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

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

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

            .role-btn-admin,
            .role-btn-customer {
                min-width: 110px;
                padding: 12px 16px;
                font-size: 13px;
            }

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

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

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

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

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

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

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

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

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

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

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

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

            .role-btn-admin:hover,
            .role-btn-customer:hover {
                border-color: #D4A574;
                background: rgba(212, 165, 116, 0.1);
            }

            .forgot-link:hover {
                text-decoration: underline;
            }
        }

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

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

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

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

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

            .btn-login {
                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) {
            .login-container {
                padding: 28px 22px;
            }

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

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

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

            .remember-section {
                margin-bottom: 15px;
            }
        }

        /* ========================================
           LIVE CHAT STYLES
           ======================================== */
        .chat-widget-container {
            position: fixed;
            bottom: 0;
            right: 0;
            z-index: 999;
            font-family: 'DM Sans', -apple-system, BlinkMacSystemFont, sans-serif;
        }

        /* Chat Icon Button */
        .chat-icon-button {
            width: clamp(50px, 12vw, 70px);
            height: clamp(50px, 12vw, 70px);
            border-radius: 50%;
            background: linear-gradient(135deg, #D4A574 0%, #c29860 100%);
            color: #fff;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: clamp(1.2rem, 5vw, 1.8rem);
            box-shadow: 0 4px 20px rgba(212, 165, 116, 0.4);
            transition: all 0.3s ease;
            margin: 1rem;
            position: relative;
        }

        .chat-icon-button:active {
            transform: scale(0.95);
            box-shadow: 0 2px 10px rgba(212, 165, 116, 0.3);
        }

        @media (hover: hover) {
            .chat-icon-button:hover {
                transform: scale(1.1);
                box-shadow: 0 8px 30px rgba(212, 165, 116, 0.5);
            }
        }

        .chat-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background: #ff4444;
            color: white;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
        }

        /* Chat Box */
        .chat-box {
            position: fixed;
            bottom: 90px;
            right: 1rem;
            width: clamp(280px, 90vw, 420px);
            height: clamp(400px, 80vh, 600px);
            background: rgba(20, 16, 13, 0.95);
            backdrop-filter: blur(20px);
            border: 1px solid rgba(212, 165, 116, 0.2);
            border-radius: 1.5rem;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
            display: flex;
            flex-direction: column;
            opacity: 0;
            visibility: hidden;
            transform: scale(0.8) translateY(20px);
            transition: all 0.3s ease;
            z-index: 1000;
        }

        .chat-box.active {
            opacity: 1;
            visibility: visible;
            transform: scale(1) translateY(0);
        }

        /* Chat Header */
        .chat-header {
            padding: 1.2rem;
            border-bottom: 1px solid rgba(212, 165, 116, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: linear-gradient(135deg, rgba(212, 165, 116, 0.1) 0%, rgba(169, 132, 94, 0.05) 100%);
            border-radius: 1.5rem 1.5rem 0 0;
        }

        .chat-header-title {
            color: #f0f0f0;
            font-size: clamp(0.9rem, 4vw, 1.1rem);
            font-weight: 700;
            margin: 0;
        }

        .chat-header-subtitle {
            color: #a8a8a8;
            font-size: 0.75rem;
            font-weight: 400;
        }

        .chat-close-btn {
            background: none;
            border: none;
            color: #a8a8a8;
            font-size: 1.5rem;
            cursor: pointer;
            transition: color 0.3s ease;
            padding: 0;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .chat-close-btn:active {
            color: #D4A574;
        }

        @media (hover: hover) {
            .chat-close-btn:hover {
                color: #D4A574;
            }
        }

        /* Chat Header Info */
        .chat-header-info {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .chat-header-avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: linear-gradient(135deg, #D4A574 0%, #b8834a 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 0.9rem;
            flex-shrink: 0;
        }

        /* Chat Messages Container */
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 1.2rem;
            display: flex;
            flex-direction: column;
            gap: 0.75rem;
            background: rgba(255, 255, 255, 0.02);
        }

        .chat-messages::-webkit-scrollbar {
            width: 6px;
        }

        .chat-messages::-webkit-scrollbar-track {
            background: transparent;
        }

        .chat-messages::-webkit-scrollbar-thumb {
            background: rgba(212, 165, 116, 0.3);
            border-radius: 3px;
        }

        .chat-messages::-webkit-scrollbar-thumb:hover {
            background: rgba(212, 165, 116, 0.5);
        }

        /* Chat Message */
        .chat-message {
            display: flex;
            gap: 0.5rem;
            animation: slideIn 0.3s ease forwards;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .chat-message.user {
            justify-content: flex-end;
        }

        .message-bubble {
            max-width: 75%;
            padding: 0.75rem 1rem;
            border-radius: 1rem;
            font-size: 0.85rem;
            line-height: 1.4;
            word-wrap: break-word;
        }

        .message-bubble.bot {
            background: rgba(212, 165, 116, 0.15);
            color: #e0e0e0;
            border-left: 3px solid #D4A574;
        }

        .message-bubble.user {
            background: linear-gradient(135deg, #D4A574 0%, #c29860 100%);
            color: #1a1a1a;
            font-weight: 600;
        }

        .chat-timestamp {
            font-size: 0.7rem;
            color: #777;
            margin-top: 0.25rem;
            text-align: right;
        }

        .chat-message.user .chat-timestamp {
            text-align: right;
        }

        /* Chat Input Area */
        .chat-input-area {
            padding: 1rem;
            border-top: 1px solid rgba(212, 165, 116, 0.1);
            display: flex;
            gap: 0.5rem;
            background: rgba(255, 255, 255, 0.02);
            border-radius: 0 0 1.5rem 1.5rem;
        }

        .chat-input {
            flex: 1;
            padding: 0.75rem 1rem;
            border: 2px solid rgba(212, 165, 116, 0.2);
            background: rgba(255, 255, 255, 0.9);
            color: #000;
            border-radius: 0.75rem;
            font-size: 0.9rem;
            font-family: inherit;
            transition: all 0.3s ease;
            min-height: 40px;
            resize: none;
        }

        .chat-input:focus {
            outline: none;
            border-color: #D4A574;
            box-shadow: 0 0 0 4px rgba(212, 165, 116, 0.1);
        }

        .chat-input::placeholder {
            color: #999;
        }

        .chat-send-btn {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, #D4A574 0%, #c29860 100%);
            color: #fff;
            border: none;
            border-radius: 0.75rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
            transition: all 0.3s ease;
        }

        .chat-send-btn:active {
            transform: scale(0.95);
        }

        @media (hover: hover) {
            .chat-send-btn:hover {
                transform: scale(1.05);
                box-shadow: 0 4px 15px rgba(212, 165, 116, 0.4);
            }
        }

        /* Welcome Message */
        .chat-welcome {
            text-align: center;
            color: #a8a8a8;
            padding: 2rem 1rem;
            font-size: 0.9rem;
        }

        .chat-welcome-icon {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: #D4A574;
        }

        /* Responsive Adjustments */
        @media (max-width: 480px) {
            .chat-box {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                width: 100% !important;
                height: 100% !important;
                max-width: 100vw;
                max-height: 100vh;
                border-radius: 0;
                border: none;
            }

            .chat-header {
                padding: 0.85rem 1rem;
                border-radius: 0;
            }

            .chat-messages {
                padding: 0.75rem;
            }

            .message-bubble {
                max-width: 88%;
                padding: 0.65rem 0.85rem;
                font-size: 0.82rem;
            }

            .chat-input-area {
                padding: 0.65rem 0.75rem;
            }

            .chat-close-btn {
                width: 36px;
                height: 36px;
            }
        }

        @media (min-width: 481px) and (max-width: 768px) {
            .chat-box {
                width: 350px;
                height: 500px;
                bottom: 85px;
            }
        }

        @media (min-width: 769px) {
            .chat-box {
                width: 420px;
                height: 600px;
                bottom: 90px;
            }
        }

        /* Print Styles */
        @media print {
            .chat-widget-container {
                display: none;
            }
        }
    </style>

    <div class="main-auth-content">
        <div class="login-wrapper">
            <a href="../index.php" class="back-link"><i class="fas fa-arrow-left"></i> Back</a>
            
            <div class="login-container">
                <div class="login-header">
                    <div class="logo">FAREN</div>
                    <h2>Welcome Back</h2>
                    <p>Sign in to your customer account</p>
                </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; ?>

                <form method="POST" action="">
                    <input type="hidden" name="step" value="<?php echo $step; ?>">
                    
                    <?php if ($step == 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>

                        <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="••••••••" required>
                        </div>

                        <div class="remember-section">
                            <label>
                                <input type="checkbox" name="remember"> Remember me
                            </label>
                            <a href="forgot-password.php" class="forgot-link">Forgot password?</a>
                        </div>

                        <button type="submit" class="btn-login">Sign In</button>
                    <?php elseif ($step == 2): ?>
                        <div style="background: rgba(40, 167, 69, 0.1); padding: 15px; border-radius: 10px; margin-bottom: 20px; border-left: 4px solid #28a745; backdrop-filter: blur(10px);">
                            <p style="margin: 0; color: #66ff99; font-size: 13px;">
                                <i class="fas fa-info-circle"></i> A 6-digit code has been sent to <strong><?php echo htmlspecialchars($_SESSION['login_email']); ?></strong>
                            </p>
                        </div>

                        <div class="form-group">
                            <label for="otp"><i class="fas fa-key"></i> Enter 2FA 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-login">Verify & Sign In</button>

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

                <script>
                    // No role selection needed - customer login only
                </script>

                <?php if ($step == 1): ?>
                    <div class="divider"><span>ADMIN ACCESS?</span></div>
                    <div class="footer-text">
                        Go to <a href="admin-login.php">Admin Login</a>
                    </div>
                <?php endif; ?>

                <?php if ($step == 1): ?>
                    <div class="divider"><span>NEW TO FAREN?</span></div>
                    <div class="footer-text">
                        Create an account <a href="register.php">Register now</a>
                    </div>
                <?php endif; ?>
            </div>
            <!-- Close login-container -->
        </div>
        <!-- Close login-wrapper -->
    </div>
    <!-- Close main-auth-content -->

    <!-- Live Chat Widget -->
    <div class="chat-widget-container">
        <!-- Chat Icon Button -->
        <button class="chat-icon-button" id="chatToggleBtn" title="Chat with us">
            <i class="fas fa-comments"></i>
            <span class="chat-badge" id="chatBadge" style="display: none;">1</span>
        </button>

        <!-- Chat Box -->
        <div class="chat-box" id="chatBox">
            <!-- Chat Header -->
            <div class="chat-header">
                <div class="chat-header-info">
                    <div class="chat-header-avatar">
                        <i class="fas fa-robot"></i>
                    </div>
                    <div>
                        <p class="chat-header-title">FAREN AI Support</p>
                        <p class="chat-header-subtitle" id="chatStatusSubtitle">Online & Ready</p>
                    </div>
                </div>
                <button class="chat-close-btn" id="chatCloseBtn">
                    <i class="fas fa-times"></i>
                </button>
            </div>

            <!-- Chat Messages -->
            <div class="chat-messages" id="chatMessages">
                <div class="chat-message">
                    <div>
                        <div class="message-bubble bot">
                            👋 Welcome to FAREN Support! How can I help you today?
                        </div>
                        <div class="chat-timestamp">Just now</div>
                    </div>
                </div>
            </div>

            <!-- Chat Input Area -->
            <div class="chat-input-area">
                <textarea class="chat-input" id="chatInput" placeholder="Type your message..." rows="1"></textarea>
                <button class="chat-send-btn" id="chatSendBtn">
                    <i class="fas fa-paper-plane"></i>
                </button>
            </div>
        </div>
    </div>

    <!-- Live Chat Script -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Chat Elements
            const chatToggleBtn = document.getElementById('chatToggleBtn');
            const chatCloseBtn = document.getElementById('chatCloseBtn');
            const chatBox = document.getElementById('chatBox');
            const chatInput = document.getElementById('chatInput');
            const chatSendBtn = document.getElementById('chatSendBtn');
            const chatMessages = document.getElementById('chatMessages');
            const chatBadge = document.getElementById('chatBadge');

            let messageCount = 0;

            // AI Chat Responses
            const aiResponses = [
                "What specific service are you interested in?",
                "Our interior design services include residential, commercial, and consultation packages.",
                "Would you like more details about our design process?",
                "We offer free initial consultation. Shall I schedule one for you?",
                "Tell me about your project vision!",
                "How can our team assist you?",
                "Would you prefer email, phone, or meeting?",
                "We'll respond within 24 hours. What's your preferred contact method?"
            ];

            // Toggle Chat Box
            chatToggleBtn.addEventListener('click', function() {
                chatBox.classList.toggle('active');
                if (chatBox.classList.contains('active')) {
                    if (window.innerWidth <= 480) document.body.style.overflow = 'hidden';
                    chatInput.focus();
                    chatBadge.style.display = 'none';
                }
            });

            // Close Chat Box
            chatCloseBtn.addEventListener('click', function() {
                chatBox.classList.remove('active');
                document.body.style.overflow = '';
            });

            // Close with Escape key
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape' && chatBox.classList.contains('active')) {
                    chatBox.classList.remove('active');
                    document.body.style.overflow = '';
                }
            });

            // Add User Message
            function addUserMessage(text) {
                const now = new Date();
                const timeStr = now.toLocaleTimeString('en-US', { 
                    hour: '2-digit', 
                    minute: '2-digit',
                    hour12: true 
                });

                const messageDiv = document.createElement('div');
                messageDiv.className = 'chat-message user';
                messageDiv.innerHTML = `
                    <div>
                        <div class="message-bubble user">${escapeHtml(text)}</div>
                        <div class="chat-timestamp">${timeStr}</div>
                    </div>
                `;
                chatMessages.appendChild(messageDiv);
                scrollToBottom();
            }

            // Add Bot Message
            function addBotMessage(text) {
                const now = new Date();
                const timeStr = now.toLocaleTimeString('en-US', { 
                    hour: '2-digit', 
                    minute: '2-digit',
                    hour12: true 
                });

                const messageDiv = document.createElement('div');
                messageDiv.className = 'chat-message';
                messageDiv.innerHTML = `
                    <div>
                        <div class="message-bubble bot">${text}</div>
                        <div class="chat-timestamp">${timeStr}</div>
                    </div>
                `;
                chatMessages.appendChild(messageDiv);
                scrollToBottom();
            }

            // Send Message Handler
            function sendMessage() {
                const message = chatInput.value.trim();
                if (!message) return;

                // Add user message
                addUserMessage(message);
                chatInput.value = '';
                chatInput.style.height = 'auto';

                // Simulate bot response delay
                setTimeout(() => {
                    const randomResponse = aiResponses[Math.floor(Math.random() * aiResponses.length)];
                    addBotMessage(randomResponse);
                }, 800);

                messageCount++;
            }

            // Scroll to Bottom
            function scrollToBottom() {
                setTimeout(() => {
                    chatMessages.scrollTop = chatMessages.scrollHeight;
                }, 0);
            }

            // Escape HTML
            function escapeHtml(text) {
                const div = document.createElement('div');
                div.textContent = text;
                return div.innerHTML;
            }

            // Send Button Click
            chatSendBtn.addEventListener('click', sendMessage);

            // Enter Key to Send (Shift+Enter for new line)
            chatInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });

            // Auto-resize Textarea
            chatInput.addEventListener('input', function() {
                this.style.height = 'auto';
                this.style.height = Math.min(this.scrollHeight, 100) + 'px';
            });

            // Show notification badge when message arrives (demo)
            window.addEventListener('blur', () => {
                if (messageCount > 0 && !chatBox.classList.contains('active')) {
                    chatBadge.style.display = 'flex';
                }
            });
        });
    </script>

<?php
include __DIR__ . '/../footer-section.html';
?>
