<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use App\Http\Requests\create_trafic;
use App\Models\Trafic;
use App\Models\Subscriber;

class AdminController extends Controller
{
    public function createtrafic(create_trafic $request){
        if(Auth::user()->role == 'admin'){
            Trafic::create([
                'name_trafic' => $request->name_trafic,
                'price_second' => $request->price_second,
            ]);
        }
        return redirect()->route('welcome');
    }

    public function deletetrafic(Trafic $trafic){
        if(Auth::user() && Auth::user()->role == 'admin'){
            $subscribers = Subscriber::where('trafic_id', $trafic->id)->get();
            foreach ($subscribers as $subscriber) {
                $subscriber->trafic_id = 1;
                $subscriber->save();
            }
            $trafic->delete(); 
        }
        return redirect()->route('welcome');
    }
}
