<?php
/**
 * Journal Controller — Generic Double-Entry Vouchers
 */

class JournalController {
    private PDO $db;
    private object $user;

    public function __construct(PDO $db, object $user) {
        $this->db = $db;
        $this->user = $user;
    }

    /** POST /journals */
    public function store(array $data): void {
        Validator::check($data, [
            'date'        => 'required|date',
            'source_type' => 'required|string|in:opening,purchase,sale,cash_bank,expense,settlement',
            'narration'   => 'nullable|string',
            'entries'     => 'required|array'
        ]);

        if (empty($data['entries'])) {
            Response::error('براہ کرم کم از کم دو اندراجات (Dr/Cr) شامل کریں۔', 400);
        }

        $this->db->beginTransaction();
        try {
            $journalId = AccountingService::postJournal($this->db, [
                'date'        => $data['date'],
                'source_type' => $data['source_type'],
                'source_id'   => $data['source_id'] ?? null,
                'narration'   => $data['narration'] ?? null,
                'created_by'  => $this->user->id
            ], $data['entries']);

            AuditLogger::log($this->db, $this->user->id, 'CREATED_JOURNAL', 'journals', $journalId, null, $data);

            $this->db->commit();
            Response::created(['id' => $journalId], 'واؤچر کامیابی سے محفوظ ہو گیا۔');
        } catch (Exception $e) {
            $this->db->rollBack();
            throw $e;
        }
    }
    /** POST /journals/add-capital */
    public function addCapital(array $data): void {
        Validator::check($data, [
            'date'      => 'required|date',
            'amount'    => 'required|numeric|gt:0',
            'narration' => 'nullable|string'
        ]);

        // 1. Find the required accounts
        // System Capital (Cr)
        $stmt = $this->db->prepare("SELECT id FROM accounts WHERE type = 'capital' AND is_system = 1 LIMIT 1");
        $stmt->execute();
        $crAcc = $stmt->fetch();

        // Proxy Capital (Dr)
        $stmt = $this->db->prepare("SELECT id FROM accounts WHERE type = 'bank_cash' AND name LIKE 'capital%' AND is_system = 0 LIMIT 1");
        $stmt->execute();
        $drAcc = $stmt->fetch();

        if (!$crAcc || !$drAcc) {
            Response::error('سرمایہ کاری کے اکاؤنٹس نہیں ملے۔ براہ کرم سیٹ اپ چیک کریں۔', 500);
        }

        $this->db->beginTransaction();
        try {
            $journalId = AccountingService::postJournal($this->db, [
                'date'        => $data['date'],
                'source_type' => 'opening',
                'narration'   => $data['narration'] ?? 'نیا سرمایہ (New Investment)',
                'created_by'  => $this->user->id
            ], [
                ['account_id' => $drAcc['id'], 'debit' => $data['amount'], 'credit' => 0, 'narration' => 'New Investment Dr'],
                ['account_id' => $crAcc['id'], 'debit' => 0, 'credit' => $data['amount'], 'narration' => 'New Investment Cr']
            ]);

            AuditLogger::log($this->db, $this->user->id, 'ADD_CAPITAL', 'journals', $journalId, null, $data);

            $this->db->commit();
            Response::created(['id' => $journalId], 'سرمایہ کامیابی سے شامل کر دیا گیا ہے۔');
        } catch (Exception $e) {
            $this->db->rollBack();
            throw $e;
        }
    }
}
