<?php

namespace App\Http\Controllers;

use App\Models\sponsor;
use App\Models\User;
use App\Notifications\CompletedTask;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SponsorController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
       return view('sponsors/new_sponsor');
    }

    public function all()
    {
        $sponsors = sponsor::all();        
        return view('sponsors/allsponsors', compact('sponsors'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'contact' => 'required',            
            'description' => 'required'                     
        ]);
        $sponsor = new sponsor();
        
        $sponsor->name = $request->name;
        $sponsor->contact = $request->contact;
        $sponsor->description = $request->description;       
        $sponsor->user_id = Auth::id();
        $sponsor->save();
        return redirect('allsponsors')->with('success', 'Saved Successfully!');
    }

    public function view($id)
    {
        $sponsor = sponsor::find($id);
        return view('sponsors.sponsorView', compact('sponsor'));
    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required',
            'contact' => 'required',
            'description' => 'required',                                 
        ]);

        $sponsor = sponsor::find($id);
        
        $sponsor->name = $request->name;
        $sponsor->contact = $request->contact;
        $sponsor->description = $request->description; 

        $sponsor->save();

        return redirect()->back()->with('success', 'Updated Successfully!');
    }

    public function delete($id)
    {
        /*sponsor::find($id)->delete();*/
        //SEND NOTIFICATION ADMIN            
        $message = Auth::user()->name . " attempted to delete Sponsor # " . $id . " on " . Carbon::now();
        $users = User::where('role', 3)->get();
        foreach ($users as $user) {
            $user->notify(new CompletedTask($message));
        }
        return redirect()->back()->with('warning', 'Contact System admin!');
    }
}
