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

class Model_artist extends CI_Model {
    public function __construct(){
        $this->load->database();
    }

    public function getArtists($genre = '', $order = 'asc', $query = '', $limit = 10, $start = 0) {
        $this->db->select('artist.name as artistName, artist.id as artistId');
        $this->db->from('artist');
        $this->db->join('album', 'album.artistid = artist.id');
        $this->db->join('genre', 'genre.id = album.genreid');
        $this->db->distinct();
    
        if (!empty($genre)) {
            $this->db->where('genre.name', $genre);
        }
    
        if ($order == 'asc' || $order == 'desc') {
            $this->db->order_by('artist.name', $order);
        }
    
        if (!empty($query)) {
            $this->db->like('artist.name', $query);
        }
    
        $this->db->limit($limit, $start);
    
        $result = $this->db->get();
        return $result->result();
    }
    

    public function getArtistDetails($artistId) {
        $this->db->select('artist.name as artistName, artist.id');
        $this->db->from('artist');
        $this->db->where('artist.id', $artistId);
        $artistQuery = $this->db->get();
        return $artistQuery->row();
    }
    

    public function getAlbumsByArtist($artistId) {
        $this->db->select('album.id as albumId, album.name as albumName, album.year, cover.jpeg, genre.name as genreName');
        $this->db->from('album');
        $this->db->join('genre', 'album.genreid = genre.id');
        $this->db->join('cover', 'album.coverid = cover.id');
        $this->db->where('album.artistid', $artistId);
        $albumsQuery = $this->db->get();
        $albums = $albumsQuery->result();
    
        foreach ($albums as $album) {
            $this->db->select('track.id as trackId, song.name as songName');
            $this->db->from('track');
            $this->db->join('song', 'track.songid = song.id');
            $this->db->where('track.albumid', $album->albumId);
            $album->songs = $this->db->get()->result();
        }
    
        return $albums;
    }

    public function get_total_artists($genre = '', $query = '') {
        $this->db->select('artist.id'); // Sélectionnez uniquement l'ID de l'artiste
        $this->db->from('artist');
        $this->db->join('album', 'album.artistid = artist.id');
        $this->db->join('genre', 'genre.id = album.genreid');
    
        if (!empty($genre)) {
            $this->db->where('genre.name', $genre);
        }
    
        if (!empty($query)) {
            $this->db->like('artist.name', $query);
        }
    
        $this->db->distinct(); // Assurez-vous que seules les lignes distinctes sont comptées
        return $this->db->count_all_results();
    }
    
}