<?php

namespace App\Http\Controllers;

use App\Models\Account;
use App\Models\Currency;
use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\DB;

class SetupController extends Controller
{
    public function dashboard()
    {
        $dailyProfits = \App\Models\Transaction::selectRaw('DATE(created_at) as date, SUM(total_profit) as total_profit')
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        $currencyDistribution = \App\Models\Transaction::selectRaw('currency_id, COUNT(id) as count')
            ->with('currency')
            ->groupBy('currency_id')
            ->get();

        return view('dashboard', [
            'currencyCount' => Currency::count(),
            'accountCount' => Account::count(),
            'stockCount' => Currency::get()->filter(fn($c) => $c->stock > 0)->count(),
            'dailyProfits' => $dailyProfits,
            'currencyDistribution' => $currencyDistribution,
        ]);
    }

    public function stockDashboard(Request $request)
    {
        $filters = $request->validate([
            'search' => ['nullable', 'string', 'max:50'],
        ]);

        $currencies = Currency::query()
            ->when(! empty($filters['search']), fn ($query) => $query->where(fn ($inner) => $inner
                ->where('code', 'like', '%' . $filters['search'] . '%')
                ->orWhere('name', 'like', '%' . $filters['search'] . '%')))
            ->orderBy('code')
            ->get();

        return view('stock.dashboard', compact('currencies', 'filters'));
    }

    public function openingBalances()
    {
        $accounts = Account::with('currency')->orderBy('name')->get();

        return view('setup.opening-balances', compact('accounts'));
    }

    public function updateOpeningBalances(Request $request)
    {
        $data = $request->validate([
            'balances' => ['array'],
            'balances.*' => ['required', 'numeric', 'min:0'],
        ]);

        DB::transaction(function () use ($data) {
            foreach ($data['balances'] ?? [] as $accountId => $balance) {
                $account = Account::lockForUpdate()->find($accountId);
                
                if (! $account) {
                    throw ValidationException::withMessages([
                        "balances.$accountId" => 'One of the selected accounts no longer exists.',
                    ]);
                }

                $diff = (float) $balance - (float) $account->balance;

                if ($diff > 0) {
                    // Record virtual buy transaction for the addition
                    Transaction::create([
                        'type' => Transaction::TYPE_OPENING_BALANCE,
                        'currency_id' => $account->currency_id,
                        'quantity' => $diff,
                        'rate' => 0,
                        'payment_amount' => 0,
                        'payment_currency_id' => null,
                        'handling_fee' => 0,
                        'fee_currency' => 'LKR',
                        'account_id' => $account->id,
                        'agent_id' => null,
                        'exchange_profit' => 0,
                        'total_profit' => 0,
                    ]);
                }

                $account->update(['balance' => $balance]);
            }
        });

        return redirect()
            ->route('setup.opening-balances')
            ->with('success', 'Opening balances updated successfully.');
    }
}
