<?php
require_once __DIR__ . '/../app/init.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'] ?? '');
$kind = $_POST['kind'] ?? 'OTHER';
$acc = (int)($_POST['revenue_account_id'] ?? 0);
$price = (float)($_POST['default_price'] ?? 0);
if ($name === '' || !$acc) { http_response_code(422); echo json_encode(['success'=>false,'message'=>'تحقق من البيانات']); exit; }
try {
  $st = $pdo->prepare("INSERT INTO services (company_id, name, kind, revenue_account_id, default_price) VALUES (?,?,?,?,?)");
  $st->execute([$cid, $name, $kind, $acc, $price]);
  $id = (int)$pdo->lastInsertId();
  echo json_encode(['success'=>true,'item'=>['id'=>$id,'text'=>$name,'price'=>$price]]);
} catch (Throwable $e) { http_response_code(422); echo json_encode(['success'=>false,'message'=>$e->getMessage()]); }
