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

class Coa {
    private PDO $db;

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

    /** 🔹 Get all accounts */
    public function getAll(): array {
        $stmt = $this->db->query("SELECT * FROM chart_of_accounts ORDER BY account_code ASC");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    /** 🔹 Get account by ID */
    public function getById(int $id): ?array {
        $stmt = $this->db->prepare("SELECT * FROM chart_of_accounts WHERE id=?");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }

    /** 🔹 Create new account */
    public function create(array $data): bool {
        $stmt = $this->db->prepare("
            INSERT INTO chart_of_accounts 
            (account_code, account_name, account_type, parent_account, description, status)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        return $stmt->execute([
            $data['account_code'] ?? '',
            $data['account_name'] ?? '',
            $data['account_type'] ?? '',
            $data['parent_account'] ?? null,
            $data['description'] ?? '',
            $data['status'] ?? 'active'
        ]);
    }

    /** 🔹 Update account */
    public function update(int $id, array $data): bool {
        $stmt = $this->db->prepare("
            UPDATE chart_of_accounts
            SET account_code=?, account_name=?, account_type=?, parent_account=?, description=?, status=?
            WHERE id=?
        ");
        return $stmt->execute([
            $data['account_code'] ?? '',
            $data['account_name'] ?? '',
            $data['account_type'] ?? '',
            $data['parent_account'] ?? null,
            $data['description'] ?? '',
            $data['status'] ?? 'active',
            $id
        ]);
    }

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