<?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);
$gstno = trim($_POST['gstno']);
$gstno_safe = mysqli_real_escape_string($conn, $gstno);
$mobile = trim($_POST['mobile']);
$state = trim($_POST['state']);
$statecode = trim($_POST['statecode']);
$group = trim($_POST['group']);

/* 🔍 Check if party already exists (case-insensitive) */
$chk = mysqli_query($conn, "
    SELECT accode, name 
    FROM accmast 
    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',
        'accode' => $row['accode'],
        'name' => $row['name']
    ]);
    exit;
}

/* ➕ Create new party */
$q = mysqli_query($conn, "SELECT MAX(accode) AS maxcode FROM accmast");
$r = mysqli_fetch_assoc($q);
$newcode = $r['maxcode'] + 1;

/* default grpcode – change if needed */
if ($group === '009') {
    $grpcode = '009'; // Suppliers
} else {
    $grpcode = '010';
}

if ($statecode != '27') {
    $oms = '1';
} else {
    $oms = '';
}

mysqli_query($conn, "INSERT INTO accmast (accode, name, grpcode, init, gstno, mobile, state, statecode, oms)
                                  VALUES ('$newcode', '$name_safe', '$grpcode', 'SDR', '$gstno_safe', '$mobile', '$state', '$statecode', '$oms')") or die(mysqli_error($conn));

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