<?php
// /public_html/erp.jewellersbd.com/api/cash/create_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);
$name    = trim($data['account_name'] ?? '');
$balance = floatval($data['opening_balance'] ?? 0);

if (empty($name)) {
    echo json_encode(["success"=>false,"message"=>"অ্যাকাউন্টের নাম দিন"], JSON_UNESCAPED_UNICODE);
    exit;
}

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

$stmt = $conn->prepare("INSERT INTO cash_accounts (account_name, opening_balance, current_balance) VALUES (?, ?, ?)");
$stmt->bind_param("sdd", $name, $balance, $balance);
if ($stmt->execute()) {
    echo json_encode(["success"=>true,"message"=>"অ্যাকাউন্ট তৈরি হয়েছে","id"=>$conn->insert_id], JSON_UNESCAPED_UNICODE);
} else {
    echo json_encode(["success"=>false,"message"=>"সমস্যা: ".$conn->error], JSON_UNESCAPED_UNICODE);
}
exit;
?>