<?php
// api_ledger.php
require_once 'auth_check.php';
require_once 'db.php';

header('Content-Type: application/json');
$action = $_GET['action'] ?? '';

try {
    // 1. Ambil daftar akun untuk dropdown filter
    if ($action === 'get_accounts') {
        // Daftar akun standar sesuai sistem akuntansi sebelumnya
        $accounts = [
            ['code' => '1100', 'name' => 'Kas / Bank'],
            ['code' => '1120', 'name' => 'Piutang Usaha'],
            ['code' => '4100', 'name' => 'Penjualan Barang'],
            // Tambahkan akun lain jika ada di database chart of accounts Anda
        ];
        echo json_encode(['status' => 'success', 'data' => $accounts]);
    }

    // 2. Ambil Data Buku Besar (General Ledger)
    elseif ($action === 'get_general_ledger') {
        $account_code = $_GET['account_code'] ?? '1100';
        $date_from    = $_GET['date_from'] ?? date('Y-m-01'); // Default awal bulan ini
        $date_to      = $_GET['date_to'] ?? date('Y-m-d');     // Default hari ini

        if (empty($account_code)) {
            echo json_encode(['status' => 'error', 'message' => 'Kode akun wajib dipilih!']);
            exit;
        }

        // A. Hitung Saldo Awal (Sebelum tanggal $date_from)
        // Saldo awal adalah akumulasi (Debit - Kredit) untuk akun aset/beban atau (Kredit - Debit) untuk kewajiban/ekuitas/pendapatan.
        // Di sini diasumsikan normal balance berbasis Net (Debit - Kredit). Sesuaikan jika diperlukan.
        $stmtStart = $pdo->prepare("
            SELECT COALESCE(SUM(jd.debit - jd.credit), 0) AS opening_balance 
            FROM journal_details jd 
            JOIN journal_entries je ON jd.journal_id = je.id 
            WHERE jd.account_code = ? AND je.journal_date < ?
        ");
        $stmtStart->execute([$account_code, $date_from]);
        $opening_balance = floatval($stmtStart->fetch()['opening_balance']);

        // B. Ambil Transaksi Pergerakan (Mutasi) Selama Rentang Tanggal ($date_from s/d $date_to)
        $stmtTrans = $pdo->prepare("
            SELECT je.journal_date, je.journal_number, je.reference_type, je.reference_id, je.description, jd.debit, jd.credit 
            FROM journal_details jd 
            JOIN journal_entries je ON jd.journal_id = je.id 
            WHERE jd.account_code = ? AND je.journal_date BETWEEN ? AND ?
            ORDER BY je.journal_date ASC, je.id ASC
        ");
        $stmtTrans->execute([$account_code, $date_from, $date_to]);
        $transactions = $stmtTrans->fetchAll(PDO::FETCH_ASSOC);

        // C. Hitung Pergerakan Total Periode & Saldo Akhir Berjalan
         মোট_debit = 0; // menggunakan variabel penampung
        $total_debit = 0;
        $total_credit = 0;

        foreach ($transactions as &$tx) {
            $total_debit += floatval($tx['debit']);
            $total_credit += floatval($tx['credit']);
        }
        unset($tx);

        $ending_balance = $opening_balance + ($total_debit - $total_credit);

        echo json_encode([
            'status'          => 'success',
            'account_code'    => $account_code,
            'date_from'       => $date_from,
            'date_to'         => $date_to,
            'opening_balance' => $opening_balance,
            'total_debit'     => $total_debit,
            'total_credit'    => $total_credit,
            'ending_balance'  => $ending_balance,
            'transactions'    => $transactions
        ]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Aksi tidak valid!']);
    }

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'Error: ' . $e->getMessage()]);
}
?>