<?php

namespace App\Http\Controllers\Store\Transportation;

use App\Helpers\CommonFunctionsHelper;
use App\Helpers\DropdownListHelper;
use App\Helpers\Places;
use App\Http\Controllers\Controller;
use App\Models\PaymentMeta;
use Illuminate\Http\Request;
use Inertia\Inertia;

class TransportationController extends Controller
{
    use CommonFunctionsHelper, Places, DropdownListHelper;

    /**
     * transportation
     */
    public function index()
    {
        /** @var \App\Models\User $user */
        $user = auth()->user();
        $store = $user->store;

        $paymentMeta = $store->paymentMeta;

        // validate payment meta model
        if ($paymentMeta == null) {
            $paymentMeta = $store->paymentMeta()->create([
                'post_ways' => serialize([]),
                'receive_in_person_period' => null,
                'free_post_min_price' => null,
            ]);
        }

        return Inertia::render('Store/Transportation/List', [
            'places' => $this->places(),
            'abandonedCartTimePeriodList' => $this->abandonedCartTimePeriod(),
            'paymentMeta' => $paymentMeta,
        ]);
    }

    /**
     * update transportation
     */
    public function update(Request $request)
    {
        $request->validate([
            'post_ways' => 'required'
        ]);

        /** @var \App\Models\User $user */
        $user = auth()->user();
        $store = $user->store;

        $paymentMeta = $store->paymentMeta;

        if ($paymentMeta != null) {
            $paymentMeta->update([
                'post_ways' => serialize($request->post_ways),
                'receive_in_person_period' => serialize($request->receive_in_person_period),
                'free_post_min_price' => $request->exists('free_post_min_price') && $request->free_post_min_price != null ? str_replace(',', '', $request->free_post_min_price) : 0,
            ]);
        } else {
            return redirect()->back()->withErrors([__('messages.unknown_error')]);
        }

        /** Report Action */
        $this->report(__("messages.report_payment_meta_edited"));

        redirect()->back()->with('message', [__('messages.transportation_settings_updated')]);
    }
}
