<?php

namespace App\Http\Controllers\Store\Account;

use App\Helpers\DropdownListHelper;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Inertia\Response;

class InformationsController extends Controller
{
    use DropdownListHelper;

    /**
     * edit store information
     */
    public function edit(Request $request): Response
    {
        /** @var App\Models\User $user */
        $user = auth()->user();
        $store = $user->store;

        return Inertia::render('Store/Account/Information', [
            'store' => [
                'id' => $store->id,
                'name' => $store->name,
                'bio' => $store->bio,
                'logo' => $store->logo,
                'get_logo' => $store->get_logo,
                'get_meta' => $store->get_meta,
                'get_information' => $store->get_information,
                'type' => $store->type,
                'status' => $store->status,
                'jalali_created_at' => $store->jalali_created_at,
                'jalali_updated_at' => $store->jalali_updated_at,
            ],
            'companyType' => $this->companyType()
        ]);
    }

    /**
     * update store information
     */
    public function update(Request $request)
    {
        /** validation */
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
        ]);

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

        $name = $store->name;
        $information = unserialize($store->information);

        if ($store->status != 'active' && $store->status != 'banned') {
            $name = $request->name;
            $information = null;
            if ($store->type == 'legal') {
                $request->validate([
                    'company_name' => 'required',
                    'company_type' => 'required',
                    'company_national_number' => 'required',
                    'company_signatory' => 'required',
                    'map' => 'required',
                    'state' => 'required',
                    'city' => 'required',
                    'full_address' => 'required',
                    'postal_code' => 'required',
                ]);

                // upload image
                $identityFileID = null;
                if ($user->store != null && array_key_exists('legal_identity_image', $user->store->get_information) && $user->store->get_information['legal_identity_image'] != null && $request->legal_identity_image == null) {
                    $identityFileID = $user->store->get_information['legal_identity_image'];
                } else {
                    $request->validate([
                        'legal_identity_image' => 'required|image|mimes:jpg,jpeg,png|max:2048',
                    ]);

                    $identityFileID = null;
                    $file = $request->file('legal_identity_image');
                    $fileName = 'file.' . time() . '.' . rand(10000, 99999) . '.' . $file->getClientOriginalExtension();
                    $fileSize = floor($file->getSize() / 1000);
                    $imageResolution = getimagesize($file)[0] . '×' . getimagesize($file)[1];
                    $fileSaveAddress = 'identity/' . date('Y-m-d') . '/' . $user->id . '/' . $fileName;
                    $uploadResult = '/' . Storage::putFileAs('private_media', $file, $fileSaveAddress);
                    if ($uploadResult) {
                        $identityFileID = $user->files()->create([
                            'name' => $fileName,
                            'url' => $uploadResult,
                            'description' => __('messages.sentence.document_image_of', ['name' => $user->get_name]),
                            'extension' => $file->getClientOriginalExtension(),
                            'size' => $fileSize,
                            'resolution' => $imageResolution,
                            'type' => 'image',
                            'visibility' => 'private',
                        ]);

                        $identityFileID = $identityFileID->id;
                    } else {
                        return redirect()->back()->withErrors([__('messages.error_while_uploading_image')]);
                    }
                }

                $information = [
                    'company_name' => $request->company_name,
                    'company_type' => $request->company_type,
                    'company_national_number' => $request->company_national_number,
                    'company_economic_number' => $request->exists('company_economic_number') ? $request->company_economic_number : null,
                    'company_signatory' => $request->company_signatory,
                    'legal_identity_image' => $identityFileID,
                    'map' => $request->map,
                    'address' => [
                        'state' => $request->state,
                        'city' => $request->city,
                        'full_address' => $request->full_address,
                        'postal_code' => $request->postal_code,
                    ]
                ];
            } else if ($store->type == 'genuine') {
                $request->validate([
                    'national_number' => 'required',
                    'map' => 'required',
                    'state' => 'required',
                    'city' => 'required',
                    'full_address' => 'required',
                    'postal_code' => 'required',
                ]);

                // upload image
                $identityFileID = null;
                if ($user->store != null && array_key_exists('national_card_image', $user->store->get_information) && $user->store->get_information['national_card_image'] != null && $request->national_card_image == null) {
                    $identityFileID = $user->store->get_information['national_card_image'];
                } else {
                    $request->validate([
                        'national_card_image' => 'required|image|mimes:jpg,jpeg,png|max:2048',
                    ]);

                    $file = $request->file('national_card_image');
                    $fileName = 'file.' . time() . '.' . rand(10000, 99999) . '.' . $file->getClientOriginalExtension();
                    $fileSize = floor($file->getSize() / 1000);
                    $imageResolution = getimagesize($file)[0] . '×' . getimagesize($file)[1];
                    $fileSaveAddress = 'identity/' . date('Y-m-d') . '/' . $user->id . '/' . $fileName;
                    $uploadResult = '/' . Storage::putFileAs('private_media', $file, $fileSaveAddress);
                    if ($uploadResult) {
                        $identityFileID = $user->files()->create([
                            'name' => $fileName,
                            'url' => $uploadResult,
                            'description' => __('messages.sentence.document_image_of', ['name' => $user->get_name]),
                            'extension' => $file->getClientOriginalExtension(),
                            'size' => $fileSize,
                            'resolution' => $imageResolution,
                            'type' => 'image',
                            'visibility' => 'private',
                        ]);

                        $identityFileID = $identityFileID->id;
                    } else {
                        return redirect()->back()->withErrors([__('messages.error_while_uploading_image')]);
                    }
                }

                $information = [
                    'national_number' => $request->national_number,
                    'national_card_image' => $identityFileID,
                    'map' => $request->map,
                    'address' => [
                        'state' => $request->state,
                        'city' => $request->city,
                        'full_address' => $request->full_address,
                        'postal_code' => $request->postal_code,
                    ]
                ];
            }
        }

        $store->update([
            'name' => $name,
            'bio' => $request->exists('bio') ? $request->bio : $store->bio,
            'logo' => $request->exists('logo') ? $request->logo : $store->logo,
            'information' => serialize($information),
            'status' => $store->status != 'active' && $store->status != 'banned' ? 'awaiting' : $store->status
        ]);

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