<?php

namespace App\Http\Controllers;

use App\Actions\Fortify\UpdateUserProfileInformation;
use App\Http\Helpers\FileUploader;
use App\Http\Helpers\UploadedFiles;
use App\Models\Firm;
use App\Models\FirmSize;
use App\Models\User;
use App\Notifications\CompleteRegistration;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Laravel\Jetstream\Jetstream;
use Rinvex\Categories\Models\Category;

class
FirmController extends Controller
{

    public function show($slug = null)
    {


        $slug = $slug ?? Auth::user()->firm?->slug;
        $firm = Firm::with('user', 'location', 'FirmSize', 'licenses',
            'skills', 'FirmType', 'portfolioProjects.skills',
            'portfolioProjects.images', 'phone', 'workRates.rateable', 'workRates.user')->where('slug', $slug)->firstOrFail();


        return Inertia::render('Dashboard/Firm/Index', [
            'firm' => $firm,
        ]);

    }

    public function settings()
    {
        $slug = Auth::user()->firm?->slug;
        $categories = Category::where('parent_id', null)->with('descendants')->get();
        $firmSize = FirmSize::all();
        $firm = Firm::with('user', 'location', 'FirmSize', 'licenses',
            'skills', 'FirmType', 'portfolioProjects.skills',
            'portfolioProjects.images', 'phone', 'rates')->where('slug', $slug)->firstOrFail();
        return Inertia::render('Settings/Firm/Show', [
            'firm' => $firm,
            'firmSize' => $firmSize,
            // 'languages' => $languages,
            // 'proficiencies' => $proficiencies,
            'categories' => $categories,
        ]);

    }

    public function index(Request $request)
    {
        if($request->has('search')){
            return Firm::search($request->search)->paginate(20);
        }
        return Firm::paginate(20);
    }

    public function store(Request $request)
    {
        try {
            $transaction = DB::transaction(function () use ($request) {
                $attr = $this->validateFirmRequest($request);
                $user = User::create([
                    "name" => $request->name,
                    "email" => $request->email,
                ]);

                //create the firm request
                $firm = Firm::create(array_merge(
                    $attr, [
                        'commercial_registration_path' => $request->has('commercial_registration_licence')? FileUploader::store('commercial_registration_licences/', $request->file('commercial_registration_licence')):null,
                        'company_profile_path' => $request->has('company_profile')? FileUploader::store('company_profiles/', $request->file('company_profile')):null,
                        'owner_id_path' =>$request->has('owner_id')?  FileUploader::store('owner_ids/', $request->file('owner_id')):null,
                        'contact_person_id_path' =>$request->has('contact_person_id')?  FileUploader::store('contact_person_ids/', $request->file('contact_person_id')):null,
                        'user_id' => $user->id,
                    ]
                ));


                $firm->addLocation($request->location);


                $firm->skills()->attach($request->skills);

                if ($request->has('social_links')){
                    $firm->addSocials($request->social_links);
                }

                $firm->categories()->attach($request->sub_categories);
                $firm->categories()->attach($request->categories);
                $firm->addCurrency(1);
                $firm->addPhone($request->phone);
                if($user->wallet !=null){
                    $wallet= $user->wallet;
                    $wallet->update([
                        'owner_id'=>$firm->id,
                        'owner_type'=> 'App\Models\Firm'
                    ]);
                    $user->wallet()->delete();
                    $user->save();
                    $wallet->save();
                }else{
                    $firm->wallet()->create();
                }
                $firm->save();

                $firm->searchable();
                $firm->notify(new CompleteRegistration(Crypt::encryptString($firm->email),'firm'));
                return $firm;
            });
            return !is_null($transaction) ? redirect()->route('complete.registration', [
                'type' => 'firm',
                'id' => Crypt::encryptString($transaction->email)
            ]) : $transaction;        } catch (Exception $exception) {
            return redirect()->back()->withErrors(['error' => $exception->getMessage()])->with(["error" => $exception->getMessage()]);
        }
    }

    protected function validateFirmRequest(Request $request, ?bool $update = false): array
    {
        $request->validate([
            'skills' => [$update ? 'nullable' : 'required', 'array'],
            'skills.*' => [$update ? 'nullable' : 'required', 'integer', Rule::exists('skills', 'id')],
            'commercial_registration' => UploadedFiles::getRules(true),
            'company_profile' => UploadedFiles::getRules(true),
            'owner_id' => UploadedFiles::getRules(true),
            'contact_person_id' => UploadedFiles::getRules(true),
            'social_links' => $update ? 'nullable' : 'required|array',
            'sub_categories' => [$update ? 'nullable' : 'required', 'array'],
            'sub_categories.*' => ['integer', Rule::exists('categories', 'id')],
            'location.long' => $update ? 'nullable' : 'required',
            'location.lat' => $update ? 'nullable' : 'required',
            'location.address' => $update ? 'nullable' : 'required',
            'phone.number' => $update ? 'nullable' : 'required',
            'phone.code' => $update ? 'nullable' : 'required'
        ]);
        return $request->validate([
            'name' => $update ? 'nullable' : 'required|string',
            'email' => $update ? 'nullable' : 'required|unique:firms,email|email|unique:users,email',
            'website' =>  'nullable',
            'about' => $update ? 'nullable' : 'required',
            'tag_line' => 'nullable',
            'slug' => 'nullable',
            'commercial_registration_number' => $update ? 'nullable' : 'required',
            'firm_type_id' => [$update ? 'nullable' : 'required', Rule::exists('firm_types', 'id')],
            'firm_size_id' => [$update ? 'nullable' : 'required', Rule::exists('firm_sizes', 'id')],
            'category_id' => ['nullable'],
        ]);
    }

    public function addPortfolioProject(Request $request)
    {
        $firm = Auth::user()->firm;
        return $firm->createPortfolio($request);
    }

    public function update(Request $request)
    {
        $firm = Auth::user()->firm;
        // dd($request->all());
        // dd($firm->categories);
        try {
            $transaction = DB::transaction(function () use ($request, $firm) {
                $attrs = $this->validateFirmRequest($request, true);


                // if ($request->has('category_id')) {
                //     $cats[] =  $request->category_id;
                // }

                if ($request->has('sub_categories')) {
                    $firm->categories()->sync(
                        $request->sub_categories
                    );
                }

                if ($request->has('skills')) {
                    $firm->skills()->sync($request->skills);
                }

                if ($request->has('location')) {
                    $firm->addLocation($request->location);
                }

                if ($request->has('phone')) {
                    $firm->addPhone($request->phone);
                }
                if ($request->has('social_links')) {
                    $firm->addSocials($request->social_links);
                }
                if ($request->hasFile('commercial_registration_licence')) {
                    $attrs['commercial_registration_path'] = FileUploader::store('commercial_registration_licences/', $request->file('commercial_registration'));
                }
                if ($request->hasFile('company_profile')) {
                    $attrs['company_profile_path'] = FileUploader::store('company_profiles/', $request->file('company_profile'));
                }
                if ($request->hasFile('owner_id')) {
                    $attrs['owner_id_path'] = FileUploader::store('owner_ids/', $request->file('owner_id'));
                }
                if ($request->hasFile('contact_person_id')) {
                    $attrs['contact_person_id_path'] = FileUploader::store('contact_person_ids/', $request->file('contact_person_id'));
                }

                if($request->hasFile('photo')){
                    $firm->user->forceFill([
                        'profile_photo_path' => FileUploader::store('photos/', $request->file('photo')),
                    ])->save();
                }

                if($request->hasFile('cover_photo')){
                    $firm->user->forceFill([
                        'cover_photo_path' => FileUploader::store('photos/', $request->file('cover_photo')),
                    ])->save();
                }

                $firm->update(
                    $attrs
                );
                $usrData=[];
                if($request->email){
                    $usrData['email']=$request->email;
                }
                if($request->name){
                    $usrData['name']=$request->name;
                }
                if($request->tag_line){
                    $usrData['tag_line']=$request->tag_line;
                }
                UpdateUserProfileInformation::updateUser(Auth::user(),$usrData);
                $firm->searchable();

            });
            return is_null($transaction) ? back(303)->with(['success' => 'success']) : $transaction;
        } catch (Exception $exception) {
            return redirect()->back()->withErrors(['error' => $exception->getMessage()])->with(["error" => $exception->getMessage()]);
        }
    }

    public function destroy(Firm $firm)
    {
        $firm->delete();
        return back(303)->with(['success' => 'success']);
    }

}
