<?php
class M_galeri extends CI_Model{

	function get_all_galeri(){
		$sql = "SELECT tbl_galeri.*, DATE_FORMAT(galeri_tanggal,'%d/%m/%Y') AS tanggal, COALESCE(album_nama,'Uncategorized') AS album_nama 
			FROM tbl_galeri 
			LEFT JOIN tbl_album ON galeri_album_id = album_id 
			WHERE (galeri_gambar IS NOT NULL AND galeri_gambar != '')
			ORDER BY galeri_id DESC";
		return $this->db->query($sql);
	}

	function simpan_galeri($judul, $album, $user_id, $user_nama, $gambar){
		$data = array(
			'galeri_judul'      => $judul,
			'galeri_album_id'   => $album ? (int)$album : null,
			'galeri_pengguna_id'=> (int)$user_id,
			'galeri_author'     => $user_nama,
			'galeri_gambar'     => $gambar
		);
		$this->db->trans_start();
		$this->db->insert('tbl_galeri', $data);
		if (!empty($album) && is_numeric($album)) {
			$this->db->query("UPDATE tbl_album SET album_count = album_count + 1 WHERE album_id = ?", array((int)$album));
		}
		$this->db->trans_complete();
		return $this->db->trans_status() === true;
	}

	function update_galeri($galeri_id, $judul, $album, $user_id, $user_nama, $gambar){
		$data = array(
			'galeri_judul'       => $judul,
			'galeri_album_id'    => $album ? (int)$album : null,
			'galeri_pengguna_id' => (int)$user_id,
			'galeri_author'      => $user_nama,
			'galeri_gambar'      => $gambar
		);
		$this->db->where('galeri_id', (int)$galeri_id);
		return $this->db->update('tbl_galeri', $data);
	}

	function update_galeri_tanpa_img($galeri_id, $judul, $album, $user_id, $user_nama){
		$data = array(
			'galeri_judul'       => $judul,
			'galeri_album_id'    => $album ? (int)$album : null,
			'galeri_pengguna_id' => (int)$user_id,
			'galeri_author'      => $user_nama
		);
		$this->db->where('galeri_id', (int)$galeri_id);
		return $this->db->update('tbl_galeri', $data);
	}

	function hapus_galeri($kode, $album){
		$this->db->trans_start();
		$this->db->where('galeri_id', (int)$kode);
		$this->db->delete('tbl_galeri');
		if (!empty($album) && is_numeric($album)) {
			$this->db->query("UPDATE tbl_album SET album_count = GREATEST(0, COALESCE(album_count,0) - 1) WHERE album_id = ?", array((int)$album));
		}
		$this->db->trans_complete();
		return $this->db->trans_status() === true;
	}

	function get_galeri_home(){
		$sql = "SELECT tbl_galeri.*, DATE_FORMAT(galeri_tanggal,'%d/%m/%Y') AS tanggal, COALESCE(album_nama,'Uncategorized') AS album_nama 
			FROM tbl_galeri 
			LEFT JOIN tbl_album ON galeri_album_id = album_id 
			WHERE (galeri_gambar IS NOT NULL AND galeri_gambar != '')
			ORDER BY galeri_id DESC LIMIT 8";
		return $this->db->query($sql);
	}

	function get_galeri_by_album_id($idalbum){
		$idalbum = (int)$idalbum;
		$sql = "SELECT tbl_galeri.*, DATE_FORMAT(galeri_tanggal,'%d/%m/%Y') AS tanggal, COALESCE(album_nama,'Uncategorized') AS album_nama 
			FROM tbl_galeri 
			LEFT JOIN tbl_album ON galeri_album_id = album_id 
			WHERE galeri_album_id = ?
			ORDER BY galeri_id DESC";
		return $this->db->query($sql, array($idalbum));
	}
}
