<?php

namespace Daylight\Core\Http\Controllers\Settings;

use Daylight\Core\Http\Controllers\Controller;
use Daylight\Core\Http\Requests\Settings\Countries\StoreCountryRequest;
use Daylight\Core\Http\Requests\Settings\Countries\UpdateCountryRequest;
use Daylight\Core\Models\Country;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\Support\Facades\Cache;
use PeterColes\Countries\CountriesFacade;

class CountryController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:update:settings', only: ['create', 'store', 'update', 'destroy']),
            new Middleware('can:read:settings', only: ['index', 'show', 'edit']),
        ];
    }

    public function index()
    {
        return view('daylight::settings.countries.index');
    }

    public function create()
    {
        $taxClasses = (daylightModel('tax_class'))::all()->map(function ($taxClass) {
            return [
                'taxClass' => $taxClass,
                'taxRate' => null,
            ];
        });

        return view('daylight::settings.countries.create', [
            'countries' => CountriesFacade::lookup(),
            'taxClasses' => $taxClasses,
        ]);
    }

    public function store(StoreCountryRequest $request)
    {
        if ($request->get('default') == 1) {
            (daylightModel('country'))::where('default', 1)->update(['default' => 0]);
        }

        $country = (daylightModel('country'))::create($request->safe()->only('code', 'default'));

        collect($request->get('taxRates'))->map(function ($taxRate, $taxClassId) use ($country) {
            $country->taxRates()->updateOrCreate(
                ['tax_class_id' => $taxClassId],
                [
                    'rate' => $taxRate['rate'],
                    'name' => $taxRate['name'] ?? 'VAT',
                ]
            );
        });

        Cache::forget('countries');

        return redirect()
            ->route('daylight.settings.countries.edit', $country)
            ->with('success', __('Country created'));
    }

    public function edit(Country $country)
    {
        $country->loadMissing('taxRates');

        $taxClasses = (daylightModel('tax_class'))::all()->map(function ($taxClass) use ($country) {
            return [
                'taxClass' => $taxClass,
                'taxRate' => $country->taxRates->firstWhere('tax_class_id', $taxClass->id),
            ];
        });

        return view('daylight::settings.countries.edit', [
            'countries' => CountriesFacade::lookup(),
            'country' => $country,
            'taxClasses' => $taxClasses,
        ]);
    }

    public function update(UpdateCountryRequest $request, Country $country)
    {
        if ($request->get('default') == 1) {
            (daylightModel('country'))::where('default', 1)->update(['default' => 0]);
        }

        $country->update($request->safe()->only('code', 'default'));

        collect($request->get('taxRates'))->map(function ($taxRate, $taxClassId) use ($country) {
            $country->taxRates()->updateOrCreate(
                ['tax_class_id' => $taxClassId],
                [
                    'rate' => $taxRate['rate'],
                    'name' => $taxRate['name'] ?? 'VAT',
                ]
            );
        });

        Cache::forget('countries');

        return redirect()
            ->route('daylight.settings.countries.index')
            ->with('success', __('Country updated'));
    }

    public function destroy(Country $country)
    {
        $country->delete();

        Cache::forget('countries');

        return redirect()
            ->route('daylight.settings.countries.index')
            ->with('success', __('Country deleted'));
    }
}
