<?php

namespace App\Http\Controllers\Accounting;

use App\Http\Controllers\Controller;
use App\Models\FinancialTreasury;
use App\Models\FinancialTransaction;
use Illuminate\Http\Request;

class TreasuryController extends Controller
{
    public function index()
    {
        $treasuries = FinancialTreasury::with('transactions')->get(); // Removed transactions count for now if not needed or add back
        $currencies = \App\Models\Currency::where('is_active', true)->get();
        return view('accounting.treasuries.index', compact('treasuries', 'currencies'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:cash,bank,wallet',
            'currency_id' => 'nullable|exists:currencies,id',
            'balance' => 'required|numeric|min:0',
        ]);

        // If currency_id is provided, use it. If not, maybe use 'currency' string as fallback or remove 'currency' string completely?
        // For now, let's keep 'currency' string empty or derived.
        // The migration kept 'currency' string column. Ideally we should populate it with code.

        $currencyCode = 'EGP';
        if (!empty($validated['currency_id'])) {
            $currency = \App\Models\Currency::find($validated['currency_id']);
            $currencyCode = $currency->code;
        }

        $treasury = FinancialTreasury::create([
            'name' => $validated['name'],
            'type' => $validated['type'],
            'currency' => $currencyCode,
            'currency_id' => $validated['currency_id'] ?? null,
            'balance' => $validated['balance'],
            'is_active' => true,
        ]);

        return back()->with('success', 'Treasury created successfully.');
    }

    public function show(FinancialTreasury $treasury)
    {
        $transactions = $treasury->transactions()
            ->with(['user', 'category', 'model'])
            ->latest()
            ->paginate(20);

        return view('accounting.treasuries.show', compact('treasury', 'transactions'));
    }

    public function update(Request $request, FinancialTreasury $treasury)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:cash,bank,wallet',
        ]);

        $treasury->update($validated);
        return back()->with('success', 'Treasury updated successfully.');
    }
    use \App\Traits\HasLockCheck;

    public function storeTransfer(Request $request)
    {
        $validated = $request->validate([
            'from_treasury_id' => 'required|exists:financial_treasuries,id',
            'to_treasury_id' => 'required|exists:financial_treasuries,id|different:from_treasury_id',
            'amount' => 'required|numeric|min:1',
            'date' => 'required|date',
            'description' => 'nullable|string',
        ]);

        if ($this->isDateLocked($validated['date'])) {
            return back()->with('error', 'The transfer date is locked for accounting.')->withInput();
        }

        $from = FinancialTreasury::find($validated['from_treasury_id']);
        $to = FinancialTreasury::find($validated['to_treasury_id']);

        if ($from->balance < $validated['amount']) {
            return back()->with('error', 'Insufficient balance in source treasury.');
        }

        // Generate a Link ID
        $ref = 'TRF-' . time();

        // Outbound
        FinancialTransaction::create([
            'treasury_id' => $from->id,
            'user_id' => auth()->id(),
            'type' => 'out',
            'amount' => $validated['amount'],
            'date' => $validated['date'],
            'description' => 'Transfer to ' . $to->name . ($validated['description'] ? ' (' . $validated['description'] . ')' : ''),
            'ref_no' => $ref,
        ]);
        $from->decrement('balance', $validated['amount']);

        // Inbound
        FinancialTransaction::create([
            'treasury_id' => $to->id,
            'user_id' => auth()->id(),
            'type' => 'in',
            'amount' => $validated['amount'],
            'date' => $validated['date'],
            'description' => 'Transfer from ' . $from->name . ($validated['description'] ? ' (' . $validated['description'] . ')' : ''),
            'ref_no' => $ref,
        ]);
        $to->increment('balance', $validated['amount']);

        return back()->with('success', 'Transfer completed successfully.');
    }

    public function storeTransaction(Request $request)
    {
        $validated = $request->validate([
            'treasury_id' => 'required|exists:financial_treasuries,id',
            'type' => 'required|in:in,out',
            'amount' => 'required|numeric|min:1',
            'date' => 'required|date',
            'description' => 'required|string',
        ]);

        if ($this->isDateLocked($validated['date'])) {
            return back()->with('error', 'The transaction date is locked for accounting.')->withInput();
        }

        $treasury = FinancialTreasury::find($validated['treasury_id']);

        if ($validated['type'] == 'out' && $treasury->balance < $validated['amount']) {
            return back()->with('error', 'Insufficient balance for this expense.');
        }

        FinancialTransaction::create([
            'treasury_id' => $treasury->id,
            'user_id' => auth()->id(),
            'type' => $validated['type'],
            'amount' => $validated['amount'],
            'date' => $validated['date'],
            'description' => $validated['description'],
        ]);

        if ($validated['type'] == 'in') {
            $treasury->increment('balance', $validated['amount']);
        } else {
            $treasury->decrement('balance', $validated['amount']);
        }

        return back()->with('success', 'Transaction recorded successfully.');
    }

    public function printVoucher(FinancialTransaction $transaction)
    {
        $transaction->load(['treasury', 'user']);
        $settings = \App\Models\Setting::getGroup('general');
        return view('accounting.treasuries.print_voucher', compact('transaction', 'settings'));
    }
}
