<?php

namespace App\Http\Controllers\Store\Register;

use App\Helpers\DropdownListHelper;
use App\Helpers\UUIDHelper;
use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Rules\NationalNumber;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;

class RegisterController extends Controller
{
    use DropdownListHelper, UUIDHelper;

    /**
     * register seller
     */
    public function register(Request $request)
    {
        /** @var \App\Models\User $user */
        $user = auth()->user(); // store_register_status

        // check register status
        $storeRegisterStatus = Setting::where('key', 'store_register_status')->first();
        if ($storeRegisterStatus != null) {
            if ($storeRegisterStatus->value == 'false') {
                return redirect()->route('index');
            }
        }

        if ($user->type == 'owner') {
            return redirect()->route('index');
        }

        if ($user->store != null && $user->store->status != 'proccess') {
            return redirect()->route('seller.dashboard');
        }

        $store = null;
        if ($user->store != null && $user->store->status == 'proccess') {
            $store = $user->store;
        }

        return Inertia::render('Store/Register/Register', [
            'store' => $store,
            'companyType' => $this->companyType()
        ])->title(__('messages.title.sellers_register'));
    }

    /**
     * submit seller register form
     */
    public function submit(Request $request)
    {
        /** @var \App\Models\User $user */
        $user = auth()->user();

        // check register status
        $storeRegisterStatus = Setting::where('key', 'store_register_status')->first();
        if ($storeRegisterStatus != null) {
            if ($storeRegisterStatus->value == 'false') {
                return redirect()->route('index');
            }
        }

        if ($user->type == 'owner') {
            return redirect()->route('index');
        }

        if ($user->store != null && ($user->store->status == 'active' || $user->store->status == 'awaiting')) {
            return redirect()->route('seller.dashboard');
        }

        $request->validate([
            'level' => 'required',
            'type' => 'required',
        ]);

        if ($request->level == 'account-information') {
            if ($request->type == 'genuine') {
                $request->validate([
                    'store_name' => 'required',
                    'national_number' => ['required', 'string', new NationalNumber()],
                ]);

                // 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')]);
                    }
                }

                // update information
                if ($identityFileID != null) {
                    if ($user->store != null) {
                        $user->store->update([
                            'name' => $request->store_name,
                            'information' => serialize([
                                'national_number' => $request->national_number,
                                'national_card_image' => $identityFileID,
                            ]),
                            'type' => $request->type,
                            'status' => 'proccess',
                        ]);
                    } else {
                        $user->store()->create([
                            'uuid' => $this->generateUniqueRandomNumber(6, \App\Models\Product::class, 'uuid', 'store-'),
                            'name' => $request->store_name,
                            'meta' => serialize([]),
                            'information' => serialize([
                                'national_number' => $request->national_number,
                                'national_card_image' => $identityFileID,
                            ]),
                            'type' => $request->type,
                            'status' => 'proccess',
                        ]);
                    }
                } else {
                    return redirect()->back();
                }

                return redirect()->back()->with('message', [__('messages.account_information_saved')]);
            } else if ($request->type == 'legal') {
                $request->validate([
                    'store_name' => 'required',
                    'company_name' => 'required',
                    'company_type' => 'required',
                    'company_national_number' => 'required',
                    'company_signatory' => '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')]);
                    }
                }

                // update information
                if ($identityFileID != null) {
                    if ($user->store != null) {
                        $user->store->update([
                            'name' => $request->store_name,
                            'information' => serialize([
                                '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,
                            ]),
                            'type' => $request->type,
                            'status' => 'proccess',
                        ]);
                    } else {
                        $user->store()->create([
                            'uuid' => $this->generateUniqueRandomNumber(6, \App\Models\Product::class, 'uuid', 'store-'),
                            'name' => $request->store_name,
                            'meta' => serialize([]),
                            'information' => serialize([
                                '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,
                            ]),
                            'type' => $request->type,
                            'status' => 'proccess',
                        ]);
                    }
                } else {
                    return redirect()->back();
                }

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


        // check map status
        $mapStatus = Setting::where('key', 'map_status')->first();
        $mapStatus = $mapStatus != null ? $mapStatus->value : '0';
        // location
        if ($request->level == 'location') {
            if ($user->store == null) {
                return redirect()->back()->withErrors([__('messages.account_information_not_found')]);
            }

            $request->validate([
                'state' => 'required',
                'city' => 'required',
                'full_address' => 'required',
                'postal_code' => 'required',
            ]);

            // map status
            if ($mapStatus == '1') {
                $request->validate([
                    'map' => ['required', 'array']
                ]);

                if (!$request->has('map.selected') || !$request->map['selected']) {
                    return redirect()->back()->withErrors([__('messages.location_is_required')]);
                }
            }

            $information = unserialize($user->store->information);
            if ($mapStatus == '1') $information['map'] = $request->map;
            $information['address'] = [
                'state' => $request->state,
                'city' => $request->city,
                'full_address' => $request->full_address,
                'postal_code' => $request->postal_code,
            ];

            $user->store->update([
                'information' => serialize($information)
            ]);

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

        if ($request->level == 'submit') {
            if ($user->store == null) {
                return redirect()->route('seller.register');
            }

            $user->store->update([
                'status' => 'awaiting'
            ]);

            $user->update([
                'seller' => true,
            ]);

            return redirect()->route('seller.dashboard')->with('message', [__('messages.seller_register_submited')]);
        }

        return redirect()->route('seller.register');
    }
}
