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

class Albums 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');
        $sort = $this->input->get('sort');
        $order = $this->input->get('order');

		if ($recherche=filter_input(INPUT_GET,'recherche') == false or $recherche=filter_input(INPUT_GET,'recherche') == null){
			$albums = $this->model_music->get_filtered_albums($genre, $artist, $year, $sort, $order);
			$data['albums'] = $albums;
		}else{
			$recherche=filter_input(INPUT_GET,'recherche');
			$albums = $this->model_music->getSearchAlbums($recherche);
			$data['albums'] = $albums;
		}
		$this->load->view('layout/header');
		if ($albums == false){
			$page = preg_split('/[\/]/',$_SERVER['REQUEST_URI']);
			$this->load->view('error',['page'=>$page[count($page)-1]]);
			$albums = $this->model_music->get_filtered_albums($genre, $artist, $year, $sort, $order);
			$data['albums'] = $albums;
		}

		$data['genres'] = $this->model_music->get_all_genres();
        $data['artists'] = $this->model_music->get_all_artists();
        $data['years'] = $this->model_music->get_all_years();

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

	public function viewMusique($id) {
        $albums = $this->model_music->getAlbumChoose($id);
        if ($albums) {
            $this->load->view('layout/header');
            $this->load->view('albums_view', ['albums' => $albums]);
            $this->load->view('layout/footer');
        }
    }

	public function viewAlbum($Id) {
        $albums = $this->model_music->getAlbumsByArtistId($Id);
        $this->load->view('layout/header');
        $this->load->view('albums_list', ['albums' => $albums]);
        $this->load->view('layout/footer');
    }

	public function addAlbumtoPlaylist($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('addAlbumtoplaylist', ["playlists" => $playlists]);
		    $this->load->view('layout/footer');
		}else{
			$playlistId = $this->input->post('playlist_id');
			$this->model_music->AddAlbumtoPlaylist($playlistId,$id);
			redirect('albums');
		}
	}
}

