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

class Peminjaman extends CI_Controller {

function __construct(){
    parent::__construct();

    if(!$this->session->userdata('login')){
        redirect('login');
    }

    $this->load->model('Peminjaman_model');
}


/* ===============================
INDEX
================================ */
public function index(){

    $q       = $this->input->get('q',true);
    $status  = $this->input->get('status',true);
    $filter  = $this->input->get('filter',true);
    $tanggal = $this->input->get('tanggal',true);
    $ganti   = $this->input->get('ganti',true);

    $data['data']        = $this->Peminjaman_model->get($q,$status,$filter,$tanggal,$ganti);
    $data['anggota']     = $this->Peminjaman_model->anggota();
    $data['buku']        = $this->Peminjaman_model->buku();
    $data['notif_count'] = $this->Peminjaman_model->count_notifikasi();
$data['belum_kembali']=$this->Peminjaman_model->jumlah_belum_kembali();

    $this->load->view('peminjaman/index',$data);
}


/* ===============================
TAMBAH
================================ */
public function tambah(){

    $id_anggota = $this->input->post('anggota',true);
    $buku_data  = json_decode($this->input->post('buku_data'),true);

    if(!$id_anggota || empty($buku_data)){
        $this->session->set_flashdata('error','Data tidak valid');
        redirect('peminjaman');
    }

    /* HITUNG PINJAMAN AKTIF */
    $pinjam_aktif = $this->Peminjaman_model->jumlah_pinjam_aktif($id_anggota);
    $akan_pinjam  = array_sum(array_column($buku_data,'qty'));

    if(($pinjam_aktif+$akan_pinjam)>4){
        $this->session->set_flashdata('error','Maksimal 4 buku aktif');
        redirect('peminjaman');
    }

    /* INSERT HEADER */
    $this->db->insert('peminjaman',[
        'id_anggota'=>$id_anggota,
        'tanggal_pinjam'=>date('Y-m-d'),
        'tanggal_kembali'=>date('Y-m-d',strtotime('+14 days')),
        'status'=>'dipinjam'
    ]);

    $id_peminjaman=$this->db->insert_id();

    /* INSERT DETAIL */
    foreach($buku_data as $b){

        if(!$b['id'] || $b['qty']<=0) continue;

        $this->db->insert('detail_peminjaman',[
            'id_peminjaman'=>$id_peminjaman,
            'id_buku'=>$b['id'],
            'jumlah'=>$b['qty'],
            'status'=>'dipinjam',
            'status_ganti'=>'tidak_perlu'
        ]);

        $this->db->set('stok',"stok-{$b['qty']}",false)
                 ->where('id_buku',$b['id'])
                 ->update('buku');
    }

    $this->session->set_flashdata('success','Peminjaman berhasil');
    redirect('peminjaman');
}


/* ===============================
CEK PINJAM AJAX
================================ */
public function cek_pinjam(){
    $id=$this->input->post('id',true);
    $jumlah=$this->Peminjaman_model->jumlah_pinjam_aktif($id);
    echo json_encode(['jumlah'=>$jumlah]);
}


/* ===============================
UPDATE STATUS
================================ */
public function update_status(){

    $id     = $this->input->post('id_detail',true);
    $status = $this->input->post('status',true);

    $detail=$this->db->get_where('detail_peminjaman',['id_detail'=>$id])->row();
    if(!$detail) return;

    $lama=$detail->status;

    /* STOK */
    if($lama=='dipinjam' && $status=='dikembalikan'){
        $this->db->set('stok','stok+'.$detail->jumlah,false)
                 ->where('id_buku',$detail->id_buku)
                 ->update('buku');
    }

    if($lama=='dikembalikan' && $status=='dipinjam'){
        $this->db->set('stok','stok-'.$detail->jumlah,false)
                 ->where('id_buku',$detail->id_buku)
                 ->update('buku');
    }

    /* STATUS GANTI */
    $status_ganti = ($status=='rusak'||$status=='hilang') ? 'belum':'tidak_perlu';

    $this->db->where('id_detail',$id)
    ->update('detail_peminjaman',[
        'status'=>$status,
        'status_ganti'=>$status_ganti,
        'tanggal_dikembalikan'=> ($status=='dikembalikan')?date('Y-m-d'):NULL
    ]);

    redirect('peminjaman');
}


/* ===============================
HAPUS DETAIL
================================ */
public function hapus_detail($id){

    if($this->session->userdata('level')!='superadmin')
        show_error('Akses ditolak',403);

    $detail=$this->db->get_where('detail_peminjaman',['id_detail'=>$id])->row();

    if($detail){

        if($detail->status=='dipinjam'){
            $this->db->set('stok','stok+'.$detail->jumlah,false)
                     ->where('id_buku',$detail->id_buku)
                     ->update('buku');
        }

        $this->db->delete('detail_peminjaman',['id_detail'=>$id]);

        $sisa=$this->db->where('id_peminjaman',$detail->id_peminjaman)
                       ->count_all_results('detail_peminjaman');

        if($sisa==0){
            $this->db->delete('peminjaman',['id_peminjaman'=>$detail->id_peminjaman]);
        }
    }

    redirect('peminjaman');
}


/* ===============================
MONITORING GANTI
================================ */
public function monitoring_ganti(){
    $data['data']=$this->Peminjaman_model->buku_perlu_ganti();
    $this->load->view('peminjaman/monitoring_ganti',$data);
}


/* ===============================
SIMPAN BUKU GANTI
================================ */
public function simpan_ganti(){

$id=$this->input->post('id_detail',true);

/* INSERT BUKU PENGGANTI */
$this->db->insert('buku',[
'judul'=>$this->input->post('judul',true),
'id_kategori'=>$this->input->post('kategori',true),
'penulis'=>$this->input->post('penulis',true),
'penerbit'=>$this->input->post('penerbit',true),
'tahun'=>$this->input->post('tahun',true),
'stok'=>1
]);

/* UPDATE DETAIL */
$this->db->where('id_detail',$id)
->update('detail_peminjaman',[
'status_ganti'=>'sudah',
'tanggal_dikembalikan'=>date('Y-m-d'),
'status'=>'dikembalikan'
]);

$this->session->set_flashdata('success','Buku pengganti berhasil disimpan');
redirect('peminjaman/monitoring_ganti');
}

public function form_ganti($id_detail)
{
    $data['detail']=$this->db
        ->select('dp.*,b.judul,a.nama')
        ->from('detail_peminjaman dp')
        ->join('peminjaman p','p.id_peminjaman=dp.id_peminjaman')
        ->join('buku b','b.id_buku=dp.id_buku')
        ->join('anggota a','a.id_anggota=p.id_anggota')
        ->where('dp.id_detail',$id_detail)
        ->get()->row();

    $data['kategori']=$this->db->get('kategori')->result();

    $this->load->view('peminjaman/form_ganti',$data);
}

}
