<?php
session_start();
include 'db.php';

$login_msg = "";
$register_msg = "";

/* ------------------------------------
   USER REGISTRATION
------------------------------------ */
if(isset($_POST['register'])){
    $name = trim($_POST['name']);
    $phone = trim($_POST['phone']);
    $email = trim($_POST['email']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    $check = $pdo->prepare("SELECT id FROM users WHERE email=?");
    $check->execute([$email]);

    if($check->rowCount() > 0){
        $register_msg = "Email already registered!";
    } else {
        $q = $pdo->prepare("INSERT INTO users(name, phone, email, password) VALUES(?,?,?,?)");
        $q->execute([$name, $phone, $email, $password]);
        $register_msg = "Account created! Please login.";
    }
}

/* ------------------------------------
   USER LOGIN
------------------------------------ */
if(isset($_POST['login'])){
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);

    $stmt = $pdo->prepare("SELECT * FROM users WHERE email=? LIMIT 1");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if($user && password_verify($password, $user['password'])){
        
        // Save login session
        $_SESSION['user_id'] = $user['id'];

        // 🔥 REDIRECT USER BACK TO LAST PAGE
        if(isset($_SESSION['redirect_after_login'])){
            $redirect = $_SESSION['redirect_after_login'];
            unset($_SESSION['redirect_after_login']);
            header("Location: $redirect");
            exit();
        }

        // Default redirect if no redirect target
        header("Location: profile.php");
        exit();

    } else {
        $login_msg = "Invalid email or password!";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login / Register – Varahi Foods</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>

<body class="bg-gray-100 font-[Poppins]">

<?php include "header.php"; ?>

<div class="min-h-[80vh] flex flex-col justify-center items-center px-4 pt-10 sm:pt-16">

    <!-- BUTTONS -->
    <div class="flex gap-3 w-full max-w-sm mb-6">
        <button id="btnLogin" onclick="showTab('loginForm')"
            class="flex-1 py-2 rounded-lg bg-blue-900 text-white font-semibold">
            Login
        </button>
        <button id="btnRegister" onclick="showTab('registerForm')"
            class="flex-1 py-2 rounded-lg bg-gray-200 text-gray-800 font-semibold">
            Register
        </button>
    </div>

    <!-- LOGIN FORM -->
    <div id="loginForm" class="w-full max-w-sm bg-white shadow-xl rounded-xl p-8">
        <h2 class="text-2xl font-bold text-center text-blue-900 mb-6">Login</h2>

        <?php if($login_msg): ?>
            <div class="text-red-600 text-center mb-3 text-sm"><?= $login_msg ?></div>
        <?php endif; ?>

        <form method="POST">
            <input type="email" name="email" placeholder="Email" required
                class="w-full px-4 py-3 mb-3 rounded-lg border focus:border-blue-800 outline-none">

            <input type="password" name="password" placeholder="Password" required
                class="w-full px-4 py-3 mb-4 rounded-lg border focus:border-blue-800 outline-none">

            <button type="submit" name="login"
                class="w-full bg-blue-900 text-white py-3 rounded-lg font-semibold hover:bg-blue-800 transition">
                Login
            </button>
        </form>
    </div>

    <!-- REGISTER FORM -->
    <div id="registerForm" class="w-full max-w-sm bg-white shadow-xl rounded-xl p-8 hidden">
        <h2 class="text-2xl font-bold text-center text-blue-900 mb-6">Create Account</h2>

        <?php if($register_msg): ?>
            <div class="text-green-600 text-center mb-3 text-sm"><?= $register_msg ?></div>
        <?php endif; ?>

        <form method="POST">
            <input type="text" name="name" placeholder="Full Name" required
                class="w-full px-4 py-3 mb-3 rounded-lg border focus:border-blue-800 outline-none">

            <input type="text" name="phone" placeholder="Phone Number" required
                class="w-full px-4 py-3 mb-3 rounded-lg border focus:border-blue-800 outline-none">

            <input type="email" name="email" placeholder="Email" required
                class="w-full px-4 py-3 mb-3 rounded-lg border focus:border-blue-800 outline-none">

            <input type="password" name="password" placeholder="Password" required
                class="w-full px-4 py-3 mb-4 rounded-lg border focus:border-blue-800 outline-none">

            <button type="submit" name="register"
                class="w-full bg-blue-900 text-white py-3 rounded-lg font-semibold hover:bg-blue-800 transition">
                Register
            </button>
        </form>
    </div>

</div>

<script>
function showTab(tab){
    document.getElementById('loginForm').classList.add('hidden');
    document.getElementById('registerForm').classList.add('hidden');
    document.getElementById(tab).classList.remove('hidden');

    const btnLogin = document.getElementById('btnLogin');
    const btnRegister = document.getElementById('btnRegister');

    btnLogin.classList.toggle("bg-blue-900", tab=='loginForm');
    btnLogin.classList.toggle("text-white", tab=='loginForm');
    btnLogin.classList.toggle("bg-gray-200", tab!='loginForm');
    btnLogin.classList.toggle("text-gray-800", tab!='loginForm');

    btnRegister.classList.toggle("bg-blue-900", tab=='registerForm');
    btnRegister.classList.toggle("text-white", tab=='registerForm');
    btnRegister.classList.toggle("bg-gray-200", tab!='registerForm');
    btnRegister.classList.toggle("text-gray-800", tab!='registerForm');
}

// Keep correct tab visible based on errors/messages
document.addEventListener("DOMContentLoaded", function() {
    <?php if($login_msg): ?>
        showTab('loginForm');
    <?php elseif($register_msg): ?>
        showTab('registerForm');
    <?php else: ?>
        showTab('loginForm');
    <?php endif; ?>
});
</script>

</body>
</html>
