<?php

namespace App\Http\Controllers;

use App\Models\Store;
use App\Http\Requests\StoreStoreRequest;
use App\Http\Requests\UpdateStoreRequest;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Storage;

class StoreController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return inertia('Store/Index', [
            'user' => User::query()->with('store')->where('id', Auth::user()->id)->first(),
            'store' => Store::query()->where('user_id', Auth::user()->id)->first(),
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return inertia('Store/Create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreStoreRequest $request)
    {
        $file = null;
        
        if ($request->logo) {
            $image = explode('base64,', $request->logo);
            $image = end($image);
            $image = str_replace(' ', '+', $image);
            $file = Auth::user()->name . uniqid() . '.jpg';

            $result = Storage::disk('public')->put("store/" . $file, base64_decode($image));
            if (!$result) {
                return Redirect::back()->with('error', 'Image upload failed, please try again');
            }
        }

        Store::create([
            'name' => $request->name,
            'description' => $request->description,
            'logo' => $file,
            'user_id' => Auth::user()->id,
        ]);

        return to_route('store.index');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Store $store)
    {
        return inertia('Store/Edit', [
            'store' => $store,
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateStoreRequest $request, Store $store)
    {
        if ($request->logo) {
            $image = explode('base64,', $request->logo);
            $image = end($image);
            $image = str_replace(' ', '+', $image);
            $file = Auth::user()->name . uniqid() . '.jpg';

            $result = Storage::disk('public')->put("store/" . $file, base64_decode($image));
            if (!$result) {
                return Redirect::back()->with('error', 'Image upload failed, please try again');
            }

            $store->update([
                'name' => $request->name,
                'description' => $request->description,
                'logo' => $file,
                'user_id' => Auth::user()->id,
            ]);
        } else {
            $store->update([
                'name' => $request->name,
                'description' => $request->description,
                'user_id' => Auth::user()->id,
            ]);
        }

        return to_route('store.index');
    }
}
