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

class Ebooks extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Ebook_model');
        $this->_cors();
    }

    private function _cors() {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
        if ($this->input->server('REQUEST_METHOD') === 'OPTIONS') {
            exit(0);
        }
    }

    private function _json($status, $message, $data = null, $code = 200) {
        http_response_code($code);
        header('Content-Type: application/json');
        $response = ['status' => $status, 'message' => $message];
        if ($data !== null) $response['data'] = $data;
        echo json_encode($response);
        exit;
    }

    private function _check_auth() {
        if (!$this->session->userdata('user_id')) {
            $this->_json(false, 'Unauthorized - silakan login', null, 401);
        }
    }

    private function _check_admin() {
        $this->_check_auth();
        if ($this->session->userdata('role') !== 'admin') {
            $this->_json(false, 'Forbidden - hanya admin', null, 403);
        }
    }

    // GET /api/ebooks
    public function index() {
        $search   = $this->input->get('search') ?: '';
        $page     = (int)($this->input->get('page') ?: 1);
        $limit    = (int)($this->input->get('limit') ?: 12);
        $kategori = $this->input->get('kategori') ?: '';
        $offset   = ($page - 1) * $limit;

        $ebooks = $this->Ebook_model->get_all($search, $offset, $limit, $kategori);
        $total  = $this->Ebook_model->count_all($search, $kategori);

        // Add base URL for files
        $base = base_url();
        foreach ($ebooks as &$e) {
            $e->file_url  = $base . 'uploads/' . $e->file;
            $e->cover_url = $e->cover ? $base . 'uploads/covers/' . $e->cover : $base . 'assets/img/no-cover.png';
        }

        $this->_json(true, 'Success', [
            'ebooks'       => $ebooks,
            'total'        => $total,
            'page'         => $page,
            'limit'        => $limit,
            'total_pages'  => ceil($total / $limit),
        ]);
    }

    // GET /api/ebooks/{id}
    public function show($id) {
        $ebook = $this->Ebook_model->get_by_id($id);
        if (!$ebook) {
            $this->_json(false, 'E-Book tidak ditemukan', null, 404);
        }
        $base = base_url();
        $ebook->file_url  = $base . 'uploads/' . $ebook->file;
        $ebook->cover_url = $ebook->cover ? $base . 'uploads/covers/' . $ebook->cover : $base . 'assets/img/no-cover.png';
        $this->_json(true, 'Success', $ebook);
    }

    // POST /api/ebooks  (admin only)
    public function create() {
        $this->_check_admin();

        $judul     = $this->input->post('judul');
        $penulis   = $this->input->post('penulis');
        $kategori  = $this->input->post('kategori');
        $deskripsi = $this->input->post('deskripsi');

        if (!$judul || !$penulis || !$kategori) {
            $this->_json(false, 'Judul, penulis, dan kategori wajib diisi', null, 400);
        }

        // Upload PDF
        if (empty($_FILES['file']['name'])) {
            $this->_json(false, 'File PDF wajib diunggah', null, 400);
        }

        $this->load->library('upload');

        // Upload PDF file
        $pdf_config = [
            'upload_path'   => FCPATH . 'uploads/',
            'allowed_types' => 'pdf',
            'max_size'      => 30720, // 30MB
            'encrypt_name'  => TRUE,
        ];
        $this->upload->initialize($pdf_config);
        if (!$this->upload->do_upload('file')) {
            $this->_json(false, 'Gagal upload PDF: ' . $this->upload->display_errors('', ''), null, 400);
        }
        $pdf_data = $this->upload->data();
        $file_name = $pdf_data['file_name'];

        // Upload Cover (optional)
        $cover_name = null;
        if (!empty($_FILES['cover']['name'])) {
            $cover_config = [
                'upload_path'   => FCPATH . 'uploads/covers/',
                'allowed_types' => 'jpg|jpeg|png|webp',
                'max_size'      => 5120, // 5MB
                'max_width'     => 2000,
                'max_height'    => 3000,
                'encrypt_name'  => TRUE,
            ];
            $this->upload->initialize($cover_config);
            if ($this->upload->do_upload('cover')) {
                $cover_data = $this->upload->data();
                $cover_name = $cover_data['file_name'];
            }
        }

        $id = $this->Ebook_model->insert([
            'judul'     => $judul,
            'penulis'   => $penulis,
            'kategori'  => $kategori,
            'deskripsi' => $deskripsi,
            'file'      => $file_name,
            'cover'     => $cover_name,
        ]);

        $this->_json(true, 'E-Book berhasil ditambahkan', ['id' => $id]);
    }

    // POST /api/ebooks/{id}  (admin only, supports multipart)
    public function update($id) {
        $this->_check_admin();

        $ebook = $this->Ebook_model->get_by_id($id);
        if (!$ebook) {
            $this->_json(false, 'E-Book tidak ditemukan', null, 404);
        }

        $judul     = $this->input->post('judul') ?: $ebook->judul;
        $penulis   = $this->input->post('penulis') ?: $ebook->penulis;
        $kategori  = $this->input->post('kategori') ?: $ebook->kategori;
        $deskripsi = $this->input->post('deskripsi') ?: $ebook->deskripsi;

        $update_data = [
            'judul'     => $judul,
            'penulis'   => $penulis,
            'kategori'  => $kategori,
            'deskripsi' => $deskripsi,
        ];

        $this->load->library('upload');

        // Replace PDF if new one uploaded
        if (!empty($_FILES['file']['name'])) {
            $pdf_config = [
                'upload_path'   => FCPATH . 'uploads/',
                'allowed_types' => 'pdf',
                'max_size'      => 30720,
                'encrypt_name'  => TRUE,
            ];
            $this->upload->initialize($pdf_config);
            if ($this->upload->do_upload('file')) {
                // Delete old file
                if (file_exists(FCPATH . 'uploads/' . $ebook->file)) {
                    unlink(FCPATH . 'uploads/' . $ebook->file);
                }
                $pdf_data = $this->upload->data();
                $update_data['file'] = $pdf_data['file_name'];
            }
        }

        // Replace Cover if new one uploaded
        if (!empty($_FILES['cover']['name'])) {
            $cover_config = [
                'upload_path'   => FCPATH . 'uploads/covers/',
                'allowed_types' => 'jpg|jpeg|png|webp',
                'max_size'      => 5120,
                'encrypt_name'  => TRUE,
            ];
            $this->upload->initialize($cover_config);
            if ($this->upload->do_upload('cover')) {
                if ($ebook->cover && file_exists(FCPATH . 'uploads/covers/' . $ebook->cover)) {
                    unlink(FCPATH . 'uploads/covers/' . $ebook->cover);
                }
                $cover_data = $this->upload->data();
                $update_data['cover'] = $cover_data['file_name'];
            }
        }

        $this->Ebook_model->update($id, $update_data);
        $this->_json(true, 'E-Book berhasil diperbarui');
    }

    // DELETE /api/ebooks/{id}  (admin only)
    public function delete($id) {
        $this->_check_admin();

        $ebook = $this->Ebook_model->get_by_id($id);
        if (!$ebook) {
            $this->_json(false, 'E-Book tidak ditemukan', null, 404);
        }

        // Delete physical files
        if ($ebook->file && file_exists(FCPATH . 'uploads/' . $ebook->file)) {
            unlink(FCPATH . 'uploads/' . $ebook->file);
        }
        if ($ebook->cover && file_exists(FCPATH . 'uploads/covers/' . $ebook->cover)) {
            unlink(FCPATH . 'uploads/covers/' . $ebook->cover);
        }

        $this->Ebook_model->delete($id);
        $this->_json(true, 'E-Book berhasil dihapus');
    }
}
