<?php

namespace App\Http\Controllers\Dashboard\Admin;

use App\Models\User;
use App\Enum\UserRole;
use App\Models\Trader;
use App\Trait\FileUpload;
use App\Enum\TraderStatus;
use Illuminate\Http\Request;
use App\Enum\TraderExperience;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreTraderRequest;
use App\Models\TraderPerformance;
use App\Models\TraderSubscription;

class TraderController extends Controller
{
    use FileUpload;
    public function index()
    {
        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('admin.dashboard')],
            ['label' => 'Traders', 'active' => true]
        ];

        $traders = Trader::with(['user'])->latest()->get();

        $data = [
            'title' => 'Traders',
            'breadcrumbs' => $breadcrumbs,
            'traders' => $traders,
        ];

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

    public function create()
    {
        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('admin.dashboard')],
            ['label' => 'Traders', 'url' => route('admin.trader.index')],
            ['label' => 'Create Trader', 'active' => true]
        ];

        $users = User::where('role', UserRole::USER)->latest()->get();
        $traderStatus = TraderStatus::cases();
        $traderExperience = TraderExperience::cases();

        $data = [
            'title' => 'Create Trader',
            'breadcrumbs' => $breadcrumbs,
            'users' => $users,
            'traderStatus' => $traderStatus,
            'traderExperience' => $traderExperience,

        ];

        return view('dashboard.admin.trader.create', $data);
    }

    public function store(StoreTraderRequest $request)
    {

        // User is already a trader
        if (Trader::where('user_id', $request->user_id)->exists()) {
            return redirect()
                ->route('admin.trader.index')
                ->with('error', 'User is already a trader');
        }

        try {
            DB::transaction(function () use ($request) {

                $validated = $request->validated();

                $validated['image'] = $this->uploadFile($request, 'image', uploadPathAdmin('trader'));

                Trader::create($validated);
            });

            return redirect()
                ->route('admin.trader.index')
                ->with('success', 'Trader created successfully');
        } catch (\Throwable $e) {
            Log::error($e->getMessage());

            return redirect()
                ->back()
                ->with('error', 'Failed to create trader');
        }
    }

    public function show(string $uuid)
    {
        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('admin.dashboard')],
            ['label' => 'Traders', 'url' => route('admin.trader.index')],
            ['label' => 'Trader Details', 'active' => true]
        ];

        $trader = Trader::where('uuid', $uuid)->firstOrFail();

        $data = [
            'title' => 'Trader Details',
            'breadcrumbs' => $breadcrumbs,
            'trader' => $trader,
        ];

        return view('dashboard.admin.trader.show', $data);
    }

    public function edit(string $uuid)
    {
        $breadcrumbs = [
            ['label' => config('app.name'), 'url' => '/'],
            ['label' => 'Dashboard', 'url' => route('admin.dashboard')],
            ['label' => 'Traders', 'url' => route('admin.trader.index')],
            ['label' => 'Edit Trader', 'active' => true]
        ];

        $users = User::where('role', UserRole::USER)->latest()->get();
        $traderStatus = TraderStatus::cases();
        $traderExperience = TraderExperience::cases();

        $trader = Trader::where('uuid', $uuid)->firstOrFail();

        $data = [
            'title' => 'Edit Trader',
            'breadcrumbs' => $breadcrumbs,
            'users' => $users,
            'traderStatus' => $traderStatus,
            'traderExperience' => $traderExperience,
            'trader' => $trader,
        ];

        return view('dashboard.admin.trader.edit', $data);
    }

    public function update(StoreTraderRequest $request, string $uuid)
    {
        try {
            $trader = Trader::where('uuid', $uuid)->firstOrFail();

            DB::transaction(function () use ($request, $trader) {

                $validated = $request->validated();

                $validated['image'] = $this->updateFile($request, 'image', uploadPathAdmin('trader'), $trader?->image);

                $trader->update($validated);
            });

            return redirect()
                ->route('admin.trader.index')
                ->with('success', 'Trader updated successfully');
        } catch (\Throwable $e) {
            Log::error($e->getMessage());

            return redirect()
                ->back()
                ->with('error', 'Failed to update trader');
        }
    }

    public function delete(string $uuid)
    {
        // Cannot delete a trader that has a performance
        $trader = Trader::where('uuid', $uuid)->firstOrFail();
        if (TraderPerformance::where('trader_id', $trader->id)->exists()) {
            return redirect()
                ->route('admin.trader.index')
                ->with('error', 'Cannot delete a trader that has a performance');
        }

        try {
            $trader = Trader::where('uuid', $uuid)->firstOrFail();

            DB::transaction(function () use ($trader) {
                $this->deleteFile($trader->image);

                $trader->delete();
            });

            return redirect()
                ->route('admin.trader.index')
                ->with('success', 'Trader deleted successfully');
        } catch (\Throwable $e) {
            Log::error($e->getMessage());

            return redirect()
                ->back()
                ->with('error', 'Failed to delete trader');
        }
    }
}
