<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\About;
use App\Models\WebsiteSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class AboutController extends Controller
{
    public function index()
    {
        # code...
        $this->authorize('viewAny', WebsiteSetting::class);
        $about = About::first();
        return view('admin.about',[
            'about' => $about,
        ]);
    }

    public function store(Request $request)
    {
        # code...
        $this->authorize('viewAny', WebsiteSetting::class);
        $about = About::first();

        if($about){
            $request->validate([
                'image' => 'nullable|mimes:png,jpg,jpeg',
                'title' => 'required|string|max:255',
                'title_ar' => 'required|string|max:255',
                'sub_title' => 'nullable|string|max:255',
                'sub_title_ar' => 'nullable|string|max:255',
                'description' => 'required',
                'description_ar' => 'required',
                'vision' => 'nullable',
                'vision_ar' => 'nullable',
                'mission' => 'nullable',
                'mission_ar' => 'nullable',
                'message' => 'nullable',
                'message_ar' => 'nullable',
            ]);

            $data = $request->all();

            $data['image'] = $about->image;

            if($request->hasFile('image') && $request->file('image')->isValid()){
                if($about->image)
                    Storage::disk('works')->delete($about->image);

                $image = $request->file('image')->store('/', 'works');
                $data['image'] = $image;
            }

            $about->update($data);
        } else {
            $request->validate([
                'image' => 'required|mimes:png,jpg,jpeg',
                'title' => 'required|string|max:255',
                'title_ar' => 'required|string|max:255',
                'sub_title' => 'nullable|string|max:255',
                'sub_title_ar' => 'nullable|string|max:255',
                'description' => 'required',
                'description_ar' => 'required',
                'vision' => 'nullable',
                'vision_ar' => 'nullable',
                'mission' => 'nullable',
                'mission_ar' => 'nullable',
                'message' => 'nullable',
                'message_ar' => 'nullable',
            ]);

            $data = $request->all();

            $data['image'] = null;

            if($request->hasFile('image') && $request->file('image')->isValid()){
                $image = $request->file('image')->store('about', 'public');
                $data['image'] = $image;
            }

            About::create($data);
        }

        return redirect()->route('c-panel.about')->with('success', __('Updated Done !'));
    }
}

