<?php

namespace App\Controllers\Libskill;

use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;

class Libdata extends BaseController
{
    use ResponseTrait;

    public function __construct()
    {
        $this->LibModel = model('App\Models\Libskill\LibModel');
    }

    private function setJsonHeader()
    {
        return $this->response->setHeader('Content-Type', 'application/json');
    }

    public function index()
    {
        $page = $this->request->getGet('page') ?? 1;
        $search = $this->request->getGet('search') ?? '';
        $limit = 6; // Items per page
        $offset = ($page - 1) * $limit;

        $rows = $this->LibModel->get_data_with_pagination($limit, $offset, $search);
        $total_records = $this->LibModel->count_all_data($search);
        $total_pages = ceil($total_records / $limit);

        return view('libskill/browse_data', [
            'rows' => $rows,
            'current_page' => $page,
            'total_pages' => $total_pages,
            'total_records' => $total_records,
            'search' => $search,
            'limit' => $limit,
            'link_rekam' => base_url('libskill/libdata/rekam'),
            'link_edit' => base_url('libskill/libdata/edit/'),
            'link_hapus' => base_url('libskill/libdata/hapus'),
        ]);
    }

    //Tampilkan Form untuk Rekam Data
    public function rekam()
    {
        return view('libskill/form_data', [
            'action' => base_url('libskill/libdata/rekam_act'),
            'titel' => 'Rekam Data',
            'id' => '',
            'judul' => '',
            'uraian' => '',
            'penulis' => '',
            'cover' => '',
            'berkas' => '',
        ]);
    }//End Tampilkan Form untuk Rekam

    public function rekam_act()
    {
        $this->setJsonHeader();

        $judul = $this->request->getPost('judul', FILTER_SANITIZE_SPECIAL_CHARS);
        $penulis = $this->request->getPost('penulis', FILTER_SANITIZE_SPECIAL_CHARS);

         // Cek apakah data sudah ada
        $jumlahData = $this->LibModel->cek_data($judul, $penulis);

        if ($jumlahData > 0) {
            return $this->fail(['message' => DUPLICATE], 403);
        } else {
            $file_cover = $this->request->getFile('cover');
            $covExtension = $file_cover->getExtension();
            $ncover = generateFilename('cov', $judul);
            $cover = "{$ncover}.{$covExtension}";

            $file_berkas = $this->request->getFile('berkas');
            $berExtension = $file_berkas->getExtension();
            $nberkas = generateFilename('file', $judul);
            $berkas = "{$nberkas}.{$berExtension}";

            if ($file_cover->move(ROOTPATH . 'public/flibs', $cover)) {
                if ($file_berkas->move(ROOTPATH . 'public/flibs', $berkas)) {
                    $data = [
                        'judul' => $judul,
                        'uraian' => $this->request->getPost('uraian', FILTER_SANITIZE_SPECIAL_CHARS),
                        'penulis' => $penulis,
                        'cover' => $cover,
                        'berkas' => $berkas,
                        'id_user' => auth()->id(),
                        'wkt_rek' => timestamp(),
                    ];

                    if (!$this->LibModel->insert($data)) {
                        return $this->fail($this->LibModel->errors(), 500);
                    }

                    return $this->respond(['message' => B_SIMPAN], 201);
                } else {
                    return $this->fail(['message' => G_UPLOAD], 403);
                }
            } else {
                return $this->fail(['message' => G_UPLOAD], 403);
            }    
        }
    }

    public function edit($id)
    {
        $row = $this->LibModel->find(decrypt_url($id));

        if (!$row) {
            exit('Data tidak ditemukan');
        }

        return view('libskill/form_data', [
            'action' => base_url('libskill/libdata/edit_act'), 
            'titel' => 'Edit Data',
            'id' => encrypt_url($row->id),
            'judul' => $row->judul,
            'uraian' => $row->uraian,
            'penulis' => $row->penulis,
            'cover' => $row->cover,
            'berkas' => $row->berkas,
        ]);
    }

    public function edit_act()
    {
        $this->setJsonHeader();

        //collect form data
        $id = decrypt_url(trim($this->request->getPost('id')));

        //inputan file
        $judul = $this->request->getPost('judul', FILTER_SANITIZE_SPECIAL_CHARS);

        $file_cover = $this->request->getFile('cover');
        if ($file_cover->getSize() > 0) {
            $covExtension = $file_cover->getExtension();
            $ncover = generateFilename('cov', $judul);
            $cover = "{$ncover}.{$covExtension}";

            $file_cover->move(ROOTPATH . 'public/flibs', $cover);
        } else {
            $cover = $this->request->getPost('cover_ori');
        }

        $file_berkas = $this->request->getFile('berkas');
        if ($file_berkas->getSize() > 0) {
            $berExtension = $file_berkas->getExtension();
            $nberkas = generateFilename('file', $judul);
            $berkas = "{$nberkas}.{$berExtension}";

            $file_berkas->move(ROOTPATH . 'public/flibs', $berkas);
        } else {
            $berkas = $this->request->getPost('berkas_ori');
        }

        $data = [
            'judul' => $judul,
            'uraian' => $this->request->getPost('uraian', FILTER_SANITIZE_SPECIAL_CHARS),
            'penulis' => $this->request->getPost('penulis', FILTER_SANITIZE_SPECIAL_CHARS),
            'cover' => $cover,
            'berkas' => $berkas,
            'id_user' => auth()->id(),
            'wkt_rek' => timestamp(),
        ];

        if (!$this->LibModel->update($id, $data)) {
            return $this->fail($this->LibModel->errors(), 500);
        }

        return $this->respond(['message' => B_UBAH], 200);
    }

    public function hapus()
    {
        $this->setJsonHeader();

        $ids  = $this->request->getPost('id');
        $id = decrypt_url($ids);
        
        if (!$this->LibModel->delete($id)) {
            return $this->fail($this->LibModel->errors(), 500);
        } else {
            return $this->respond(['message' => 'Data berhasil dihapus']);
        }
    }
}