<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Artist ;
use App\Song ;

class ArtistController extends Controller
{
    public function browse()
    {
        return view('artists.index');
    }

    public function byLetter($letter)
    {
        if ($letter == '0-9') {
            $artists = Artist::whereRaw("name GLOB '[0-9]*'")->orderBy('name')->get();
        } else {
            $artists = Artist::where('name', 'LIKE', $letter.'%')->orderBy('name')->get();
        }
        return view('artists.index', compact('artists'))->with('activeLetter', $letter);
    }

    public function show(Artist $artist ) 
    {
    	return view('artist.show', compact('artist')) ;
    }

    public function edit($id){
    	$artist = Artist::find($id) ;
    	return view('artist.edit',compact('artist')) ;
    }

    public function update (Request $request, $id)
    {
    	$validatedData  = $request->validate([
            'artist' => 'required',
        ]);

        $artist 		= Artist::find($id) ;
        $artist->name 	= $request->input('artist') ;
        $artist->save() ;

        return redirect()->route('home') ;
    }

    public function destroy ($id)
    {
    	$artist 		= Artist::find($id) ;
    	if (!$artist) return redirect()->route('home') ;
    	foreach ($artist->songs()->get() as $song) {
    		Song::DeleteSong($song->id) ;
    	}
    	$artist->delete() ;
    	flash('تم حذف الفنان بنجاح')->error() ;
    	return redirect()->route('home') ;
    }
}
