<?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';
if ($name === '') { http_response_code(422); echo json_encode(['success'=>false,'message'=>'اسم المورد مطلوب']); exit; }
try {
  $st = $pdo->prepare("INSERT INTO suppliers (company_id, name, kind, phone, notes) VALUES (?,?,?,?,?)");
  $st->execute([$cid, $name, $kind, trim($_POST['phone'] ?? ''), trim($_POST['notes'] ?? '')]);
  $id = (int)$pdo->lastInsertId();
  echo json_encode(['success'=>true,'item'=>['id'=>$id,'text'=>$name]]);
} catch (Throwable $e) { http_response_code(422); echo json_encode(['success'=>false,'message'=>$e->getMessage()]); }
