<?php
require_once "db.php";
header("Content-Type: application/json; charset=UTF-8");

// Accept JSON or normal POST
$raw = file_get_contents("php://input");
$data = json_decode($raw, true);
if (!is_array($data)) $data = $_POST;

$username = isset($data["username"]) ? trim($data["username"]) : "";
$password = isset($data["password"]) ? trim($data["password"]) : "";

if ($username === "" || $password === "") {
    echo json_encode([
        "success" => false,
        "error" => "Missing username/password"
    ]);
    exit();
}

// Admin shortcut
if ($username === "admin" && $password === "admin123") {
    echo json_encode([
        "success" => true,
        "role" => "admin",
        "admin_username" => "admin"
    ]);
    exit();
}

// Employee login
$sql = "SELECT emp_id, emp_name, username FROM employee WHERE username=? AND password=? LIMIT 1";
$stmt = $conn->prepare($sql);

if (!$stmt) {
    echo json_encode([
        "success" => false,
        "error" => "Prepare failed: " . $conn->error
    ]);
    exit();
}

$stmt->bind_param("ss", $username, $password);

if (!$stmt->execute()) {
    echo json_encode([
        "success" => false,
        "error" => "Execute failed: " . $stmt->error
    ]);
    exit();
}

$result = $stmt->get_result();
if (!$result) {
    echo json_encode([
        "success" => false,
        "error" => "get_result failed"
    ]);
    exit();
}

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

    echo json_encode([
        "success" => true,
        "role" => "employee",
        "emp_id" => intval($row["emp_id"]),
        "emp_name" => $row["emp_name"],
        "username" => $row["username"]
    ]);
    exit();
}

echo json_encode([
    "success" => false,
    "error" => "Invalid login"
]);