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

require_once FCPATH . 'vendor/autoload.php'; // pastikan ini aktif

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use Dompdf\Dompdf;
use Dompdf\Options;

class Barang_masuk_controller extends CI_Controller {

    public function __construct() {  
        parent::__construct();
        $this->load->model('Barang_masuk_model');
        $this->load->helper(['url', 'form']);
        $this->load->library(['session','upload']);
    }

    // ===================== LIST =====================
    public function index() {
        $data['barang_masuk'] = $this->Barang_masuk_model->get_all();
        $this->load->view('barang_masuk/list', $data);
    }

    public function list_admin() {
        $data['barang_masuk'] = $this->Barang_masuk_model->get_all();
        $this->load->view('barang_masuk/list_admin', $data);
    }

    // ===================== FORM =====================
    public function form() {
        $this->load->view('barang_masuk/form');
    }

    public function form_admin() {
        $this->load->view('barang_masuk/form_admin');
    }

    // ===================== SIMPAN =====================
    public function simpan() {
        $data = $this->input_data();
        $foto = $this->_upload_foto();
        if ($foto) $data['foto'] = $foto;

        $this->_save_to_db($data, 'barang_masuk_controller');
    }

    public function simpan_admin() {
        $data = $this->input_data();
        $foto = $this->_upload_foto();
        if ($foto) $data['foto'] = $foto;

        $this->_save_to_db($data, 'barang_masuk_controller/list_admin');
    }

    private function _save_to_db($data, $redirect_url) {
        if ($this->Barang_masuk_model->insert($data)) {
            $this->session->set_flashdata('success', 'Data berhasil disimpan!');
        } else {
            $this->session->set_flashdata('error', 'Gagal menyimpan data!');
        }
        redirect($redirect_url);
    }

    // ===================== EDIT =====================
    public function edit($id) {
        $data['barang'] = $this->Barang_masuk_model->get_by_id($id);
        if (!$data['barang']) show_404();
        $this->load->view('barang_masuk/edit', $data);
    }

    public function edit_admin($id) {
        $data['barang'] = $this->Barang_masuk_model->get_by_id($id);
        if (!$data['barang']) show_404();
        $this->load->view('barang_masuk/edit_admin', $data);
    }

    // ===================== UPDATE =====================
    public function update($id) {
        $this->_update_data($id, 'barang_masuk_controller');
    }

    public function update_admin($id) {
        $this->_update_data($id, 'barang_masuk_controller/list_admin');
    }

    private function _update_data($id, $redirect_url) {
        $data = $this->input_data(false);
        $foto = $this->_upload_foto();

        if ($foto) {
            $barang = $this->Barang_masuk_model->get_by_id($id);
            if ($barang && $barang->foto && file_exists(FCPATH . 'uploads/barang/' . $barang->foto)) {
                unlink(FCPATH . 'uploads/barang/' . $barang->foto);
            }
            $data['foto'] = $foto;
        }

        if ($this->Barang_masuk_model->update($id, $data)) {
            $this->session->set_flashdata('success', 'Data berhasil diperbarui!');
        } else {
            $this->session->set_flashdata('error', 'Gagal memperbarui data!');
        }
        redirect($redirect_url);
    }

    // ===================== DELETE =====================
    public function delete($id) {
        $this->_delete_data($id, 'barang_masuk_controller');
    }

    public function delete_admin($id) {
        $this->_delete_data($id, 'barang_masuk_controller/list_admin');
    }

    private function _delete_data($id, $redirect_url) {
        $barang = $this->Barang_masuk_model->get_by_id($id);
        if ($barang && $barang->foto && file_exists(FCPATH . 'uploads/barang/' . $barang->foto)) {
            unlink(FCPATH . 'uploads/barang/' . $barang->foto);
        }

        if ($this->Barang_masuk_model->delete($id)) {
            $this->session->set_flashdata('success', 'Data berhasil dihapus!');
        } else {
            $this->session->set_flashdata('error', 'Gagal menghapus data!');
        }
        redirect($redirect_url);
    }

    // ===================== INPUT DATA =====================
    private function input_data($with_created = true) {
        $data = [
            'nama_pengirim' => $this->input->post('nama_pengirim', true),
            'nama_vendor'   => $this->input->post('nama_vendor', true),
            'no_registrasi' => $this->input->post('no_registrasi', true),
            'jenis_barang'  => $this->input->post('jenis_barang', true),
            'penerima'      => $this->input->post('penerima', true),
            'security'      => $this->input->post('security', true),
            'location'      => $this->input->post('location', true),
            'tanggal'       => $this->input->post('tanggal', true),
            'waktu_masuk'   => $this->input->post('waktu_masuk', true),
        ];
        if ($with_created) {
            $data['created_at'] = date('Y-m-d H:i:s');
        }
        return $data;
    }

   public function export_excel() {
    $search = $this->input->get('search');
    $tanggal = $this->input->get('tanggal');

    // --- Ambil data ---
    // Tambahkan kolom 'foto' ke dalam SELECT
    $this->db->select('nama_pengirim, nama_vendor, no_registrasi, jenis_barang, penerima, security, location, tanggal, waktu_masuk, foto');
    $this->db->from('barang_masuk');

    if (!empty($search)) {
        $this->db->group_start()
            ->like('nama_pengirim', $search)
            ->or_like('nama_vendor', $search)
            ->or_like('no_registrasi', $search)
            ->or_like('jenis_barang', $search)
            ->group_end();
    }

    if (!empty($tanggal)) {
        $this->db->where('tanggal', $tanggal);
    }

    $this->db->order_by('tanggal', 'DESC');
    $barang = $this->db->get()->result();

    // --- Info user & waktu cetak ---
    $username = $this->session->userdata('nama_lengkap') ?? $this->session->userdata('username') ?? 'Tidak diketahui';
    $tanggal_cetak = date('d/m/Y H:i');

    // --- Inisialisasi Spreadsheet ---
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setTitle('Barang Masuk');
    $sheet->getPageSetup()->setOrientation(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE);
    $sheet->getPageSetup()->setFitToWidth(1);
    
    // UBAH: Tambah satu kolom lagi, menjadi kolom 'K'
    $col_end = 'K'; 

    // --- Logo ---
    $logoPath = FCPATH . 'asset/img/asiaserv-logo.png';
    if (file_exists($logoPath)) {
        $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
        $drawing->setName('Logo');
        $drawing->setDescription('Logo Perusahaan');
        $drawing->setPath($logoPath);
        $drawing->setHeight(55);
        $drawing->setCoordinates('A1');
        $drawing->setWorksheet($sheet);
    }

    // --- Judul Laporan (Perlu Merge Cell sampai $col_end) ---
    $sheet->mergeCells('A1:'.$col_end.'1');
    $sheet->setCellValue('A1', 'LAPORAN DATA BARANG MASUK');
    $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(15);
    $sheet->getStyle('A1')->getAlignment()
        ->setHorizontal(Alignment::HORIZONTAL_CENTER)
        ->setVertical(Alignment::VERTICAL_CENTER);

    // --- Dicetak oleh (Perlu Merge Cell sampai $col_end) ---
    $sheet->mergeCells('A2:'.$col_end.'2');
    $sheet->setCellValue('A2', 'Dicetak oleh: ' . $username);
    $sheet->getStyle('A2')->getFont()->setSize(11);
    $sheet->getStyle('A2')->getAlignment()
        ->setHorizontal(Alignment::HORIZONTAL_CENTER)
        ->setVertical(Alignment::VERTICAL_CENTER);

    // --- Tanggal Cetak (Perlu Merge Cell sampai $col_end) ---
    $sheet->mergeCells('A3:'.$col_end.'3');
    $sheet->setCellValue('A3', 'Tanggal Cetak: ' . $tanggal_cetak);
    $sheet->getStyle('A3')->getFont()->setSize(11);
    $sheet->getStyle('A3')->getAlignment()
        ->setHorizontal(Alignment::HORIZONTAL_CENTER)
        ->setVertical(Alignment::VERTICAL_CENTER);

    // --- Filter Info (Perlu Merge Cell sampai $col_end) ---
    $filter_info = "Semua Data";
    if (!empty($search) || !empty($tanggal)) {
        $filter_detail = [];
        if (!empty($search)) $filter_detail[] = "Pencarian: \"$search\"";
        if (!empty($tanggal)) $filter_detail[] = "Tanggal: " . date('d-M-Y', strtotime($tanggal));
        $filter_info = implode(" | ", $filter_detail);
    }
    $sheet->mergeCells('A4:'.$col_end.'4');
    $sheet->setCellValue('A4', 'Filter: ' . $filter_info);
    $sheet->getStyle('A4')->getFont()->setItalic(true)->setSize(10);
    $sheet->getStyle('A4')->getAlignment()
        ->setHorizontal(Alignment::HORIZONTAL_CENTER)
        ->setVertical(Alignment::VERTICAL_CENTER);

    // --- Header tabel ---
    $start_row = 6;
    // UBAH: Tambahkan 'Foto' di akhir array headers
    $headers = ['No', 'Nama Pengirim', 'Nama Vendor', 'No Registrasi', 'Jenis Barang', 'Penerima', 'Security', 'Location', 'Tanggal', 'Waktu Masuk', 'Foto']; 

    $styleHeader = [
        'font' => ['bold' => true, 'color' => ['argb' => 'FFFFFFFF']],
        'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER],
        'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['argb' => 'FF003366']],
        'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN, 'color' => ['argb' => 'FF000000']]]
    ];

    $sheet->getRowDimension($start_row)->setRowHeight(25);
    $col = 'A';
    foreach ($headers as $header) {
        $sheet->setCellValue($col . $start_row, $header);
        $col++;
    }
    $sheet->getStyle('A'.$start_row.':'.$col_end.$start_row)->applyFromArray($styleHeader);

    // --- Isi data ---
    $row = $start_row + 1;
$no = 1;
$foto_path = FCPATH . 'uploads/barang/';

foreach ($barang as $b) {
    $sheet->getRowDimension($row)->setRowHeight(90); // tinggi baris agar foto cukup

    $sheet->setCellValue('A'.$row, $no++)
          ->setCellValue('B'.$row, $b->nama_pengirim)
          ->setCellValue('C'.$row, $b->nama_vendor)
          ->setCellValue('D'.$row, $b->no_registrasi)
          ->setCellValue('E'.$row, $b->jenis_barang)
          ->setCellValue('F'.$row, $b->penerima)
          ->setCellValue('G'.$row, $b->security)
          ->setCellValue('H'.$row, $b->location)
          ->setCellValue('I'.$row, $b->tanggal)
          ->setCellValue('J'.$row, $b->waktu_masuk);

    // FOTO (kolom K)
    if (!empty($b->foto)) {
        $full_foto_path = $foto_path . $b->foto;

        if (file_exists($full_foto_path)) {
            // Tambahkan debug dulu (sementara)
            // echo "Path foto: $full_foto_path<br>";

            $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
            $drawing->setName('Foto-'.$row);
            $drawing->setDescription('Foto Barang');
            $drawing->setPath($full_foto_path);
            $drawing->setHeight(80);
            $drawing->setCoordinates('K'.$row);
            $drawing->setOffsetX(10);
            $drawing->setOffsetY(5);
            $drawing->setWorksheet($sheet); // <---- INI WAJIB ADA DI DALAM LOOP
        } else {
            $sheet->setCellValue('K'.$row, 'Foto tidak ditemukan');
        }
    } else {
        $sheet->setCellValue('K'.$row, 'Tidak ada foto');
    }

    $sheet->getStyle('A'.$row.':K'.$row)->applyFromArray([
        'alignment' => [
            'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            'vertical'   => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
            'wrapText'   => true
        ],
        'borders' => [
            'allBorders' => [
                'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                'color' => ['argb' => 'FF000000']
            ]
        ]
    ]);

    $row++;
}

// Pastikan kolom K cukup lebar untuk gambar
$sheet->getColumnDimension('K')->setWidth(20);


    // --- Auto Size ---
    // UBAH: Hanya Auto Size kolom A-J. Kolom K (Foto) diatur ukurannya secara manual.
    foreach (range('A', 'J') as $col) {
        $sheet->getColumnDimension($col)->setAutoSize(true);
    }
    
    // TAMBAH: Atur lebar kolom K secara manual agar foto terlihat jelas
    $sheet->getColumnDimension('K')->setWidth(15); 

    // --- Output ---
    $writer = new Xlsx($spreadsheet);
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="Laporan_Barang_Masuk_'.date('Ymd_His').'.xlsx"');
    header('Cache-Control: max-age=0'); 
    $writer->save('php://output');
    exit;
}


// ===================== EXPORT PDF =====================
public function export_pdf() {
    $search = $this->input->get('search');
    $tanggal = $this->input->get('tanggal');

    $this->db->select('*');
    $this->db->from('barang_masuk');

    if (!empty($search)) {
        $this->db->group_start()
            ->like('nama_pengirim', $search)
            ->or_like('nama_vendor', $search)
            ->group_end();
    }

    if (!empty($tanggal)) {
        $this->db->where('tanggal', $tanggal);
    }

    // bagian sebelum render
$data['barang_masuk'] = $this->db->get()->result();

// tambahkan konversi gambar -> data URI
foreach ($data['barang_masuk'] as &$item) {
    $item->foto_data = null;
    if (!empty($item->foto)) {
        $full = FCPATH . 'uploads/barang/' . $item->foto;
        if (file_exists($full)) {
            $mime = mime_content_type($full) ?: 'image/jpeg';
            $dataContent = base64_encode(file_get_contents($full));
            $item->foto_data = "data:{$mime};base64,{$dataContent}";
        }
    }
}
// Muat tampilan
$html = $this->load->view('barang_masuk/pdf_view', $data, TRUE);

// Optionally: enable remote if you still use external resources (fonts/CSS)


$options = new Options();
$options->set('isRemoteEnabled', true); // IZINKAN akses remote
$dompdf = new Dompdf($options);

$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
$dompdf->stream('Laporan_Barang_Masuk_' . date('YmdHis') . '.pdf', ["Attachment" => 1]);

} 


    // ===================== UPLOAD FOTO =====================
    private function _upload_foto() {
        if (empty($_FILES['foto']['name'])) return null;

        $config['upload_path']   = './uploads/barang/';
        $config['allowed_types'] = 'jpg|jpeg|png';
        $config['max_size']      = 2048;
        $config['file_name']     = time().'-'.$_FILES['foto']['name'];

        $this->upload->initialize($config);
        return ($this->upload->do_upload('foto')) ? $this->upload->data('file_name') : null;
    }
}
