<?php
require_once __DIR__ . '/../app/init.php';
require_once __DIR__ . '/account_lib.php';
header('Content-Type: application/json; charset=utf-8');
$pdo = db();
$cid = (int)$_SESSION['company_id'];
$parent_id = ($_GET['parent_id'] ?? '') !== '' ? (int)$_GET['parent_id'] : null;
$type = $_GET['type'] ?? 'EXPENSE';
if (!in_array($type,['ASSET','LIABILITY','EQUITY','REVENUE','EXPENSE'], true)) {
  $type = 'EXPENSE';
}
try {
  if ($parent_id) {
    $st = $pdo->prepare("SELECT type, name FROM accounts WHERE company_id=? AND id=? LIMIT 1");
    $st->execute([$cid, $parent_id]);
    $parent = $st->fetch(PDO::FETCH_ASSOC);
    if ($parent) $type = $parent['type'];
  }
  $code = next_account_code($pdo, $cid, $parent_id, $type);
  echo json_encode(['success'=>true,'code'=>$code,'type'=>$type]);
} catch (Throwable $e) {
  http_response_code(422);
  echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
