<?php
ob_start();
require("dbconnect.php");
require("config.php");
require("function.php");

header('Content-Type: application/json');

if (!isset($_SESSION["username_" . $dbname])) {
    echo json_encode(['ok' => false, 'error' => 'Not authenticated']);
    exit;
}

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

$type   = isset($_POST['type'])   ? trim($_POST['type'])   : '';
$name   = isset($_POST['name'])   ? trim($_POST['name'])   : '';
$mobile = isset($_POST['mobile']) ? trim($_POST['mobile']) : '';

$grpMap = ['customer' => '010', 'supplier' => '009', 'agent' => '040'];
if (!isset($grpMap[$type])) {
    echo json_encode(['ok' => false, 'error' => 'Invalid type.']);
    exit;
}
if ($name === '') {
    echo json_encode(['ok' => false, 'error' => 'Name is required.']);
    exit;
}

$grpcode = $grpMap[$type];
$nameEsc = mysqli_real_escape_string($conn, $name);
$mobEsc  = mysqli_real_escape_string($conn, $mobile);
$user    = mysqli_real_escape_string($conn, audituser());

// Check for duplicate name in same group
$dup = mysqli_query($conn, "SELECT `accode` FROM `accmast` WHERE `grpcode`='$grpcode' AND `name`='$nameEsc'");
if ($dup && mysqli_num_rows($dup) > 0) {
    $row = mysqli_fetch_assoc($dup);
    echo json_encode(['ok' => false, 'error' => 'A ' . $type . ' with this name already exists.', 'accode' => (int)$row['accode']]);
    exit;
}

// Insert minimal account record — all other fields default to empty/zero
$ins = mysqli_query($conn, "INSERT INTO `accmast`
    (`grpcode`,`name`,`mobile`,`adduser`,`adddate`,`addtime`)
    VALUES
    ('$grpcode','$nameEsc','$mobEsc','$user',CURDATE(),CURTIME())")
    or die(json_encode(['ok' => false, 'error' => mysqli_error($conn)]));

$newAcccode = (int)mysqli_insert_id($conn);

echo json_encode([
    'ok'     => true,
    'accode' => $newAcccode,
    'name'   => $name,
    'type'   => $type,
]);
