<?php
declare(strict_types=1);

require_once __DIR__ . '/../../app/Config/database.php';

class Journal
{
    private PDO $db;

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

    /**
     * Get all journals
     */
    public function getAll(): array
    {
        $stmt = $this->db->query("SELECT * FROM journals ORDER BY id DESC");
        return $stmt->fetchAll();
    }

    /**
     * ✅ Generate next sequential journal number
     * Format: JRN-YYYY-00001
     * Automatically resets numbering at the start of each new year.
     */
    public function generateJournalNo(): string
    {
        $year = date('Y');

        // Fetch the last journal number for this year
        $stmt = $this->db->prepare("
            SELECT journal_no 
            FROM journals 
            WHERE journal_no LIKE ? 
            ORDER BY id DESC LIMIT 1
        ");
        $stmt->execute(["JRN-$year-%"]);
        $lastNo = $stmt->fetchColumn();

        if ($lastNo) {
            // Extract numeric part and increment
            $seq = (int)substr($lastNo, -5) + 1;
        } else {
            // Start new sequence each year
            $seq = 1;
        }

        return sprintf("JRN-%s-%05d", $year, $seq);
    }

    /**
     * Add new journal entry (auto-generates journal_no)
     */
    public function add(array $data): bool
    {
        $journalNo = $this->generateJournalNo();

        $stmt = $this->db->prepare("
            INSERT INTO journals (journal_no, reference_no, journal_date, description, status, created_by)
            VALUES (?, ?, ?, ?, ?, ?)
        ");

        return $stmt->execute([
            $journalNo,
            $data['reference_no'] ?? null,
            $data['journal_date'] ?? date('Y-m-d'),
            $data['description'] ?? '',
            $data['status'] ?? 'draft',
            $data['created_by'] ?? null
        ]);
    }

    /**
     * Delete a journal entry by ID
     */
    public function delete(int $id): bool
    {
        $stmt = $this->db->prepare("DELETE FROM journals WHERE id = ?");
        return $stmt->execute([$id]);
    }

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