<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\Atom;
use App\Models\Event;
use App\Models\EventAtoms;
use App\Models\EventProvince;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class adminEventAtomsController extends Controller
{
    function index($event_province_id)
    {
        $event_info = EventProvince::query()->findOrFail($event_province_id);
        $atoms = Atom::query()->where('event_province_id', $event_province_id)->latest()->get();
        return view('admin.events.atoms.index', compact('atoms', 'event_province_id', 'event_info'));
    }

    function store(Request $request, $event_id)
    {
        $event_info = EventProvince::query()->findOrFail($event_id);

        $input = $request->all();
        $validation = Validator::make($input, [
            'img' => 'required|string|max:255',
            'video' => 'required|string|max:255',
            'title' => 'required|string|max:255',
            'text' => 'required|string|max:255',
        ]);

        if ($validation->fails()) {
            alert()->error('', $validation->errors()->first());
            return back()->withErrors($validation->errors())->withInput();
        }

        Atom::query()->create([
            'event_province_id' => $event_id,
            'img' => $input['img'],
            'video' => $input['video'],
            'title' => $input['title'],
            'text' => $input['text'],
        ]);

        alert()->success('', ' اتم جدید برای رویداد ' . $event_info->province->name . ' با موفقیت افزوده شد ');
        return back();
    }

    function update(Request $request, $atom_id)
    {
        $atom_info = EventAtoms::query()->findOrFail($atom_id);

        $input = $request->all();
        $validation = Validator::make($input, [
            'img' => 'required|string|max:255',
            'video' => 'required|string|max:255',
            'title' => 'required|string|max:255',
            'text' => 'required|string|max:255',
        ]);

        if ($validation->fails()) {
            alert()->error('', $validation->errors()->first());
            return back()->withErrors($validation->errors())->withInput();
        }

        $atom_info->update([
            'img' => $input['img'],
            'video' => $input['video'],
            'title' => $input['title'],
            'text' => $input['text'],
        ]);

        alert()->success('','اتم با موفقیت ویرایش شد');
        return back();
    }

    function delete($atom_id)
    {
        $atom_info = Atom::query()->findOrFail($atom_id);
        $atom_info->delete();

        alert()->success('', 'اتم با موفقیت از رویداد حذف شد ');
        return back();
    }
}
