<?php
session_start();
include 'config.php'; // include your db connection

if (isset($_SESSION['user'])) {
    header('Location: index.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name     = trim($_POST['name'] ?? '');
    $email    = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $cpass    = $_POST['cpassword'] ?? '';
    $city     = mysqli_real_escape_string($conn, $_POST['city'] ?? '');

    if ($password !== $cpass) {
        $error = 'Passwords do not match.';
    } elseif (strlen($password) < 6) {
        $error = 'Password must be at least 6 characters.';
    } else {
        $hash = password_hash($password, PASSWORD_BCRYPT);

        // check if email exists
        $check = mysqli_query($conn, "SELECT id FROM users WHERE email='" . mysqli_real_escape_string($conn, $email) . "'");
        if (mysqli_num_rows($check) > 0) {
            $error = 'Email already registered.';
        } else {
            // insert user with city only
            $sql = "INSERT INTO users (name, email, password_hash, role, city, created_at)
                    VALUES ('" . mysqli_real_escape_string($conn, $name) . "',
                            '" . mysqli_real_escape_string($conn, $email) . "',
                            '$hash',
                            'student',
                            '$city',
                            NOW())";

            if (mysqli_query($conn, $sql)) {
                $_SESSION['flash'] = 'Registration successful. Please login.';
                header('Location: login.php');
                exit;
            } else {
                $error = 'Registration failed. Please try again.';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register</title>
    <style>
    body {
        font-family: Arial, sans-serif;
        background-color: #f5f7fb;
        margin: 0;
    }

    /* Navbar */
    .nav {
        background-color: #1f2937; /* dark navy */
        color: #fff;
        padding: 12px 20px;
    }
    .nav .container {
        display: flex;
        justify-content: space-between;
        align-items: center;
        max-width: 1200px;
        margin: 0 auto;
    }
    .nav .brand {
        font-weight: bold;
        font-size: 16px;
    }
    .nav a {
        color: #fff;
        text-decoration: none;
        font-weight: 500;
    }
    .nav a:hover {
        text-decoration: underline;
    }

    /* Wrapper + Card */
    .wrapper {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 40px 20px;
    }
    h2 {
        margin-bottom: 20px;
        font-size: 22px;
        font-weight: bold;
        color: #333;
        text-align: center;
    }
    label {
        font-size: 14px;
        color: #444;
        margin-bottom: 6px;
        display: block;
    }
    input {
        width: 100%;
        padding: 12px;
        border: 1px solid #ccc;
        border-radius: 6px;
        margin-bottom: 16px;
        font-size: 14px;
        box-sizing: border-box;
    }
    button {
        width: 100%;
        padding: 12px;
        background: #2563eb;
        color: #fff;
        border: none;
        border-radius: 6px;
        font-size: 15px;
        font-weight: bold;
        cursor: pointer;
    }
    button:hover {
        background: #1e4ed8;
    }
    .error {
        color: red;
        margin-bottom: 10px;
        text-align: center;
    }
    .success {
        color: green;
        margin-bottom: 10px;
        text-align: center;
    }

    /* Password wrapper */
    .password-wrapper {
        position: relative;
        margin-bottom: 16px;
    }

    .password-wrapper input {
        width: 100%;
        padding: 12px 40px 12px 12px; /* space for eye icon */
        border: 1px solid #ccc;
        border-radius: 6px;
        font-size: 14px;
        box-sizing: border-box;
    }

    .password-wrapper img {
        position: absolute;
        right: 12px;
        top: 50%;
        transform: translateY(-50%);
        width: 20px;
        height: 20px;
        cursor: pointer;
        opacity: 0.6;
        transition: opacity 0.2s;
    }

    .password-wrapper img:hover {
        opacity: 1;
    }
    @media (min-width:481px) {   
        .card {
        background: #fff;
        padding: 25px;
        border-radius: 10px;
        box-shadow: 0px 4px 20px rgba(0,0,0,0.1);
        width: 100%;
        max-width: 480px;
    }
   }

    /* Responsive Styles */
    @media (max-width: 480px) {
        body {
            font-size: 14px;
        }
        .card {
            padding: 20px;
            border-radius: 8px;
        }
        input, button {
            padding: 10px;
            font-size: 13px;
        }
        h2 {
            font-size: 18px;
        }
    }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="nav">
        <div class="container">
            <div class="brand">📝 Exam Portal</div>
            <div><a href="login.php">Login</a></div>
        </div>
    </nav>

    <!-- Register Card -->
    <div class="wrapper">
        <div class="card">
            <h2>Register</h2>

            <?php if (!empty($error)) : ?>
                <p class="error"><?php echo htmlspecialchars($error); ?></p>
            <?php endif; ?>

            <?php if (!empty($_SESSION['flash'])) : ?>
                <p class="success"><?php echo htmlspecialchars($_SESSION['flash']); unset($_SESSION['flash']); ?></p>
            <?php endif; ?>

            <form method="POST" action="">
                <label>Name</label>
                <input type="text" name="name" required>

                <label>Email</label>
                <input type="email" name="email" required>

                <label>Password</label>
                <div class="password-wrapper">
                    <input type="password" name="password" id="password" required>
                    <img src="images/invisible.png" id="togglePassword">
                </div>

                <label>Confirm Password</label>
                <div class="password-wrapper">
                    <input type="password" name="cpassword" id="cpassword" required>
                    <img src="images/invisible.png" id="toggleCPassword">
                </div>

                <!-- Visible City Field -->
                <label>City</label>
                <input type="text" name="city" id="city" placeholder="Fetching your city..." required>

                <button type="submit">Create Account</button>
            </form>
        </div>
    </div>

    <script>
    document.addEventListener("DOMContentLoaded", () => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(success, error);
        } else {
            document.getElementById("city").placeholder = "Enter your city";
        }

        function success(position) {
            let lat = position.coords.latitude;
            let lon = position.coords.longitude;

            fetch(`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lon}&format=json`)
                .then(res => res.json())
                .then(data => {
                    let addr = data.address;
                    let location = "";

                    if (addr.village) location += addr.village;
                    else if (addr.town) location += addr.town;
                    else if (addr.city) location += addr.city;

                    if (addr.city && !location.includes(addr.city)) {
                        location += ", " + addr.city;
                    } else if (addr.state_district) {
                        location += ", " + addr.state_district;
                    }

                    document.getElementById("city").value = location || "Enter your city";
                })
                .catch(() => {
                    document.getElementById("city").placeholder = "Enter your city";
                });
        }

        function error() {
            document.getElementById("city").placeholder = "Enter your city";
        }
    });

    // Toggle Password
    const togglePassword = document.getElementById('togglePassword');
    const password = document.getElementById('password');
    togglePassword.addEventListener('click', () => {
        if (password.type === 'password') {
            password.type = 'text';
            togglePassword.src = 'images/view.png';
        } else {
            password.type = 'password';
            togglePassword.src = 'images/invisible.png';
        }
    });

    const toggleCPassword = document.getElementById('toggleCPassword');
    const cpassword = document.getElementById('cpassword');
    toggleCPassword.addEventListener('click', () => {
        if (cpassword.type === 'password') {
            cpassword.type = 'text';
            toggleCPassword.src = 'images/view.png';
        } else {
            cpassword.type = 'password';
            toggleCPassword.src = 'images/invisible.png';
        }
    });
    </script>
</body>
</html>
