<?php

namespace App\Http\Controllers\Admin\Config\Layout;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Config;
use App\Models\FileLib;

class LogoController extends Controller
{
    private Config $configModel;

    public function __construct(Config $config)
    {
        $this->configModel = $config;
    }

    /**
     * 로고
     * @method GET
     * @see /admin/config/layout/logo
     */
    public function index()
    {
        return view('admin.config.layout.logo', []);
    }

    /**
     * 로고 저장
     * @method POST
     * @see /admin/config/layout/logo
     */
    public function store(Request $request, FileLib $fileLib)
    {
        $rules = [
            'site_favicon' => 'mimes:ico|max:1192',
            'site_logo' => 'mimes:jpg,jpeg,gif,png|max:2192'
        ];

        $attributes = [
            'site_favicon' => '사이트 파비콘',
            'site_logo' => '사이트 로고',
        ];

        $this->validate($request, $rules, [], $attributes);

        // 파일 저장
        $storage = (UPLOAD_PATH_STORAGE . DIRECTORY_SEPARATOR);
        $updateData = [];
        if($request->hasFile('site_favicon')) {
            $siteFavicon = $request->file('site_favicon');
            $siteFavicon->store(UPLOAD_PATH_PUBLIC . DIRECTORY_SEPARATOR . UPLOAD_PATH_FAVICON);
            $updateData['site_favicon'] = ($storage . UPLOAD_PATH_FAVICON . DIRECTORY_SEPARATOR . $siteFavicon->hashName());
        }
        if($request->hasFile('site_logo')) {
            $siteLogo = $request->file('site_logo');
            $siteLogo->store(UPLOAD_PATH_PUBLIC . DIRECTORY_SEPARATOR . UPLOAD_PATH_LOGO);
            $updateData['site_logo'] = ($storage . UPLOAD_PATH_LOGO . DIRECTORY_SEPARATOR . $siteLogo->hashName());
        }

        // 파일 삭제
        if($request->get('site_favicon_del')) {
            $faviconPath = ($request->get('site_favicon_url'));
            if(file_exists($faviconPath)) {
                unlink($faviconPath);
            }
            $updateData['site_favicon'] = '';
        }

        if($request->get('site_logo_del')) {
            $logoPath = $request->get('site_logo_url');
            if(file_exists($logoPath)) {
                unlink($logoPath);
            }
            $updateData['site_logo'] = '';
        }

        $this->configModel->save($updateData, $attributes);

        $message = '로고 정보가 저장되었습니다.';
        return redirect()->route('admin.config.layout.logo.index')->with('message', $message);
    }
}
