<?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'];
$id = (int)($_POST['id'] ?? 0);
$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;
$is_active = isset($_POST['is_active']) ? (int)!empty($_POST['is_active']) : 1;
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 && $id && $parent_id === $id) {
    throw new RuntimeException('لا يمكن اختيار نفس الحساب كأب');
  }
  $current = null;
  if ($id > 0) {
    $cur = $pdo->prepare("SELECT id, parent_id FROM accounts WHERE company_id=? AND id=? LIMIT 1");
    $cur->execute([$cid, $id]);
    $current = $cur->fetch(PDO::FETCH_ASSOC);
    if (!$current) throw new RuntimeException('الحساب غير موجود');
  }

  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) throw new RuntimeException('الحساب الأب غير موجود');
    $type = (string)$parentType;
  }

  if ($current && (int)($current['parent_id'] ?? 0) !== (int)($parent_id ?? 0) && account_has_references($pdo, $cid, $id)) {
    throw new RuntimeException('لا يمكن نقل الحساب لأنه مرتبط بقيود أو حركات بالنظام');
  }
  $code = next_account_code($pdo, $cid, $parent_id, $type, $id ?: null);
  $normal = account_normal_side($type);
  if ($id > 0) {
    $st = $pdo->prepare("UPDATE accounts SET code=?, name=?, type=?, normal_side=?, parent_id=?, is_cash=?, is_active=? WHERE company_id=? AND id=?");
    $st->execute([$code,$name,$type,$normal,$parent_id,$is_cash,$is_active,$cid,$id]);
  } else {
    $st = $pdo->prepare("INSERT INTO accounts (company_id, code, name, type, normal_side, parent_id, is_cash, is_locked, is_active) VALUES (?,?,?,?,?,?,?,0,?)");
    $st->execute([$cid,$code,$name,$type,$normal,$parent_id,$is_cash,$is_active]);
    $id = (int)$pdo->lastInsertId();
  }
  echo json_encode([
    'success'=>true,
    'id'=>$id,
    'code'=>$code,
    'item'=>[
      'id'=>$id,
      'name'=>$name,
      'type'=>$type,
      'code'=>$code,
      'parent_id'=>$parent_id,
      'is_cash'=>(int)$is_cash,
      'is_active'=>(int)$is_active,
    ]
  ]);
} catch (Throwable $e) {
  http_response_code(422);
  echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
