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

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

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

        if (!$email || !$password) {
            $error = 'Email and password are required';
        } else {
            // Check if user is admin
            $stmt = $conn->prepare('SELECT id, name, email, role, password, two_factor_enabled FROM users WHERE email = ? AND role = ?');
            $user_role = 'admin';
            $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'];
                        ?>
                        <script>
                            localStorage.setItem('userLoggedIn', 'true');
                            localStorage.setItem('userName', '<?php echo htmlspecialchars($user['name']); ?>');
                            localStorage.setItem('userRole', '<?php echo htmlspecialchars($user['role']); ?>');
                            window.location.href = '../admin-dashboard.php';
                        </script>
                        <?php
                        exit;
                    }
                } else {
                    $error = 'Invalid email or password';
                }
            } else {
                $error = 'Admin account not found. Access denied.';
            }
            $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']);
                ?>
                <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 = '../admin-dashboard.php';
                </script>
                <?php
                exit;
            } else {
                $error = 'Invalid or expired 2FA code. Please try again.';
                $step = 2;
            }
            $otp_stmt->close();
        }
    }
}

?>

<?php 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); }
        }

        .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: 20px;
            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;
        }

        .admin-badge {
            display: inline-block;
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 700;
            letter-spacing: 1px;
            text-transform: uppercase;
            margin-bottom: 12px;
            box-shadow: 0 4px 15px rgba(220, 53, 69, 0.3);
        }

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

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

        /* 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;
            }

            .admin-badge {
                font-size: 10px;
                padding: 5px 12px;
                margin-bottom: 10px;
            }

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

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

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

        /* Extra Large Screens (1024px+) */
        @media (min-width: 1024px) {
            .login-container {
                padding: 50px 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;
            }
        }
    </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="admin-badge">
                        <i class="fas fa-shield-alt"></i> Admin Portal
                    </div>
                    <div class="logo">FAREN</div>
                    <h2>Admin Access</h2>
                    <p>Secure administration login</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> Admin Email</label>
                            <input type="email" id="email" class="form-control" name="email" placeholder="admin@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 as Admin</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 & Access Dashboard</button>

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

                <?php if ($step == 1): ?>
                    <div class="divider"><span>Customer Access?</span></div>
                    <div class="footer-text">
                        Go to <a href="login.php">Customer Login</a>
                    </div>
                <?php endif; ?>
            </div>
            <!-- Close login-container -->
        </div>
        <!-- Close login-wrapper -->
    </div>
    <!-- Close main-auth-content -->

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