<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
header('Content-Type: text/html; charset=utf-8');

include "db.php";

$action = $_POST['action'] ?? '';

if ($action == 'register') {
    $fullname = trim($_POST['fullname']);
  
    $mobile   = trim($_POST['mobile']);
    $email    = trim($_POST['email']);
    $place    = trim($_POST['place']);
   

    // ✅ Validation
    if (empty($fullname)  || empty($mobile) || empty($email) || empty($place)) {
        echo "<div class='alert alert-danger'>All fields are required.</div>";
        exit;
    }

    // ✅ Check if email already exists
    $check = $conn->prepare("SELECT id FROM usermaster WHERE email = ?");
    $check->bind_param("s", $email);
    $check->execute();
    $check->store_result();

    if ($check->num_rows > 0) {
        echo "<div class='alert alert-warning'>Email already registered!</div>";
    } else {
        // ✅ Insert new record (added year, degree)
        $stmt = $conn->prepare("
            INSERT INTO usermaster 
            (fullname,  mobileno, email, place, created_at) 
            VALUES (?, ?,  ?,?, NOW())
        ");
        $stmt->bind_param("ssss", $fullname, $mobile, $email, $place);

        if ($stmt->execute()) {
            echo "<div class='alert alert-success'>Registration successful! Please login.</div>";
        } else {
            echo "<div class='alert alert-danger'>Registration failed. Try again.</div>";
        }
    }

    $check->close();
    if (isset($stmt)) $stmt->close();
    $conn->close();
    exit;
}

if ($action == 'login') {
    $email = trim($_POST['email']);

    if (empty($email)) {
        echo "<div class='alert alert-danger'>Enter your email address.</div>";
        exit;
    }

    $stmt = $conn->prepare("SELECT id, fullname FROM usermaster WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();

        // ✅ Log login
        $ip = $_SERVER['REMOTE_ADDR'];
        $fullname = $user['fullname'];

        $log = $conn->prepare("INSERT INTO login_logs (email, fullname, ip_address) VALUES (?, ?, ?)");
        $log->bind_param("sss", $email, $fullname, $ip);
        $log->execute();
        $log->close();

        echo "<div class='alert alert-success'>Welcome, " . htmlspecialchars($fullname) . "!</div>";
    } else {
        echo "<div class='alert alert-danger'>Email not found. Please register first.</div>";
    }

    $stmt->close();
    $conn->close();
    exit;
}
?>