<?php
/**
 * File: api/karigar/ledger_get.php
 * Purpose: একটি karigar এর full transaction history + running balance
 * Method : GET
 * Query  : ?karigar_id=<int>&date_from=YYYY-MM-DD&date_to=YYYY-MM-DD&entry_type=ALL|ISSUE_GOLD|...
 * Output : { success, data: { karigar:{}, summary:{}, entries:[...] } }
 */

ini_set('display_errors', 0);
error_reporting(E_ALL);

header('Content-Type: application/json; charset=utf-8');

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

function out_json($code, $success, $message, $data = null) {
    http_response_code($code);
    echo json_encode([
        'success' => (bool)$success,
        'status'  => (bool)$success,
        'message' => $message,
        'data'    => $data
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if (function_exists('is_logged_in') && !is_logged_in()) {
    out_json(401, false, 'লগইন প্রয়োজন', null);
}

if (!isset($pdo) || !($pdo instanceof PDO)) {
    out_json(500, false, 'Database connection পাওয়া যায়নি', null);
}

$karigar_id = (int)($_GET['karigar_id'] ?? 0);
$date_from  = trim((string)($_GET['date_from'] ?? ''));
$date_to    = trim((string)($_GET['date_to'] ?? ''));
$entry_type = trim((string)($_GET['entry_type'] ?? 'ALL'));

if ($karigar_id <= 0) out_json(400, false, 'Karigar ID দিন', null);

try {
    // ===== Karigar info =====
    $kstmt = $pdo->prepare("
        SELECT id, name, phone, address, note, gold_balance, opening_payable, opening_receivable
        FROM parties WHERE id = ? AND is_karigar = 1 LIMIT 1
    ");
    $kstmt->execute([$karigar_id]);
    $karigar = $kstmt->fetch(PDO::FETCH_ASSOC);

    if (!$karigar) out_json(404, false, 'Karigar পাওয়া যায়নি', null);

    // ===== WHERE clause =====
    $where  = ["kl.karigar_party_id = :kid"];
    $params = [':kid' => $karigar_id];

    if ($date_from !== '') { $where[] = "kl.entry_date >= :dfrom"; $params[':dfrom'] = $date_from; }
    if ($date_to   !== '') { $where[] = "kl.entry_date <= :dto";   $params[':dto']   = $date_to; }
    if ($entry_type !== 'ALL' && $entry_type !== '') {
        $where[] = "kl.entry_type = :etype";
        $params[':etype'] = $entry_type;
    }
    $whereSql = implode(' AND ', $where);

    // ===== Entries =====
    $sql = "
        SELECT
            kl.id, kl.entry_date, kl.entry_type, kl.reference_table, kl.reference_id,
            kl.gold_in_pure_gram, kl.gold_out_pure_gram, kl.cash_in, kl.cash_out,
            kl.note, kl.created_at, kl.created_by,
            u.name AS created_by_name
        FROM karigar_ledger kl
        LEFT JOIN users u ON u.id = kl.created_by
        WHERE $whereSql
        ORDER BY kl.entry_date ASC, kl.id ASC
    ";

    $stmt = $pdo->prepare($sql);
    foreach ($params as $k => $v) $stmt->bindValue($k, $v);
    $stmt->execute();
    $rawEntries = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // ===== Running balance calculation =====
    // Gold pure balance: gold_in (from karigar) - gold_out (to karigar)
    //   > 0 → karigar এর কাছে gold আছে (আটকে আছে — আমরা পাব)
    //   = 0 → settled
    // Cash balance: cash_out (আমরা দিতে দেনা) - cash_in (আমরা পেতে দেনা)
    //   > 0 → আমাদের দেনা = karigar এর pawn
    //   < 0 → karigar আমাদের দেনা

    $running_gold = 0.0;
    $running_cash = 0.0;
    $entries = [];

    foreach ($rawEntries as $e) {
        $gin  = (float)$e['gold_in_pure_gram'];
        $gout = (float)$e['gold_out_pure_gram'];
        $cin  = (float)$e['cash_in'];
        $cout = (float)$e['cash_out'];

        // gold_out_pure_gram = আমরা দিয়েছি = karigar এর কাছে আটকে = balance এ +
        // gold_in_pure_gram = আমরা পেয়েছি/wastage = balance থেকে -
        $running_gold += ($gout - $gin);

        // cash_out = আমরা দিতে হবে / দিয়েছি (labor)
        // cash_in = আমরা পেতে / পেয়েছি (shortage charge)
        $running_cash += ($cout - $cin);

        $entries[] = [
            'id'                => (int)$e['id'],
            'entry_date'        => $e['entry_date'],
            'entry_type'        => $e['entry_type'],
            'reference_table'   => $e['reference_table'],
            'reference_id'      => $e['reference_id'] !== null ? (int)$e['reference_id'] : null,
            'gold_in'           => round($gin, 4),
            'gold_out'          => round($gout, 4),
            'cash_in'           => round($cin, 2),
            'cash_out'          => round($cout, 2),
            'running_gold'      => round($running_gold, 4),
            'running_cash'      => round($running_cash, 2),
            'note'              => (string)($e['note'] ?? ''),
            'created_at'        => $e['created_at'],
            'created_by_name'   => (string)($e['created_by_name'] ?? '')
        ];
    }

    // ===== Summary =====
    $sumStmt = $pdo->prepare("
        SELECT
            COALESCE(SUM(gold_out_pure_gram), 0) AS total_issued_pure,
            COALESCE(SUM(gold_in_pure_gram), 0)  AS total_received_pure_plus_wastage,
            COALESCE(SUM(CASE WHEN entry_type='WASTAGE_ACCEPTED' THEN gold_in_pure_gram ELSE 0 END), 0) AS total_wastage_pure,
            COALESCE(SUM(CASE WHEN entry_type='SHORTAGE_CHARGED' THEN gold_in_pure_gram ELSE 0 END), 0) AS total_shortage_pure,
            COALESCE(SUM(CASE WHEN entry_type='RECEIVE_GOLD' THEN gold_in_pure_gram ELSE 0 END), 0) AS total_received_pure_only,
            COALESCE(SUM(CASE WHEN entry_type='LABOR_CHARGE' THEN cash_out ELSE 0 END), 0) AS total_labor_charged,
            COALESCE(SUM(CASE WHEN entry_type='LABOR_PAYMENT' THEN cash_out ELSE 0 END), 0) AS total_labor_paid,
            COALESCE(SUM(CASE WHEN entry_type='SHORTAGE_CHARGED' THEN cash_in ELSE 0 END), 0) AS total_shortage_cash
        FROM karigar_ledger
        WHERE karigar_party_id = ?
    ");
    $sumStmt->execute([$karigar_id]);
    $sum = $sumStmt->fetch(PDO::FETCH_ASSOC);

    $total_issued       = (float)$sum['total_issued_pure'];
    $total_received     = (float)$sum['total_received_pure_only'];
    $total_wastage      = (float)$sum['total_wastage_pure'];
    $total_shortage     = (float)$sum['total_shortage_pure'];
    $labor_charged      = (float)$sum['total_labor_charged'];
    $labor_paid         = (float)$sum['total_labor_paid'];
    $shortage_cash      = (float)$sum['total_shortage_cash'];

    $pending_pure = $total_issued - $total_received - $total_wastage - $total_shortage;
    $labor_due    = $labor_charged - $labor_paid - $shortage_cash; // shortage cash adjusts labor

    $summary = [
        'total_issued_pure'   => round($total_issued, 4),
        'total_received_pure' => round($total_received, 4),
        'total_wastage_pure'  => round($total_wastage, 4),
        'total_shortage_pure' => round($total_shortage, 4),
        'pending_pure'        => round($pending_pure, 4),
        'total_labor_charged' => round($labor_charged, 2),
        'total_labor_paid'    => round($labor_paid, 2),
        'total_shortage_cash' => round($shortage_cash, 2),
        'labor_due'           => round($labor_due, 2),
        'gold_balance_field'  => (float)($karigar['gold_balance'] ?? 0)
    ];

    out_json(200, true, 'OK', [
        'karigar' => [
            'id'      => (int)$karigar['id'],
            'name'    => (string)$karigar['name'],
            'phone'   => (string)($karigar['phone'] ?? ''),
            'address' => (string)($karigar['address'] ?? ''),
            'note'    => (string)($karigar['note'] ?? '')
        ],
        'summary' => $summary,
        'entries' => $entries
    ]);

} catch (Throwable $e) {
    out_json(500, false, 'সার্ভার ত্রুটি: ' . $e->getMessage(), null);
}
