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

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

    public function getByJournalId(int $journal_id): array {
        $stmt = $this->db->prepare("SELECT * FROM journal_lines WHERE journal_id=? ORDER BY id ASC");
        $stmt->execute([$journal_id]);
        return $stmt->fetchAll();
    }

    public function add(array $data): bool {
        $stmt = $this->db->prepare("
            INSERT INTO journal_lines (journal_id, account_code, line_description, debit, credit)
            VALUES (?, ?, ?, ?, ?)
        ");
        return $stmt->execute([
            $data['journal_id'],
            $data['account_code'],
            $data['line_description'],
            $data['debit'],
            $data['credit']
        ]);
    }

    public function delete(int $id): bool {
        $stmt = $this->db->prepare("DELETE FROM journal_lines WHERE id=?");
        return $stmt->execute([$id]);
    }

    public function getTotals(int $journal_id): array {
        $stmt = $this->db->prepare("
            SELECT SUM(debit) AS total_debit, SUM(credit) AS total_credit
            FROM journal_lines WHERE journal_id=?
        ");
        $stmt->execute([$journal_id]);
        return $stmt->fetch() ?: ['total_debit'=>0,'total_credit'=>0];
    }
}
