<?php

namespace App\Http\Controllers\Admin;


use App\Constants\Status;
use App\Http\Controllers\Controller;
use App\Models\SocialMedia;
use Illuminate\Http\Request;
use App\Rules\FileTypeValidate;

class SocialMediaController extends Controller
{
    public function index()
    {
        $pageTitle = "All List of Social Media Links";
        $emptyMessage = "No Social Media Links found";
        $SocialMedia = SocialMedia::searchable(['social_media_name'])->paginate(getPaginate());
        return view( 'admin.social_media.index', compact('pageTitle', 'emptyMessage', 'SocialMedia'));
    }

    public function editCreate($id = 0)
    {
        $pageTitle = $id ? "Social Media Update" : "Social Media Create";
        $SocialMedia = new SocialMedia();
        if ($id) {
            $SocialMedia = SocialMedia::findOrFail($id);
        }
        return view('admin.social_media.edit', compact('SocialMedia'));
    }

    public function updateStore(Request $request, $id = 0)
    {
        $request->validate([
            'social_media_name' => 'required|string|max:255',
            'social_media_link' => 'required|string|max:255',
            'social_media_icon' => ['nullable', 'image', new FileTypeValidate(['jpg', 'jpeg', 'png'])],
            'status' => 'required|in:' . implode(',', [
                Status::ENABLE,
                Status::DISABLE,
            ]),
        ]);

        $socialMedia = new SocialMedia();
        if ($id) {
            $socialMedia = SocialMedia::findOrFail($id);
        }
        if ($request->hasFile('social_media_icon')) {
            try {
                $socialMedia->social_media_icon = fileUploader($request->social_media_icon, getFilePath('withdrawMethod'), getFileSize('withdrawMethod'), $socialMedia->social_media_icon);
            } catch (\Exception $exp) {
                $notify[] = ['error', 'Couldn\'t upload your Social Media Icon Image'];
                return back()->withNotify($notify);
            }
        }

        $socialMedia->social_media_name = $request->social_media_name;
        $socialMedia->social_media_link = $request->social_media_link;
        // $socialMedia->social_media_icon = $request->social_media_icon;
        $socialMedia->status = $request->status;
        $socialMedia->save();

        $notify[] = ['success', 'Social Media '.($id ? 'updated' : 'created').' successfully'];
        return back()->withNotify($notify);
    }

}
