<?php
require_once '../../config/db.php';
require_once '../../config/session.php';
require_once '../../config/response.php';

session_start_if_not_started();

if (!is_logged_in()) {
    send_response(401, false, 'অনুমতি নেই');
}

$party_id    = $_GET['party_id'] ?? null;
$location_id = $_GET['location_id'] ?? null;
$from_date   = $_GET['from_date'] ?? date('Y-m-01');
$to_date     = $_GET['to_date'] ?? date('Y-m-d');
$entry_type  = $_GET['entry_type'] ?? null;

try {
    $where  = "WHERE gl.entry_date BETWEEN :from_date AND :to_date";
    $params = [
        ':from_date' => $from_date,
        ':to_date'   => $to_date
    ];

    if ($party_id) {
        $where .= " AND gl.party_id = :party_id";
        $params[':party_id'] = $party_id;
    }

    if ($location_id) {
        $where .= " AND gl.location_id = :location_id";
        $params[':location_id'] = $location_id;
    }

    if ($entry_type) {
        $where .= " AND gl.entry_type = :entry_type";
        $params[':entry_type'] = $entry_type;
    }

    $stmt = $pdo->prepare(
        "SELECT 
            gl.id,
            gl.entry_date,
            gl.entry_type,
            gl.karat,
            gl.gold_in,
            gl.gold_out,
            gl.amount_in,
            gl.amount_out,
            gl.note,
            p.name AS party_name,
            sl.name AS location_name,
            u.name AS created_by_name
         FROM gold_ledger gl
         LEFT JOIN parties p 
            ON gl.party_id = p.id
         LEFT JOIN stock_locations sl 
            ON gl.location_id = sl.id
         LEFT JOIN users u 
            ON gl.created_by = u.id
         $where
         ORDER BY gl.entry_date DESC, gl.id DESC"
    );
    $stmt->execute($params);
    $ledger = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // মোট হিসাব
    $total_gold_in    = 0;
    $total_gold_out   = 0;
    $total_amount_in  = 0;
    $total_amount_out = 0;

    foreach ($ledger as $entry) {
        $total_gold_in    += $entry['gold_in'];
        $total_gold_out   += $entry['gold_out'];
        $total_amount_in  += $entry['amount_in'];
        $total_amount_out += $entry['amount_out'];
    }

    send_response(200, true, 'সফল', [
        'ledger'            => $ledger,
        'total_gold_in'     => round($total_gold_in, 3),
        'total_gold_out'    => round($total_gold_out, 3),
        'total_amount_in'   => round($total_amount_in, 2),
        'total_amount_out'  => round($total_amount_out, 2)
    ]);

} catch (Exception $e) {
    send_response(500, false, 'সার্ভার সমস্যা: ' . $e->getMessage());
}
?>