<?php
require_once __DIR__ . '/../app/init.php';
require_once __DIR__ . '/account_lib.php';
header('Content-Type: application/json; charset=utf-8');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['success'=>false,'message'=>'Method not allowed']); exit; }
csrf_check();
$pdo = db();
$cid = (int)$_SESSION['company_id'];
$name = trim($_POST['name'] ?? '');
$type = $_POST['type'] ?? '';
$parent_id = ($_POST['parent_id'] ?? '') !== '' ? (int)$_POST['parent_id'] : null;
$is_cash = !empty($_POST['is_cash']) ? 1 : 0;
if (!$name || !in_array($type,['ASSET','LIABILITY','EQUITY','REVENUE','EXPENSE'], true)) {
  http_response_code(422); echo json_encode(['success'=>false,'message'=>'تحقق من البيانات']); exit;
}
try {
  if ($parent_id) {
    $st = $pdo->prepare("SELECT type FROM accounts WHERE company_id=? AND id=? LIMIT 1");
    $st->execute([$cid, $parent_id]);
    $parentType = $st->fetchColumn();
    if ($parentType) $type = (string)$parentType;
  }
  $code = next_account_code($pdo, $cid, $parent_id, $type);
  $normal = account_normal_side($type);
  $st = $pdo->prepare("INSERT INTO accounts (company_id, code, name, type, normal_side, parent_id, is_cash, is_locked) VALUES (?,?,?,?,?,?,?,0)");
  $st->execute([$cid,$code,$name,$type,$normal,$parent_id,$is_cash]);
  $id = (int)$pdo->lastInsertId();
  echo json_encode(['success'=>true,'item'=>['id'=>$id,'text'=>$code.' - '.$name,'code'=>$code,'name'=>$name]]);
} catch (Throwable $e) {
  http_response_code(422); echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
