<?php

namespace App\Http\Controllers;

use App\Mail\LocationAppeal;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Ramsey\Uuid\Uuid;
use App\Models\Appeal;

class AppealController extends Controller
{
    /**
     * Send appeal request
     */
    public function sendAppeal(Request $request)
    {
        //$order = Order::findOrFail($request->order_id);
        $token = csrf_token();

        if ($request->h1 != '' || $request->question != 2) {
            return back()->withErrors([
                'error' => 'Invalid Request',
            ]);
        } else {
            $check = Appeal::where("location", $request->location)->first();

            if ($check) {
                return back()->withErrors([
                    'error' => 'Appeal already in process for Location',
                ]);
            } else {
                $clean = $request->validate([
                    'location'           => ['required'],
                    'local_admin'        => ['required'],
                    'local_sponsor'      => ['required'],
                    'appeal_description' => ['required'],
                ]);

                $new = Appeal::create([
                    'uuid'           => Uuid::uuid4(),
                    'location'       => $request->location,
                    'location_admin' => $request->location_admin,
                    'sponsor'        => $request->sponsor,
                    'description'    => $request->appeal_description,
                    'approved'       => false,
                    'reviewed'       => false,
                ]);
                Mail::to(env('TBS_ADMIN_EMAIL'))->send(new LocationAppeal($request->location, $request->sponsor));
            }
            //return redirect('/appeals');
            return back()->with('message', "Appeal Filed");
        };
    }
}
