<?php
// /public_html/erp.jewellersbd.com/api/cash/update_account.php
header("Content-Type: application/json; charset=UTF-8");

require_once __DIR__ . '/../../config/session.php';
require_once __DIR__ . '/../../config/db.php';

if (session_status() === PHP_SESSION_NONE) session_start();

if ((!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) &&
    (!function_exists('is_logged_in') || !is_logged_in())) {
    echo json_encode(["success"=>false,"message"=>"লগইন প্রয়োজন"], JSON_UNESCAPED_UNICODE);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
$id   = intval($data['id'] ?? 0);
$name = trim($data['account_name'] ?? '');

if (!$id || empty($name)) {
    echo json_encode(["success"=>false,"message"=>"তথ্য সম্পূর্ণ নয়"], JSON_UNESCAPED_UNICODE);
    exit;
}

// duplicate check (other accounts)
$chk = $conn->prepare("SELECT id FROM cash_accounts WHERE account_name = ? AND id != ?");
$chk->bind_param("si", $name, $id);
$chk->execute();
if ($chk->get_result()->num_rows > 0) {
    echo json_encode(["success"=>false,"message"=>"এই নামে অন্য অ্যাকাউন্ট আছে"], JSON_UNESCAPED_UNICODE);
    exit;
}

$stmt = $conn->prepare("UPDATE cash_accounts SET account_name = ? WHERE id = ?");
$stmt->bind_param("si", $name, $id);
if ($stmt->execute()) {
    echo json_encode(["success"=>true,"message"=>"অ্যাকাউন্ট আপডেট হয়েছে"], JSON_UNESCAPED_UNICODE);
} else {
    echo json_encode(["success"=>false,"message"=>"সমস্যা: ".$conn->error], JSON_UNESCAPED_UNICODE);
}
exit;
?>