<?php

namespace App\Http\Controllers\Dashboard\Admin;

use Carbon\Carbon;
use App\Models\User;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use App\Http\Requests\UserAccountStatementStoreRequest;

class UserAccountStatementController extends Controller
{
    public function index(string $uuid)
    {
        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('admin.dashboard')],
            ['label' => 'Users', 'url' => route('admin.user.index')],
            ['label' => 'Account Statement', 'active' => true],
        ];

        $user = User::where('uuid', $uuid)->firstOrFail();
        $transactions = $user->transaction()->with(['user'])->latest()->get();

        $data = [
            'title' => 'Account Statement',
            'breadcrumbs' => $breadcrumbs,
            'user' => $user,
            'transactions' => $transactions
        ];

        return view('dashboard.admin.user.account_statement.index', $data);
    }

    public function store(UserAccountStatementStoreRequest $request, string $uuid)
    {
        $request->validated();

        try {
            $user = User::where('uuid', $uuid)->firstOrFail();

            $transactions = $user->transaction()
                ->whereBetween('transaction_at', [$request->from, $request->to])
                ->get();

            if ($transactions->isNotEmpty()) {
                return redirect()->route('admin.user.account_statement.show', [
                    $user->uuid,
                    $request->from,
                    $request->to
                ])->with('success', 'Account statement generated successfully.');
            }

            return redirect()->back()->with('warning', 'No transactions found for the selected date range. Please try a different period.');
        } catch (\Throwable $e) {
            Log::error('Account statement generation failed: ' . $e->getMessage());

            return redirect()->back()->with('error', 'An unexpected error occurred while generating the account statement. Please try again later.');
        }
    }

    public function show(string $uuid, string $from, string $to)
    {
        try {
            $breadcrumbs = [
                ['label' => config('app.name'), 'url' => '/'],
                ['label' => 'Dashboard', 'url' => route('admin.dashboard')],
                ['label' => 'Users', 'url' => route('admin.user.index')],
                ['label' => 'Account Statement', 'active' => true],
            ];

            $user = User::where('uuid', $uuid)->firstOrFail();

            $transactions = $user->transaction()
                ->whereBetween('transaction_at', [$from, $to])
                ->orderBy('transaction_at', 'desc')
                ->get();

            $totalAmount = $transactions->sum('amount');

            if ($transactions->isEmpty()) {
                return redirect()
                    ->route('admin.user.account_statement.index', $user->uuid)
                    ->with('warning', 'No transactions found for the selected period.');
            }

            $data = [
                'title' => 'Account Statement for ' . $user->name,
                'breadcrumbs' => $breadcrumbs,
                'user' => $user,
                'from' => $from,
                'to' => $to,
                'transactions' => $transactions,
                'totalAmount' => $totalAmount,
            ];

            return view('dashboard.admin.user.account_statement.show', $data);
        } catch (\Throwable $e) {
            Log::error('Error displaying account statement: ' . $e->getMessage());

            return redirect()
                ->route('admin.user.account_statement.index', $user->uuid)
                ->with('error', 'An error occurred while loading the account statement. Please try again later.');
        }
    }

    public function download(string $uuid, string $from, string $to)
    {
        try {
            $user = User::where('uuid', $uuid)->firstOrFail();

            $transactions = $user->transaction()
                ->whereBetween('transaction_at', [$from, $to])
                ->orderBy('transaction_at', 'desc')
                ->get();

            $totalAmount = $transactions->sum('amount');

            if ($transactions->isEmpty()) {
                return redirect()
                    ->route('admin.user.account_statement.index', $user->uuid)
                    ->with('warning', 'No transactions found for the selected period.');
            }

            $data = [
                'title' => 'Account Statement for ' . $user->name,
                'user' => $user,
                'from' => $from,
                'to' => $to,
                'transactions' => $transactions,
                'totalAmount' => $totalAmount,
            ];

            $name = 'Statement_' . $user->account_number . '_' . Carbon::parse($from)->format('dMy') . '_to_' . Carbon::parse($to)->format('dMy');

            $pdf = Pdf::loadView('pdf.account_statement', $data)->setPaper('A4', 'portrait');

            return match (config('app.env')) {
                'production' => $pdf->download($name),
                default => $pdf->stream($name),
            };
        } catch (\Throwable $e) {
            Log::error('Error downloading account statement: ' . $e->getMessage());

            return redirect()
                ->route('admin.user.account_statement.show', [$user->uuid, $from, $to])
                ->with('error', 'An error occurred while downloading the account statement. Please try again later.');
        }
    }
}
