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

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Dompdf\Dompdf;
use Dompdf\Options;

class Barang_keluar_controller extends CI_Controller {

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

    // ==================== LIST DATA ====================
    public function index() {
        $data['barang_keluar'] = $this->Barang_keluar_model->get_all();

        if ($this->session->userdata('role') == 'admin') {
            $data['total_barang_keluar'] = $this->Barang_keluar_model->count_all();
            $this->load->view('barang_keluar/list_admin', $data);
        } else {
            $this->load->view('barang_keluar/list', $data);
        }
    }

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

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

    // ==================== STORE DATA ====================
    public function store() {
        $this->_rules();

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('barang_keluar/form');
        } else {
            $foto = $this->_upload_foto();

            $data = [
                'pic'          => $this->input->post('pic'),
                'jenis_barang' => $this->input->post('jenis_barang'),
                'jumlah'       => $this->input->post('jumlah'),
                'driver'       => $this->input->post('driver'),
                'origin'       => $this->input->post('origin'), // ← Tambahan
                'tujuan'       => $this->input->post('tujuan'),
                'tanggal'      => $this->input->post('tanggal'),
                'waktu_keluar' => $this->input->post('waktu_keluar'),
                'foto'         => $foto
            ];

            $this->Barang_keluar_model->insert($data);
            $this->session->set_flashdata('success', 'Data barang keluar berhasil disimpan!');
            redirect('barang_keluar_controller');
        }
    }

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

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

    public function update($id) {
        $this->_rules();

        if ($this->form_validation->run() == FALSE) {
            $data['barang'] = $this->Barang_keluar_model->get_by_id($id);
            $this->load->view('barang_keluar/form_edit', $data);
        } else {
            $barang = $this->Barang_keluar_model->get_by_id($id);
            $foto = $barang->foto;

            if (!empty($_FILES['foto']['name'])) {
                $foto = $this->_upload_foto($foto);
            }

            $updateData = [
                'pic'          => $this->input->post('pic'),
                'jenis_barang' => $this->input->post('jenis_barang'),
                'jumlah'       => $this->input->post('jumlah'),
                'driver'       => $this->input->post('driver'),
                'origin'       => $this->input->post('origin'), // ← Tambahan
                'tujuan'       => $this->input->post('tujuan'),
                'tanggal'      => $this->input->post('tanggal'),
                'waktu_keluar' => $this->input->post('waktu_keluar'),
                'foto'         => $foto
            ];

            $this->Barang_keluar_model->update($id, $updateData);
            $this->session->set_flashdata('success', 'Data barang keluar berhasil diperbarui!');
            redirect('barang_keluar_controller');
        }
    }

    // ==================== DELETE ====================
    public function delete($id) {
        $barang = $this->Barang_keluar_model->get_by_id($id);
        if ($barang && $barang->foto && file_exists(FCPATH.'uploads/'.$barang->foto)) {
            unlink(FCPATH.'uploads/'.$barang->foto);
        }

        $this->Barang_keluar_model->delete($id);
        $this->session->set_flashdata('success', 'Data barang keluar berhasil dihapus!');
        redirect('barang_keluar_controller');
    }

    // ==================== VALIDATION RULES ====================
    private function _rules() {
        $this->form_validation->set_rules('pic', 'PIC', 'required');
        $this->form_validation->set_rules('jenis_barang', 'Jenis Barang', 'required');
        $this->form_validation->set_rules('jumlah', 'Jumlah', 'required|integer');
        $this->form_validation->set_rules('driver', 'Driver', 'required');
        $this->form_validation->set_rules('origin', 'Origin', 'required'); // ← Tambahan
        $this->form_validation->set_rules('tujuan', 'Tujuan', 'required');
        $this->form_validation->set_rules('tanggal', 'Tanggal', 'required');
        $this->form_validation->set_rules('waktu_keluar', 'Waktu Keluar', 'required');
    }

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

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

        $this->upload->initialize($config);

        if ($this->upload->do_upload('foto')) {
            if ($old_foto && file_exists(FCPATH.'uploads/'.$old_foto)) {
                unlink(FCPATH.'uploads/'.$old_foto);
            }
            return $this->upload->data('file_name');
        } else {
            $this->session->set_flashdata('error', $this->upload->display_errors());
            redirect(current_url());
            exit;
        }
    }

    // ==================== ADMIN LIST ====================
    public function list_admin() {
        $data['barang_keluar'] = $this->Barang_keluar_model->get_all();
        $data['total_barang_keluar'] = $this->Barang_keluar_model->count_all();
        $this->load->view('barang_keluar/list_admin', $data);
    }

    // ==================== SAVE (INSERT/UPDATE ADMIN) ====================
    public function save($id = null) {
        $this->_rules();

        if ($this->form_validation->run() == FALSE) {
            $id ? $this->edit_admin($id) : $this->form_admin();
        } else {
            $foto = $id ? $this->Barang_keluar_model->get_by_id($id)->foto : null;
            if (!empty($_FILES['foto']['name'])) {
                $foto = $this->_upload_foto($foto);
            }

            $data = [
                'pic'          => $this->input->post('pic'),
                'jenis_barang' => $this->input->post('jenis_barang'),
                'jumlah'       => $this->input->post('jumlah'),
                'driver'       => $this->input->post('driver'),
                'origin'       => $this->input->post('origin'), // ← Tambahan
                'tujuan'       => $this->input->post('tujuan'),
                'tanggal'      => $this->input->post('tanggal'),
                'waktu_keluar' => $this->input->post('waktu_keluar'),
                'foto'         => $foto
            ];

            if ($id) {
                $this->Barang_keluar_model->update($id, $data);
                $this->session->set_flashdata('success', 'Data barang keluar berhasil diperbarui!');
            } else {
                $this->Barang_keluar_model->insert($data);
                $this->session->set_flashdata('success', 'Data barang keluar berhasil disimpan!');
            }

            redirect('barang_keluar_controller/list_admin');
        }
    }

    // ==================== EXPORT EXCEL (tambahkan kolom Origin) ====================
   public function export_excel()
{
    $search  = $this->input->get('search');
    $tanggal = $this->input->get('tanggal');
    $data    = $this->Barang_keluar_model->get_data_with_filters($search, $tanggal);

    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setTitle('Laporan Barang Keluar');

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

    // Placeholder Logo
    $sheet->mergeCells('A1:B4');
    if (file_exists('asset/img/asiaserv-logo.png')) {
        $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
        $drawing->setName('Logo Perusahaan');
        $drawing->setPath('asset/img/asiaserv-logo.png');
        $drawing->setHeight(70);
        $drawing->setCoordinates('A1');
        $drawing->setOffsetX(5);
        $drawing->setOffsetY(5);
        $drawing->setWorksheet($sheet);
    }

    // Judul Laporan
    $sheet->setCellValue('C1', 'LAPORAN DATA BARANG KELUAR');
    $sheet->mergeCells('C1:J1');
    $sheet->getStyle('C1')->getFont()->setBold(true)->setSize(16);
    $sheet->getStyle('C1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

    // Info Cetak
    $sheet->setCellValue('C3', 'Dicetak Oleh: ' . $username);
    $sheet->mergeCells('C3:J3');
    $sheet->setCellValue('C4', 'Tanggal Cetak: ' . $tanggal_cetak);
    $sheet->mergeCells('C4:J4');
    $sheet->getStyle('C3:J4')->getFont()->setBold(true);
    $sheet->getStyle('C3:J4')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
    $sheet->getStyle('C3:J4')->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);

    // Header tabel
    $row_start = 6;
    $headers = [
        'No','PIC','Jenis Barang','Jumlah','Driver',
        'Origin','Tujuan','Tanggal','Waktu Keluar','Foto'
    ];

    $col = 'A';
    foreach ($headers as $h) {
        $sheet->setCellValue($col.$row_start, $h);
        $col++;
    }

    // Styling header
    $sheet->getStyle('A6:J6')->applyFromArray([
        'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
        'fill' => [
            'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
            'startColor' => ['rgb' => 'DC3545']
        ],
        'alignment' => [
            'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
        ],
        'borders' => [
            'allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN],
        ]
    ]);

    // Isi data
    $row = 7;
    $no  = 1;

    foreach ($data as $item) {

        $sheet->setCellValue('A'.$row, $no++);
        $sheet->setCellValue('B'.$row, $item->pic);
        $sheet->setCellValue('C'.$row, $item->jenis_barang);
        $sheet->setCellValue('D'.$row, $item->jumlah);
        $sheet->setCellValue('E'.$row, $item->driver);
        $sheet->setCellValue('F'.$row, $item->origin);
        $sheet->setCellValue('G'.$row, $item->tujuan);
        $sheet->setCellValue('H'.$row, $item->tanggal);
        $sheet->setCellValue('I'.$row, $item->waktu_keluar);

        // ---- FOTO ----
        $fotoFile = $item->foto ?? '';
        $fotoPath = FCPATH . 'uploads/' . $fotoFile;

        if (!empty($fotoFile) && file_exists($fotoPath)) {

            $img = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
            $img->setName('Foto');
            $img->setDescription('Foto');
            $img->setPath($fotoPath);
            $img->setHeight(70);
            $img->setCoordinates('J' . $row);
            $img->setOffsetX(5);
            $img->setOffsetY(5);
            $img->setWorksheet($sheet);

            $sheet->getRowDimension($row)->setRowHeight(55);

        } else {
            $sheet->setCellValue('J'.$row, 'Tidak Ada Foto');
            $sheet->getRowDimension($row)->setRowHeight(20);
        }

        $row++;
    }

    // Border seluruh data
    $sheet->getStyle("A7:J".($row-1))->applyFromArray([
        'borders' => [
            'allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN]
        ],
        'alignment' => [
            'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
        ]
    ]);

    // Lebar kolom
    foreach (range('A', 'I') as $columnID) {
        $sheet->getColumnDimension($columnID)->setAutoSize(true);
    }
    $sheet->getColumnDimension('J')->setWidth(15);

    // Output Excel
    $writer = new Xlsx($spreadsheet);
    $filename = 'Laporan_Barang_Keluar_' . date('YmdHis') . '.xlsx';

    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="' . $filename . '"');
    header('Cache-Control: max-age=0');

    ob_end_clean();
    $writer->save('php://output');
    exit;
}


    // ==================== EXPORT PDF (tambahkan kolom Origin) ====================
public function export_pdf() {
    $search  = $this->input->get('search');
    $tanggal = $this->input->get('tanggal');
    $data['barang_keluar'] = $this->Barang_keluar_model->get_data_with_filters($search, $tanggal);

    $html = $this->load->view('barang_keluar/export_pdf', $data, true);

    $options = new Options();
    $options->set('isRemoteEnabled', true);
    $options->set('isHtml5ParserEnabled', true);

    $dompdf = new Dompdf($options);
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'landscape');
    $dompdf->render();
    $dompdf->stream("export_pdf", ["Attachment" => true]);
}


    // ==================== FORM ADMIN ====================
    public function form_admin() {
        $this->load->view('barang_keluar/form_admin');
    }
}
