<?php
declare(strict_types=1);
require_once __DIR__ . '/../../app/Config/database.php';

class GeneralLedger {
    private PDO $db;
    public function __construct() { $this->db = Database::getConnection(); }

    public function getAll(?string $start=null, ?string $end=null, ?string $account=null): array {
        $conditions = [];
        $params = [];

        if ($start) { $conditions[] = "j.journal_date >= ?"; $params[] = $start; }
        if ($end) { $conditions[] = "j.journal_date <= ?"; $params[] = $end; }
        if ($account) { $conditions[] = "l.account_code = ?"; $params[] = $account; }

        $where = $conditions ? 'WHERE ' . implode(' AND ', $conditions) : '';

        $sql = "
            SELECT j.id AS journal_id, j.journal_no, j.journal_date, j.description AS journal_desc,
                   l.account_code, a.account_name, l.debit, l.credit, j.status
            FROM journal_lines l
            JOIN journal_entries j ON j.id = l.journal_id
            JOIN chart_of_accounts a ON a.account_code = l.account_code
            $where
            ORDER BY j.journal_date DESC, j.journal_no ASC
        ";
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }

    public function getAccounts(): array {
        $stmt = $this->db->query("SELECT account_code, account_name FROM chart_of_accounts ORDER BY account_code ASC");
        return $stmt->fetchAll();
    }
}
