<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\App;
use App\Core\Response;
use App\Modules\Accounting\Models\DailyTransaction;
use App\Modules\Accounting\Models\JournalType;
use App\Modules\Accounting\Services\DailyTransactionService;

class DailyTransactionController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('accounting.daily_tx.view');

        $date = $request->get('date', date('Y-m-d'));
        $transactions = DailyTransaction::getByDate($date);

        $db = App::getInstance()->db();
        $accounts = $db->select("SELECT id, code, name_ar FROM chart_of_accounts WHERE is_archived = 0 AND is_header = 0 ORDER BY code");
        $journalTypes = JournalType::getActive();
        $costCenters = $db->select("SELECT id, code, name_ar FROM cost_centers WHERE is_active = 1 ORDER BY code");

        $accountMap = [];
        foreach ($accounts as $a) $accountMap[(int)$a['id']] = $a;
        $typeMap = [];
        foreach ($journalTypes as $jt) $typeMap[(int)$jt['id']] = $jt;

        return $this->view('Accounting/Views/daily_transactions/index', [
            'date'          => $date,
            'transactions'  => $transactions,
            'accounts'      => $accounts,
            'journalTypes'  => $journalTypes,
            'costCenters'   => $costCenters,
            'accountMap'    => $accountMap,
            'typeMap'       => $typeMap,
        ]);
    }

    public function store(Request $request): Response
    {
        $this->authorize('accounting.daily_tx.manage');

        $data = $this->validate($request->all(), [
            'transaction_date' => 'required',
            'account_id'       => 'required',
            'amount'           => 'required',
            'direction'        => 'required',
        ]);

        $session = App::getInstance()->session();

        DailyTransaction::create([
            'transaction_date' => $data['transaction_date'],
            'journal_type_id'  => $request->post('journal_type_id') ? (int)$request->post('journal_type_id') : null,
            'account_id'       => (int)$data['account_id'],
            'cost_center_id'   => $request->post('cost_center_id') ? (int)$request->post('cost_center_id') : null,
            'amount'           => (float)$data['amount'],
            'direction'        => $data['direction'],
            'description'      => $request->post('description'),
            'document_number'  => $request->post('document_number'),
            'currency'         => $request->post('currency', 'EGP'),
            'branch_id'        => $request->post('branch_id') ? (int)$request->post('branch_id') : null,
            'created_by'       => (int)($session->get('employee_id') ?? 0) ?: null,
        ]);

        return $this->redirect('/accounting/daily-transactions?date=' . $data['transaction_date'])
            ->withSuccess('تم تسجيل الحركة');
    }

    public function consolidate(Request $request): Response
    {
        $this->authorize('accounting.daily_tx.manage');

        $date = $request->post('date', date('Y-m-d'));
        $journalTypeId = $request->post('journal_type_id') ? (int)$request->post('journal_type_id') : null;

        $entryId = DailyTransactionService::consolidate($date, $journalTypeId);

        if ($entryId === null) {
            return $this->redirect('/accounting/daily-transactions?date=' . $date)
                ->withError('لا توجد حركات غير مجمعة لهذا التاريخ');
        }

        return $this->redirect('/accounting/daily-transactions?date=' . $date)
            ->withSuccess('تم إنشاء القيد المجمع رقم #' . $entryId);
    }
}
