<?php

namespace App\Http\Controllers;

use App\Enums\UserRole;
use App\Enums\UserStatus;
use App\Http\Controllers\Concerns\ManagesPartnerUploads;
use App\Http\Requests\PromoterRequest;
use App\Models\Promoter;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class PromoterController extends Controller
{
    use ManagesPartnerUploads;

    private const PROFILE_FIELDS = [
        'applicant_name', 'designation', 'building', 'street', 'city', 'state', 'postal_code',
        'country', 'email', 'phone', 'institute_name', 'firm_type', 'official_building',
        'official_street', 'official_city', 'official_state', 'official_postal_code',
        'official_country', 'official_email', 'official_phone', 'operational_area',
        'experience', 'second_contact_name', 'second_contact_email', 'second_contact_phone',
    ];

    public function index(): View
    {
        $this->authorize('viewAny', Promoter::class);

        $promoters = Promoter::with('user')
            ->withCount('authorisedPartners')
            ->latest()
            ->paginate(15);
        $page_title = 'Promoters';
        $page_description = 'Manage promoters';

        return view('iqec.promoters.index', compact('promoters', 'page_title', 'page_description'));
    }

    public function create(): View
    {
        $this->authorize('create', Promoter::class);

        $page_title = 'Add Promoter';
        $page_description = 'Create a promoter account';

        return view('iqec.promoters.create', compact('page_title', 'page_description'));
    }

    public function store(PromoterRequest $request): RedirectResponse
    {
        DB::transaction(function () use ($request) {
            $user = User::create([
                'name' => $request->applicant_name,
                'email' => $request->email,
                'password' => $request->password,
                'role' => UserRole::Promoter,
                'status' => UserStatus::Pending,
            ]);

            $data = $this->storePartnerUploads($request, $request->only(self::PROFILE_FIELDS));
            $data['user_id'] = $user->id;

            $promoter = Promoter::create($data);
            $promoter->superAdmins()->attach($request->user()->id);
        });

        return redirect()->route('promoters.index')->with('success', 'Promoter created and is pending approval.');
    }

    public function show(Promoter $promoter): View
    {
        $this->authorize('view', $promoter);

        $promoter->load('user', 'superAdmins', 'authorisedPartners.user');
        $page_title = 'Promoter Details';
        $page_description = $promoter->applicant_name;

        return view('iqec.promoters.show', compact('promoter', 'page_title', 'page_description'));
    }

    public function authorisedPartners(Request $request, Promoter $promoter): View
    {
        $this->authorize('view', $promoter);
        abort_unless($request->ajax(), 404);

        $partners = $promoter->authorisedPartners()
            ->with('user')
            ->latest()
            ->paginate(10);

        return view('iqec.promoters.partials.authorised-partners-list', compact('promoter', 'partners'));
    }

    public function edit(Promoter $promoter): View
    {
        $this->authorize('update', $promoter);

        $page_title = 'Edit Promoter';
        $page_description = $promoter->applicant_name;

        return view('iqec.promoters.edit', compact('promoter', 'page_title', 'page_description'));
    }

    public function update(PromoterRequest $request, Promoter $promoter): RedirectResponse
    {
        $this->authorize('update', $promoter);

        DB::transaction(function () use ($request, $promoter) {
            $userData = [
                'name' => $request->applicant_name,
                'email' => $request->email,
            ];
            if ($request->filled('password')) {
                $userData['password'] = $request->password;
            }
            $promoter->user->update($userData);

            $data = $this->storePartnerUploads(
                $request,
                $request->only(self::PROFILE_FIELDS),
                $promoter->photo_path,
                $promoter->id_proof_path
            );
            $promoter->update($data);
        });

        return redirect()->route('promoters.index')->with('success', 'Promoter updated.');
    }

    public function destroy(Promoter $promoter): RedirectResponse
    {
        $this->authorize('delete', $promoter);

        $promoter->user->delete();

        return redirect()->route('promoters.index')->with('success', 'Promoter deleted.');
    }

    public function approve(Promoter $promoter): RedirectResponse
    {
        $this->authorize('approve', $promoter);

        $promoter->user->update(['status' => UserStatus::Approved]);

        return back()->with('success', 'Promoter approved. They can now log in.');
    }

    public function reject(Promoter $promoter): RedirectResponse
    {
        $this->authorize('approve', $promoter);

        $promoter->user->update(['status' => UserStatus::Rejected]);

        return back()->with('success', 'Promoter rejected.');
    }
}
