<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Services;

use App\Core\App;
use App\Modules\Accounting\Models\DailyTransaction;

class DailyTransactionService
{
    public static function consolidate(string $date, ?int $journalTypeId = null): ?int
    {
        $db = App::getInstance()->db();

        $qb = DailyTransaction::query()
            ->where('is_consolidated', '=', 0)
            ->where('transaction_date', '=', $date);

        if ($journalTypeId) {
            $qb->where('journal_type_id', '=', $journalTypeId);
        }

        $transactions = $qb->get();

        if (empty($transactions)) {
            return null;
        }

        $lines = [];
        $totalDebit = 0;
        $totalCredit = 0;

        foreach ($transactions as $tx) {
            $accountId = (int)$tx['account_id'];
            $amount = (float)$tx['amount'];
            $direction = $tx['direction'];

            $debit = $direction === 'debit' ? $amount : 0;
            $credit = $direction === 'credit' ? $amount : 0;
            $totalDebit += $debit;
            $totalCredit += $credit;

            $lines[] = [
                'account_id'     => $accountId,
                'debit_amount'   => $debit,
                'credit_amount'  => $credit,
                'cost_center_id' => $tx['cost_center_id'] ? (int)$tx['cost_center_id'] : null,
                'description'    => $tx['description'] ?? 'حركة يومية مجمعة',
            ];
        }

        $fy = $db->selectOne("SELECT id FROM fiscal_years WHERE is_current = 1 AND is_archived = 0");
        if (!$fy) {
            return null;
        }

        $now = date('Y-m-d H:i:s');
        $entryNumber = 'DT-' . str_replace('-', '', $date) . '-001';

        $existing = $db->selectOne("SELECT id FROM journal_entries WHERE entry_number = ?", [$entryNumber]);
        if ($existing) {
            $suffix = $db->selectOne(
                "SELECT COUNT(*) as cnt FROM journal_entries WHERE entry_number LIKE ?",
                ['DT-' . str_replace('-', '', $date) . '%']
            );
            $num = ((int)($suffix['cnt'] ?? 0)) + 1;
            $entryNumber = 'DT-' . str_replace('-', '', $date) . '-' . str_pad((string)$num, 3, '0', STR_PAD_LEFT);
        }

        $db->insert('journal_entries', [
            'entry_number'    => $entryNumber,
            'entry_date'      => $date,
            'fiscal_year_id'  => (int)$fy['id'],
            'reference_type'  => 'daily_consolidated',
            'description'     => 'قيد مجمع — حركات يومية ' . $date,
            'total_debit'     => $totalDebit,
            'total_credit'    => $totalCredit,
            'status'          => 'posted',
            'posted_at'       => $now,
            'created_at'      => $now,
            'updated_at'      => $now,
        ]);

        $journalEntryId = (int)$db->lastInsertId();

        foreach ($lines as $line) {
            $db->insert('journal_entry_lines', [
                'journal_entry_id' => $journalEntryId,
                'account_id'       => $line['account_id'],
                'debit_amount'     => $line['debit_amount'],
                'credit_amount'    => $line['credit_amount'],
                'cost_center_id'   => $line['cost_center_id'],
                'description'      => $line['description'],
                'created_at'       => $now,
                'updated_at'       => $now,
            ]);
        }

        $txIds = array_column($transactions, 'id');
        if (!empty($txIds)) {
            $placeholders = implode(',', array_fill(0, count($txIds), '?'));
            $db->query(
                "UPDATE daily_transactions SET is_consolidated = 1, consolidated_entry_id = ? WHERE id IN ({$placeholders})",
                array_merge([$journalEntryId], $txIds)
            );
        }

        return $journalEntryId;
    }
}
