<?php
session_start();
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');

$zroot = $_SESSION["zdbroot"];

$zdb = $_SESSION["zdbyear_" . $dbname];

mysqli_select_db($conn, $zdb);

$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);

$name = trim($_POST['name']);
$name_safe = mysqli_real_escape_string($conn, $name);
$mobile = trim($_POST['mobile']);

/* 🔍 Check if party already exists (case-insensitive) */
$chk = mysqli_query($conn, "
    SELECT code, name 
    FROM transport 
    WHERE LOWER(name) = LOWER('$name_safe')
    LIMIT 1
");

if (mysqli_num_rows($chk) > 0) {

    // ✅ Party exists → return existing
    $row = mysqli_fetch_assoc($chk);

    echo json_encode([
        'status' => 'exists',
        'code' => $row['code'],
        'name' => $row['name']
    ]);
    exit;
}

/* ➕ Create new party */
$q = mysqli_query($conn, "SELECT IFNULL(MAX(code),0) AS maxcode FROM transport");
$r = mysqli_fetch_assoc($q);

$newcode = $r['maxcode'] + 1;

mysqli_query($conn, "INSERT INTO transport (code, name)
                                  VALUES ('$newcode', '$name_safe')") or die(mysqli_error($conn));

echo json_encode([
    'status' => 'created',
    'code' => $newcode,
    'name' => $name_safe
]);
