<?php

/**
 * Nesvra Ecosystem — Authentication (Sign In & Sign Up)
 */
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check redirect target
$redirect = isset($_GET['redirect']) ? htmlspecialchars($_GET['redirect']) : '';
$product  = isset($_GET['product']) ? htmlspecialchars($_GET['product']) : '';
$plan     = isset($_GET['plan']) ? htmlspecialchars($_GET['plan']) : '';
$action   = isset($_GET['action']) && $_GET['action'] === 'register' ? 'register' : 'login';

$targetUrl = 'home';
if ($redirect === 'checkout') {
    $params = [];
    if ($product) $params['product'] = $product;
    if ($plan) $params['plan'] = $plan;
    $targetUrl = 'checkout' . (!empty($params) ? '?' . http_build_query($params) : '');
}

// Handle Form Submission
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formType = $_POST['form_type'] ?? 'login';

    if ($formType === 'register') {
        $fullname = trim($_POST['fullname'] ?? '');
        $email    = trim($_POST['email'] ?? '');
        $password = trim($_POST['password'] ?? '');
        $company  = trim($_POST['company'] ?? '');
        $phone    = trim($_POST['phone'] ?? '');
        $country  = trim($_POST['country'] ?? '');

        if (!$fullname || !$email || strlen($password) < 6) {
            $error = 'Please fill all required fields (Password must be at least 6 characters).';
            $action = 'register';
        } else {
            $_SESSION['nesvra_user'] = [
                'fullname' => $fullname,
                'email'    => $email,
                'company'  => $company,
                'phone'    => $phone,
                'country'  => $country,
            ];
            header('Location: ' . $targetUrl);
            exit;
        }
    } else {
        $email    = trim($_POST['email'] ?? '');
        $password = trim($_POST['password'] ?? '');

        if (!$email || !$password) {
            $error = 'Please enter both your email and password.';
            $action = 'login';
        } else {
            $_SESSION['nesvra_user'] = [
                'fullname' => explode('@', $email)[0],
                'email'    => $email,
                'company'  => '',
                'phone'    => '',
                'country'  => '',
            ];
            header('Location: ' . $targetUrl);
            exit;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<?php
$pagetitle = ($action === 'register' ? 'Create Account' : 'Sign In') . " | Nesvra";
include 'components/head.php';
?>

<style>
    .input-group {
        position: relative;
        display: flex;
        align-items: center;
        background: #ffffff;
        border: 1px solid #E2E8F0;
        border-radius: 16px;
        transition: all 0.25s cubic-bezier(0.16, 1, 0.3, 1);
    }

    .input-group:focus-within {
        border-color: #081F5C;
        box-shadow: 0 0 0 3px rgba(8, 31, 92, 0.08);
        background: #ffffff;
    }

    .input-group .icon-left {
        position: absolute;
        left: 18px;
        color: #94A3B8;
        font-size: 17px;
        pointer-events: none;
        transition: color 0.2s ease;
    }

    .input-group:focus-within .icon-left {
        color: #081F5C;
    }

    .input-field {
        width: 100%;
        background: transparent;
        padding: 16px 18px 16px 48px;
        font-size: 14px;
        font-weight: 500;
        color: #0F172A;
        outline: none;
        border: none;
    }

    .input-field::placeholder {
        color: #94A3B8;
        font-weight: 400;
    }

    /* Smooth Form Fade & Slide */
    .form-view {
        transition: opacity 0.3s cubic-bezier(0.16, 1, 0.3, 1), transform 0.3s cubic-bezier(0.16, 1, 0.3, 1);
    }

    .form-view.entering {
        opacity: 0;
        transform: translateY(8px) scale(0.99);
    }

    .form-view.active {
        opacity: 1;
        transform: translateY(0) scale(1);
    }
</style>

<body class="bg-[#FAFBFD] min-h-screen text-slate-900 flex flex-col justify-between selection:bg-brandOrange selection:text-white">

    <!-- Top Navigation Header -->
    <header class="w-full pt-8 pb-4 px-6 sm:px-12 md:px-16 flex items-center justify-between">
        <!-- Brand Logo on Left -->
        <a href="index.php" class="flex items-center group transition-transform duration-300 hover:scale-[1.02]">
            <img src="Asset/logo-colored.png" alt="Nesvra" class="h-8 md:h-9 w-auto object-contain block" onerror="this.onerror=null; this.src='Asset/logo.png';">
        </a>

        <!-- Centered Pill Switcher (Flecisoft Pattern) -->
        <div class="relative bg-[#EEF2F6] p-1.5 rounded-full flex items-center border border-slate-200/60 shadow-inner">
            <button type="button" id="tabLoginBtn"
                class="relative z-10 px-6 sm:px-8 py-2.5 rounded-full text-xs font-semibold tracking-tight transition-all duration-300 <?= $action === 'login' ? 'bg-royal text-white shadow-md' : 'text-slate-600 hover:text-royal' ?>">
                Sign In
            </button>
            <button type="button" id="tabRegisterBtn"
                class="relative z-10 px-6 sm:px-8 py-2.5 rounded-full text-xs font-semibold tracking-tight transition-all duration-300 <?= $action === 'register' ? 'bg-royal text-white shadow-md' : 'text-slate-600 hover:text-royal' ?>">
                Create Account
            </button>
        </div>

        <!-- Right Placeholder to balance layout (Back link on desktop) -->
        <div class="hidden sm:flex items-center">
            <a href="index.php" class="text-xs font-semibold text-soft hover:text-royal transition-colors flex items-center gap-1.5">
                <i class="ri-arrow-left-line"></i> Back to website
            </a>
        </div>
    </header>

    <!-- Main Content Area -->
    <main class="flex-1 flex items-center justify-center px-4 py-8 md:py-12">
        <div class="w-full max-w-[500px] mx-auto">

            <!-- Error Alert Banner -->
            <?php if ($error): ?>
                <div class="mb-6 p-4 rounded-2xl bg-red-50 border border-red-200 text-red-700 text-xs font-semibold flex items-center gap-2.5 animate-[fadeIn_0.3s_ease]">
                    <i class="ri-error-warning-fill text-base text-red-500 shrink-0"></i>
                    <span><?= htmlspecialchars($error) ?></span>
                </div>
            <?php endif; ?>

            <!-- ═══════════════════════════════════════ -->
            <!--  SIGN IN VIEW                           -->
            <!-- ═══════════════════════════════════════ -->
            <div id="loginFormContainer" class="form-view <?= $action === 'register' ? 'hidden' : 'active' ?>">

                <div class="mb-8 text-left">
                    <h1 class="text-3xl sm:text-4xl font-[700] tracking-tight text-slate-900 mb-2">Welcome back</h1>
                    <p class="text-sm text-soft font-medium">Sign in to your Nesvra account</p>
                </div>

                <form action="auth.php<?= !empty($_SERVER['QUERY_STRING']) ? '?' . htmlspecialchars($_SERVER['QUERY_STRING']) : '' ?>" method="POST" class="flex flex-col gap-4">
                    <input type="hidden" name="form_type" value="login" />

                    <!-- Email Input -->
                    <div class="input-group">
                        <i class="ri-mail-line icon-left"></i>
                        <input type="email" name="email" required placeholder="alex@fintechventures.com" class="input-field" />
                    </div>

                    <!-- Password Input -->
                    <div class="input-group">
                        <i class="ri-lock-line icon-left"></i>
                        <input type="password" id="loginPasswordInput" name="password" required placeholder="••••••••" class="input-field pr-12" />
                        <button type="button" class="absolute right-4 text-slate-400 hover:text-slate-700 transition-colors p-1" onclick="togglePassword('loginPasswordInput', this)" aria-label="Toggle password visibility">
                            <i class="ri-eye-line text-base"></i>
                        </button>
                    </div>

                    <!-- Submit Button -->
                    <button type="submit" class="w-full mt-2 py-4 px-6 rounded-full bg-royal text-white font-semibold text-sm hover:bg-electric active:scale-[0.99] transition-all duration-200 shadow-[0_10px_25px_-5px_rgba(8,31,92,0.3)] flex items-center justify-center gap-2 group">
                        <span>Sign In</span>
                        <i class="ri-arrow-right-line group-hover:translate-x-1 transition-transform"></i>
                    </button>
                </form>

                <p class="text-center text-xs text-soft mt-8 font-medium">
                    Don't have an account?
                    <button type="button" class="text-slate-900 font-bold hover:text-brandOrange transition-colors" onclick="switchToRegister()">Create one</button>
                </p>
            </div>


            <!-- ═══════════════════════════════════════ -->
            <!--  CREATE ACCOUNT VIEW                    -->
            <!-- ═══════════════════════════════════════ -->
            <div id="registerFormContainer" class="form-view <?= $action === 'register' ? 'active' : 'hidden' ?>">

                <div class="mb-8 text-left">
                    <h1 class="text-3xl sm:text-4xl font-[700] tracking-tight text-slate-900 mb-2">Create your account</h1>
                    <p class="text-sm text-soft font-medium">Join 50+ founders building with Nesvra</p>
                </div>

                <form action="auth.php<?= !empty($_SERVER['QUERY_STRING']) ? '?' . htmlspecialchars($_SERVER['QUERY_STRING']) : '' ?>" method="POST" class="flex flex-col gap-4">
                    <input type="hidden" name="form_type" value="register" />

                    <!-- Full Name Input -->
                    <div class="input-group">
                        <i class="ri-user-3-line icon-left"></i>
                        <input type="text" name="fullname" required placeholder="Full name *" class="input-field" />
                    </div>

                    <!-- Email Input -->
                    <div class="input-group">
                        <i class="ri-mail-line icon-left"></i>
                        <input type="email" name="email" required placeholder="alex@fintechventures.com" class="input-field" />
                    </div>

                    <!-- Password Input -->
                    <div class="input-group">
                        <i class="ri-lock-line icon-left"></i>
                        <input type="password" id="regPasswordInput" name="password" minlength="6" required placeholder="Password (min 6 chars) *" class="input-field pr-12" />
                        <button type="button" class="absolute right-4 text-slate-400 hover:text-slate-700 transition-colors p-1" onclick="togglePassword('regPasswordInput', this)" aria-label="Toggle password visibility">
                            <i class="ri-eye-line text-base"></i>
                        </button>
                    </div>

                    <!-- 2-Column Row: Company & Phone -->
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div class="input-group">
                            <i class="ri-building-line icon-left"></i>
                            <input type="text" name="company" placeholder="Company name" class="input-field" />
                        </div>
                        <div class="input-group">
                            <i class="ri-phone-line icon-left"></i>
                            <input type="tel" name="phone" placeholder="Phone number" class="input-field" />
                        </div>
                    </div>

                    <!-- Country Select Input -->
                    <div class="input-group">
                        <i class="ri-global-line icon-left"></i>
                        <select name="country" class="input-field appearance-none cursor-pointer pr-10">
                            <option value="" disabled selected>Country</option>
                            <option value="United States">United States</option>
                            <option value="United Kingdom">United Kingdom</option>
                            <option value="Nigeria">Nigeria</option>
                            <option value="Ghana">Ghana</option>
                            <option value="Kenya">Kenya</option>
                            <option value="South Africa">South Africa</option>
                            <option value="Canada">Canada</option>
                            <option value="United Arab Emirates">United Arab Emirates</option>
                            <option value="Germany">Germany</option>
                            <option value="Other">Other Country</option>
                        </select>
                        <i class="ri-arrow-down-s-line absolute right-4 text-slate-400 pointer-events-none"></i>
                    </div>

                    <!-- Submit Button -->
                    <button type="submit" class="w-full mt-2 py-4 px-6 rounded-2xl bg-royal text-white font-bold text-sm hover:bg-electric active:scale-[0.99] transition-all duration-200 shadow-[0_10px_25px_-5px_rgba(8,31,92,0.3)] flex items-center justify-center gap-2 group">
                        <span>Create Account</span>
                        <i class="ri-arrow-right-line group-hover:translate-x-1 transition-transform"></i>
                    </button>
                </form>

                <p class="text-center text-xs text-soft mt-8 font-medium">
                    Already have an account?
                    <button type="button" class="text-slate-900 font-bold hover:text-brandOrange transition-colors" onclick="switchToLogin()">Sign in</button>
                </p>
            </div>

        </div>
    </main>

    <!-- Clean Minimal Footer -->
    <footer class="py-6 text-center text-xs text-slate-400">
        &copy; <?= date('Y') ?> Nesvra Technologies Inc. All rights reserved.
    </footer>

    <!-- Interactive Scripts for Smooth Animated Switching & Password Toggling -->
    <script>
        const loginContainer = document.getElementById('loginFormContainer');
        const registerContainer = document.getElementById('registerFormContainer');
        const tabLoginBtn = document.getElementById('tabLoginBtn');
        const tabRegisterBtn = document.getElementById('tabRegisterBtn');

        function switchToLogin() {
            if (!registerContainer.classList.contains('hidden')) {
                registerContainer.classList.add('entering');
                setTimeout(() => {
                    registerContainer.classList.add('hidden');
                    registerContainer.classList.remove('active', 'entering');

                    loginContainer.classList.remove('hidden');
                    loginContainer.classList.add('entering');
                    requestAnimationFrame(() => {
                        loginContainer.classList.remove('entering');
                        loginContainer.classList.add('active');
                    });
                }, 150);
            }

            tabLoginBtn.className = "relative z-10 px-6 sm:px-8 py-2.5 rounded-full text-xs font-semibold tracking-tight transition-all duration-300 bg-royal text-white shadow-md";
            tabRegisterBtn.className = "relative z-10 px-6 sm:px-8 py-2.5 rounded-full text-xs font-semibold tracking-tight transition-all duration-300 text-slate-600 hover:text-royal";
        }

        function switchToRegister() {
            if (!loginContainer.classList.contains('hidden')) {
                loginContainer.classList.add('entering');
                setTimeout(() => {
                    loginContainer.classList.add('hidden');
                    loginContainer.classList.remove('active', 'entering');

                    registerContainer.classList.remove('hidden');
                    registerContainer.classList.add('entering');
                    requestAnimationFrame(() => {
                        registerContainer.classList.remove('entering');
                        registerContainer.classList.add('active');
                    });
                }, 150);
            }

            tabRegisterBtn.className = "relative z-10 px-6 sm:px-8 py-2.5 rounded-full text-xs font-semibold tracking-tight transition-all duration-300 bg-royal text-white shadow-md";
            tabLoginBtn.className = "relative z-10 px-6 sm:px-8 py-2.5 rounded-full text-xs font-semibold tracking-tight transition-all duration-300 text-slate-600 hover:text-royal";
        }

        tabLoginBtn.addEventListener('click', switchToLogin);
        tabRegisterBtn.addEventListener('click', switchToRegister);

        // Password Show/Hide Toggle
        function togglePassword(inputId, btn) {
            const input = document.getElementById(inputId);
            const icon = btn.querySelector('i');
            if (input.type === 'password') {
                input.type = 'text';
                icon.className = 'ri-eye-off-line text-base text-slate-700';
            } else {
                input.type = 'password';
                icon.className = 'ri-eye-line text-base text-slate-400';
            }
        }
    </script>
</body>

</html>