<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Chansons extends CI_Controller {

	public function __construct(){
		parent::__construct();
		$this->load->model('model_music');
		$this->load->library('form_validation');
	}
	public function index(){
		$genre = $this->input->get('genre');
        $artist = $this->input->get('artist');
        $year = $this->input->get('year');
		$album = $this->input->get('albums');
        $sort = $this->input->get('sort');
        $order = $this->input->get('order');
		$recherche = $this->input->get('recherche', true);

        if (empty($recherche)) {
            $data['chansons'] = $this->model_music->get_filtered_chansons($genre, $artist, $year, $album, $sort, $order);
        } else {
            $data['chansons'] = $this->model_music->getSearchChansons($recherche);
        }

		$this->load->view('layout/header');
		
		if ($data['chansons'] == false){
			$page = preg_split('/[\/]/',$_SERVER['REQUEST_URI']);
			$this->load->view('error',['page'=>$page[count($page)-1]]);
			$data['chansons'] = $this->model_music->get_filtered_chansons($genre, $artist, $year, $album, $sort, $order);
		}
		$data['genres'] = $this->model_music->get_all_genres_chansons();
        $data['artists'] = $this->model_music->get_all_artists_chansons();
        $data['years'] = $this->model_music->get_all_years_chansons();
		$data['albums'] = $this->model_music->get_all_albums_chansons();

		$this->load->view('chansons_list',$data);
		$this->load->view('layout/footer');
	}

	public function addSongtoPlaylist($id){
		$playlists = $this->model_music->getPlaylist();
		
		$this->form_validation->set_rules('playlist_id', 'playlist_id', 'required');

        if ($this->form_validation->run() == FALSE){
			$this->load->view('layout/header');
		    $this->load->view('addSongtoplaylist', ["id" => $id, "playlists" => $playlists]);
		    $this->load->view('layout/footer');
		}else{
			$playlistId = $this->input->post('playlist_id');
			$url = $this->input->get('page');
			$this->model_music->AddSongtoPlaylist($playlistId,$id);
			redirect($url);
		}
	}

	public function deleteSongtoPlaylist($id){
		$playlists = $this->model_music->getPlaylistIdSong($id);
		
		$this->form_validation->set_rules('playlist_id', 'playlist_id', 'required');

        if ($this->form_validation->run() == FALSE){
			$this->load->view('layout/header');
		    $this->load->view('deleteSongtoplaylist', ["id" => $id, "playlists" => $playlists]);
		    $this->load->view('layout/footer');
		}else{
			$playlistId = $this->input->post('playlist_id');
			$url = $this->input->get('page');
			$this->model_music->DeleteSongtoPlaylist($playlistId,$id);
			redirect($url);
		}
	}

	public function view($id){
		$chansons = $this->model_music->get_song_playlist($id);
		$data['chansons'] = $chansons;

		$this->load->view('layout/header');
		$this->load->view('chansons_list',$data);
		$this->load->view('layout/footer');
	}
}

