<?php
// File: /public_html/erp.jewellersbd.com/api/cash/get_cash_categories.php
// Cash Module 2.0 — Cash Entry: active category list (IN / OUT) for dropdown
// Uses $pdo (provided by config/db.php). NEW FILE — overwrites nothing.

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" => "লগইন প্রয়োজন",
        "data"    => null
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $stmt = $pdo->query("
        SELECT id, category_code, category_name, category_name_bn,
               direction, category_group, icon, sort_order
        FROM cash_categories
        WHERE is_active = 1
        ORDER BY direction ASC, sort_order ASC, id ASC
    ");
    $rows = $stmt->fetchAll();

    $in  = [];
    $out = [];

    foreach ($rows as $r) {
        $name = (isset($r['category_name_bn']) && $r['category_name_bn'] !== '' && $r['category_name_bn'] !== null)
            ? $r['category_name_bn']
            : $r['category_name'];

        $item = [
            "id"        => (int)$r['id'],
            "code"      => (string)$r['category_code'],
            "name"      => (string)$name,
            "direction" => (string)$r['direction'],
            "group"     => (string)($r['category_group'] ?? ''),
            "icon"      => (string)($r['icon'] ?? '')
        ];

        if ($r['direction'] === 'IN') {
            $in[] = $item;
        } else {
            $out[] = $item;
        }
    }

    echo json_encode([
        "success" => true,
        "message" => "ক্যাটাগরি সফলভাবে লোড হয়েছে",
        "data"    => [
            "IN"  => $in,
            "OUT" => $out
        ]
    ], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        "success" => false,
        "message" => "সার্ভার সমস্যা: " . $e->getMessage(),
        "data"    => null
    ], JSON_UNESCAPED_UNICODE);
}

exit;
?>