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

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

class Produksi extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

        if (isset($this->session->id_user) == false) {
            redirect(base_url('Auth'));
        }

        $this->load->library('Pdf');
        $this->load->model('M_sql');
        $this->load->model('M_Produksi');
        $this->load->model('M_pengaturan');
    }

    public function lotfg()
    {
        $id = $this->session->id_user;
        $akses = $this->db->get_where('tb_akses', ['id_menu' => 7, "akses" => 1, "id_user" => $id])->row_array();

        $grup = $this->db->get('tb_group_menu')->result_array();
        $sub = $this->db->get('tb_sub_menu')->result_array();
        $usr = $this->M_pengaturan->tb_akses($id);
        $mesin = $this->db->get("tb_mesin")->result_array();
        $fg = $this->db->get("tb_fg")->result_array();
        $this->load->view('header', ["grup" => $grup, "sub" => $sub, "usr" => $usr, "akses" => $akses]);
        if (isset($akses['id'])) {
            $this->load->view('produksi-lotfg', ["mesin" => $mesin, "fg" => $fg]);
        } else {
            $this->load->view('halaman_404');
        }
        $this->load->view('footer');
    }

    public function tb_lotfg()
    {
        $id = $this->session->id_user;
        $akses = $this->db->get_where('tb_akses', ['id_menu' => 7, "akses" => 1, "id_user" => $id])->row_array();
        $mulai = $this->input->get('mulai');
        $hingga = $this->input->get('hingga');
        $datalotfg = $this->M_Produksi->tb_lotfg($mulai, $hingga);
        $brg = $this->db->get("tb_fg")->result_array();
        $mesin = $this->db->get("tb_mesin")->result_array();
        $this->load->view('produksi-tblotfg', ["resultlot" => $datalotfg, "brglot" => $brg, "resultmesin" => $mesin, "akses" => $akses]);
    }

    public function tb_lotfg_xls()
    {
        $mulai = $this->input->get('mulai');
        $hingga = $this->input->get('hingga');

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $datalotfg = $this->M_Produksi->tb_lotfg($mulai, $hingga);
        $brg = $this->db->get("tb_fg")->result_array();
        $mesin = $this->db->get("tb_mesin")->result_array();

        $i = 2;
        $no = 1;
        $sheet->setCellValue('A1', 'No.');
        $sheet->setCellValue('B1', 'SKU');
        $sheet->setCellValue('C1', 'Nama Barang');
        $sheet->setCellValue('D1', 'Tgl');
        $sheet->setCellValue('E1', 'Shift');
        $sheet->setCellValue('F1', 'No Mesin');
        $sheet->setCellValue('G1', 'Jumlah Kardus');
        $sheet->setCellValue('H1', 'Tgl Transfer');
        foreach ($datalotfg as $l) {
            $sheet->setCellValue('A' . $i, $no++);
            $sheet->setCellValue('B' . $i, $l['sku']);
            $sheet->setCellValue('C' . $i, $l['barang']);
            $sheet->setCellValue('D' . $i, $l['tanggal']);
            $sheet->setCellValue('E' . $i, $l['shift']);
            $sheet->setCellValue('F' . $i, $l['mesin']);
            $sheet->setCellValue('G' . $i, $l['nomor']);
            $sheet->setCellValue('H' . $i, $l['tgl_transfer']);
            $i++;
        }
        $styleArray = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                ],
            ],
        ];
        $i = $i - 1;
        $sheet->getStyle('A1:H' . $i)->applyFromArray($styleArray);

        $writer = new Xlsx($spreadsheet);
        $filename = 'Laporan_LOT_FG.xlsx';

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

        $writer->save('php://output'); // Unduh file ke browser
        exit;
    }

    public function cetaklotfg()
    {
        $id = $this->input->get('id');
        $datalot = $this->M_Produksi->cetaklot($id);

        $leftMargin = 1;
        $topMargin = 1;
        $rightMargin = 1;
        $bottomMargin = 1;
        $custom_format = array(100, 80); // Landscape: lebar 100mm, tinggi 80mm
        // Inisialisasi TCPDF
        $pdf = new TCPDF('L', 'mm', $custom_format, true, 'UTF-8', false); // 'L' untuk landscape
        $pdf->SetMargins($leftMargin, $topMargin, $rightMargin);
        $pdf->SetAutoPageBreak(false, $bottomMargin);
        $pdf->AddPage();

        $style = array(
            'position' => '',
            'align' => '',
            'stretch' => true,
            'fitwidth' => false,
            'cellfitalign' => '',
            'border' => true,
            'hpadding' => 'auto',
            'vpadding' => 'auto',
            'fgcolor' => array(0, 0, 0),
            'bgcolor' => array(255, 255, 255),
            'text' => true,
            'font' => 'helvetica',
            'fontsize' => 20,
            'stretchtext' => 4
        );

        // Lebar dan tinggi yang tersedia setelah margin
        $available_width = 100 - ($leftMargin + $rightMargin);  // 100 mm - 2 mm
        $available_height_per_barcode = (80 - ($topMargin + $bottomMargin)) / 2;  // 80 mm - 2 mm, dibagi 2

        // Perulangan untuk data yang dihasilkan, memastikan dua barcode per halaman
        foreach ($datalot as $index => $d) {
            if ($index % 2 == 0 && $index > 0) {
                $pdf->AddPage(); // Tambah halaman baru setelah dua barcode        
            }

            $yPosition = $index % 2 == 0 ? $topMargin : $topMargin + $available_height_per_barcode;

            // Menulis barcode
            $pdf->write1DBarcode($d['lotfg'], 'C128', $leftMargin, $yPosition, $available_width, $available_height_per_barcode - 5, 0.6, $style, 'N');

            // Menulis warna di bawah barcode
            $pdf->SetXY($leftMargin, $yPosition + $available_height_per_barcode - 5);
            $pdf->Cell($available_width, 5, $d['warna'], 1, 1, 'C');
        }

        $pdf->Output('lotnumber.pdf', 'I');
    }

    public function simpanlotfg()
    {
        $brglot = $this->input->post('brglot');
        $tgllot = $this->input->post('tgllot');
        $shiftlot = $this->input->post('shiftlot');
        $mesinlot = $this->input->post('mesinlot');
        $qtylot = $this->input->post('qtylot');
        $data = array(
            'shift' => $shiftlot,
            'tgl' => $tgllot,
            'kd_mesin' => $mesinlot,
            'nomor' => $qtylot,
            'sku' => $brglot
        );
        $this->db->insert('tb_lot', $data);
    }

    public function tfgudang()
    {
        $fg = $this->input->post('id');
        $tfid = $this->input->post('tfid');
        $this->db->query("call tf_gudang(" . $fg . ",'" . $tfid . "');");
    }

    public function update_lot()
    {
        $id = $this->input->post('id');
        $sku = $this->input->post('sku');
        $sift = $this->input->post('sift');
        $mesin = $this->input->post('mesin');

        $data = array(
            'shift' => $sift,
            'sku' => $sku,
            'kd_mesin' => $mesin
        );
        $this->db->where('id', $id);
        $this->db->update('tb_lot', $data);

        $data = array(
            'sku' => $sku
        );
        $this->db->where('id_produksi', $id);
        $this->db->update('tb_fg_gudang', $data);
    }

    public function update_lot_gudang()
    {
        $id = $this->input->post('id');
        $sku = $this->input->post('sku');
        $sift = $this->input->post('sift');
        $mesin = $this->input->post('mesin');

        $data = array(
            'shift' => $sift,
            'sku' => $sku,
            'kd_mesin' => $mesin
        );
        $this->db->where('id', $id);
        $this->db->update('tb_lot', $data);

        $data = array(
            'sku' => $sku
        );
        $this->db->where('id_produksi', $id);
        $this->db->update('tb_fg_gudang', $data);
    }

    public function tb_void()
    {
        $id = $this->input->get('id');
        $datalot = $this->M_Produksi->lotvoid($id);
        $this->load->view('tb_void', ["data" => $datalot, "id" => $id]);
    }

    public function void_lot()
    {
        $id = $this->session->id_user;
        $lot = $this->input->post('pilihan');
        $sku = $this->input->post('sku');
        $ket = $this->input->post('keterangan_void');
        $token = sha1($sku . date('Y-m-d H:i:s'));
        $id_apprv = $this->db->get('tb_usr_apprv')->row_array();
        $nama_approval = $this->db->get_where('employee', ['emp_id' => $id_apprv['id_emp']])->row_array();
        if (isset($lot)) {
            $jml = count($lot);
            for ($no = 0; $no < $jml; $no++) {
                $data = array(
                    'no_lot' => $lot[$no],
                    'tgl' => date('Y-m-d H:i:s'),
                    'usr' => $id,
                    'keterangan' => $ket,
                    'sts' => 1,
                    'sku' => $sku,
                    'token' => $token,
                    'id_apprv' => $id_apprv['id_emp']
                );
                $this->db->insert('tb_void_lot', $data);
            }

            $url = base_url('Approve/online_void_lot?key=') . $token;
            $data = $this->M_Produksi->tb_void($token);
            $dtl = $this->db->get_where('tb_void_lot', ["token" => $token])->result_array();
            $pesan = "<style>
            table {
                width: 100%;
                border-collapse: collapse;
                margin: 20px 0;
                font-family: Arial, sans-serif;
            }
            th, td {
                border: 1px solid #dddddd;
                text-align: left;
                padding: 8px;
            }
            th {
                background-color: #f2f2f2;
                color: #333;
            }
            tr:nth-child(even) {
                background-color: #f9f9f9;
            }
            tr:hover {
                background-color: #f1f1f1;
            }
            caption {
                font-weight: bold;
                margin-bottom: 10px;
            }
            .button {
                    display: inline-block;
                    padding: 10px 20px;
                    margin: 10px 0;
                    font-size: 16px;
                    color: #fff;
                    background-color: #007BFF;
                    text-decoration: none;
                    border-radius: 5px;
                }

                .button:hover {
                    background-color: #0056b3;
                }
            </style>";
            $pesan .= "Dear " . $nama_approval['FullName'] . "<br>";
            $pesan .= "I hope this message find you well, please void this transaction below : ";
            $pesan .= '<a href="' . $url . '" class="button">Click me for approve void directly</a>';
            $pesan .= "<table>";
            $pesan .= "<thead>";
            $pesan .= "<tr>";
            $pesan .= "<th style='width: 120px;'>SKU</th>";
            $pesan .= "<th>" . htmlspecialchars($data['sku']) . "</th>";
            $pesan .= "</tr>";
            $pesan .= "<tr>";
            $pesan .= "<th style='width: 120px;'>Item</th>";
            $pesan .= "<th>" . htmlspecialchars($data['barang']) . "</th>";
            $pesan .= "</tr>";
            $pesan .= "<tr>";
            $pesan .= "<th style='width: 120px;'>Date</th>";
            $pesan .= "<th>" . htmlspecialchars($data['tgl']) . "</th>";
            $pesan .= "</tr>";
            $pesan .= "<tr>";
            $pesan .= "<th style='width: 120px;'>Description</th>";
            $pesan .= "<th>" . htmlspecialchars($data['keterangan']) . "</th>";
            $pesan .= "</tr>";
            $pesan .= "<tr>";
            $pesan .= "<th style='width: 120px;'>#</th>";
            $pesan .= "<th>Nomor LOT</th>";
            $pesan .= "</tr>";
            $pesan .= "</thead>";
            $pesan .= "<tbody>";
            $i = 1;
            foreach ($dtl as $d) {
                $pesan .= "<tr>";
                $pesan .= "<td>" . htmlspecialchars($i) . "</td>";
                $pesan .= "<td>" . htmlspecialchars($d['no_lot']) . "</td>";
                $pesan .= "</tr>";
                $i++;
            }
            $pesan .= "</tbody>";
            $pesan .= "</table>";
            $pesan .= "Best Regards";

            //echo $pesan;

            //$to_email = 'krisna.it@tpc-pack.com';
            $to_email = $nama_approval['Email'];
            $subjek = '[Produksi] Void Lot number request';
            $from_email = 'mailapps@tpc-pack.com';

            $config = [
                'protocol'  => 'smtp',
                'smtp_host' => $this->config->item('smtp'),
                'smtp_crypto' => 'tls',
                'smtp_timeout' => '4',
                'smtp_port'   => 587,
                'smtp_user' => $this->config->item('email'),
                'smtp_pass' => $this->config->item('pass'),
                'mailtype'  => 'html',
                'charset' => 'utf-8'
            ];

            $this->load->library('email');
            $this->email->initialize($config);
            $this->email->set_newline("\r\n");
            $this->email->set_crlf("\r\n");

            $this->email->from($from_email, 'LPBJ Notification');
            $this->email->to($to_email);
            $this->email->subject($subjek);
            $this->email->message($pesan);

            if ($this->email->send()) {
            } else {
                echo $this->email->print_debugger();
            }
        }
    }

    public function open_lot()
    {
        $lot = $this->input->post('lot');
        $this->db->delete('tb_void_lot', ['no_lot' => $lot]);
    }

    public function halaman_void()
    {
        $this->load->view('halaman_void');
    }
}
