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

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

class Tamu_controller extends CI_Controller {

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

    // Biarkan publik akses method tertentu tanpa login
    $allowed_methods = ['form', 'simpan', 'simpan_ajax'];
    if (!$this->session->userdata('logged_in') && !in_array($this->router->fetch_method(), $allowed_methods)) {
        redirect('auth');
    }
}
 

      // Daftar tamu (index)
 public function index() { 
    $keyword        = $this->input->get('keyword');
    $tanggal_dari   = $this->input->get('tanggal_dari');
    $tanggal_sampai = $this->input->get('tanggal_sampai');
    $location       = $this->input->get('location'); // <--- PERBAIKAN: Ambil variabel location

    $this->db->from('tamu');

    // Filter keyword
    if (!empty($keyword)) {
        $this->db->group_start();
        $this->db->like('nama', $keyword);
        $this->db->or_like('instansi', $keyword);
        $this->db->or_like('keperluan', $keyword);
        $this->db->group_end();
    }

    // Filter tanggal
    if (!empty($tanggal_dari) && !empty($tanggal_sampai)) {
        $this->db->where("DATE(created_at) >=", $tanggal_dari);
        $this->db->where("DATE(created_at) <=", $tanggal_sampai);
    }
    
    // Filter Lokasi <--- PERBAIKAN: Logika Filter Lokasi
    if (!empty($location)) {
        $this->db->where('location', $location);
    }
    // End Filter Lokasi

    // Urutkan berdasarkan tanggal terbaru
    $this->db->order_by('created_at', 'DESC');
    $query = $this->db->get();
    $data['tamu'] = $query->result();

    // Pilih view sesuai role (sesuaikan nama view dengan yang kamu pakai)
    if ($this->session->userdata('role') == 'admin') {
        $this->load->view('tamu/list_tamu', $data); // versi admin CRUD (ini file kamu, tidak diubah)
    } else {
        $this->load->view('tamu/list_tamu_user', $data); // versi user tanpa CRUD
    }

    }

    // Form tamu publik
    public function form() {
        $data['no_tamu'] = $this->Tamu_model->generate_no_tamu();
        $this->load->view('tamu/form_tamu');
    }

    // Simpan versi AJAX
     public function simpan_ajax(){
        $data = [
            
            'nama' => $this->input->post('nama'),
            'instansi' => $this->input->post('instansi'),
            'no_handphone' => $this->input->post('no_handphone'),
            'no_visitor' => $this->input->post('no_visitor'),
            'no_tamu' => $this->input->post('no_tamu'),
            'keperluan' => $this->input->post('keperluan'),
            'location' => $this->input->post('location'), // sekarang diambil dari pilihan dropdown
            'created_at' => date('Y-m-d H:i:s'),
            'waktu_masuk' => date('H:i:s'),
        ];

        $insert = $this->Tamu_model->insert_tamu($data);

        if ($insert) {
            echo json_encode(['status' => 'success', 'message' => 'Data tamu berhasil disimpan!']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Gagal menyimpan data tamu.']);
        }
    }

    // Simpan normal
    public function simpan() {
        $data = [
            'nama'       => $this->input->post('nama'),
            'instansi'   => $this->input->post('instansi'),
            'no_handphone'=> $this->input->post('no_handphone'),
            'no_visitor' => $this->input->post('no_visitor'),
            'no_tamu'    => $this->input->post('no_tamu'),
            'keperluan'  => $this->input->post('keperluan'),
            'location'   => $this->input->post('location'),
            'waktu_masuk'=> $this->input->post('waktu_masuk'),
            'created_at' => date('Y-m-d H:i:s')
        ];

        $this->Tamu_model->insert($data);

        $this->session->set_flashdata('success', 'Data tamu berhasil disimpan.');
        redirect('tamu_controller');
    }

    // Edit
    public function edit($id) {
        $data['tamu'] = $this->Tamu_model->get_by_id($id);
        if (!$data['tamu']) {
            show_404();
        }
        $this->load->view('tamu/edit_tamu', $data);
    }

    // Update
public function update($id) {
    $data = [
        'nama'         => $this->input->post('nama'),
        'instansi'     => $this->input->post('instansi'),
        'no_handphone'=> $this->input->post('no_handphone'),
        'no_visitor'   => $this->input->post('no_visitor'),
        'no_tamu'      => $this->input->post('no_tamu'),
        'keperluan'    => $this->input->post('keperluan'),
        'location'     => $this->input->post('location'), 
        'waktu_masuk'  => $this->input->post('waktu_masuk'),
        'waktu_keluar' => $this->input->post('waktu_keluar'),
    ];

    $this->Tamu_model->update($id, $data);
    $this->session->set_flashdata('success', 'Data tamu berhasil diupdate.');
    redirect('tamu_controller');
}


    // Hapus
    public function hapus($id) { 
        $this->Tamu_model->delete($id);
        $this->session->set_flashdata('success', 'Data tamu berhasil dihapus.');
        redirect('tamu_controller');
    }

    // Input keluar (set waktu_keluar)
    public function keluar($id) {
        $data = [
            'waktu_keluar' => $this->input->post('waktu_keluar'),
            'checkout_by'  => $this->input->post('checkout_by'),
        ];
        $this->Tamu_model->update($id, $data);
        $this->session->set_flashdata('success', 'Waktu keluar berhasil ditambahkan.');
        redirect('tamu_controller');
    }

    // versi user list
    public function list_tamu_user() {
        $this->db->order_by('created_at', 'DESC');
        $query = $this->db->get('tamu');
        $data['tamu'] = $query->result();
        $this->load->view('tamu/list_tamu_user', $data);
    }

    public function form_tamu_user($id = null) {
        if ($id) {
            $data['tamu'] = $this->db->get_where('tamu', ['id' => $id])->row();
        } else {
            $data['tamu'] = null;
        }
        $this->load->view('tamu/form_tamu_user', $data);
    }

    public function simpan_user() {
        $waktu_keluar = $this->input->post('waktu_keluar');
        $data = [
            'nama'        => $this->input->post('nama'),
            'instansi'    => $this->input->post('instansi'),
            'no_handphone'=> $this->input->post('no_handphone'),
            'no_visitor'       => $this->input->post('no_visitor'),
            'no_tamu'     => $this->input->post('no_tamu'),
            'keperluan'   => $this->input->post('keperluan'),
            'waktu_masuk' => $this->input->post('waktu_masuk'),
            'waktu_keluar'=> !empty($waktu_keluar) ? $waktu_keluar : NULL,
            'created_at'  => date('Y-m-d H:i:s')
        ];
        $this->db->insert('tamu', $data);
        $this->session->set_flashdata('success', 'Data tamu berhasil ditambahkan!');
        redirect('tamu_controller');
    }

    public function update_user($id) {
    $waktu_keluar = $this->input->post('waktu_keluar');
    $data = [
        'nama'        => $this->input->post('nama'),
        'instansi'    => $this->input->post('instansi'),
        'no_handphone'=> $this->input->post('no_handphone'),
        'no_visitor'  => $this->input->post('no_visitor'),
        'no_tamu'     => $this->input->post('no_tamu'),
        'keperluan'   => $this->input->post('keperluan'),
        'location'    => $this->input->post('location'), // <= tambahkan ini
        'waktu_masuk' => $this->input->post('waktu_masuk'),
        'waktu_keluar'=> !empty($waktu_keluar) ? $waktu_keluar : NULL
    ];
    $this->db->where('id', $id);
    $this->db->update('tamu', $data);
    $this->session->set_flashdata('success', 'Data tamu berhasil diperbarui!');
    redirect('tamu_controller');
}


    // EXPORT EXCEL (menggunakan PhpSpreadsheet)
   public function export_excel()
{
    // =========================
    // 1️⃣ Ambil Parameter Filter
    // =========================
    $keyword        = $this->input->get('keyword');
    $tanggal_dari   = $this->input->get('tanggal_dari');
    $tanggal_sampai = $this->input->get('tanggal_sampai');
    $location       = $this->input->get('location');

    // Ambil data dari model (pastikan model menerima filter)
    $filter = [
        'tanggal_awal'  => $tanggal_dari,
        'tanggal_akhir' => $tanggal_sampai,
        'keyword'       => $keyword,
        'location'      => $location,
    ];
    $dataTamu = $this->Tamu_model->get_all($filter);

    // =========================
    // 2️⃣ Inisialisasi Spreadsheet
    // =========================
    $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setTitle('Laporan Buku Tamu');
    $sheet->getPageSetup()
          ->setOrientation(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE)
          ->setPaperSize(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4);

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

    // =========================
    // 4️⃣ Judul, Periode, dan Dicetak Oleh
    // =========================
    $sheet->mergeCells('C1:K1');
    $sheet->setCellValue('C1', 'LAPORAN BUKU TAMU VISITORS');
    $sheet->getStyle('C1')->getFont()->setBold(true)->setSize(16);
    $sheet->getStyle('C1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

    $tglDari   = !empty($tanggal_dari)   ? date('d F Y', strtotime($tanggal_dari))   : 'Awal Data';
    $tglSampai = !empty($tanggal_sampai) ? date('d F Y', strtotime($tanggal_sampai)) : 'Akhir Data';
    $periodeText = "Periode: {$tglDari} s/d {$tglSampai}";

    $sheet->mergeCells('C2:K2');
    $sheet->setCellValue('C2', $periodeText);
    $sheet->getStyle('C2')->getFont()->setSize(11);
    $sheet->getStyle('C2')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

    // 🧾 Nama user yang mencetak
    $username = $this->session->userdata('nama_lengkap') ?? $this->session->userdata('username') ?? 'Tidak diketahui';
    $sheet->mergeCells('C3:K3');
    $sheet->setCellValue('C3', 'Dicetak oleh: ' . $username . ' | ' . date('d-m-Y H:i'));
    $sheet->getStyle('C3')->getFont()->setSize(10)->setItalic(true);
    $sheet->getStyle('C3')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

    // =========================
    // 5️⃣ Header Tabel (tambahkan No Handphone & Checkout by)
    // =========================
    $startRow = 5;
    $headers = [
        'No', 'Nama', 'Instansi', 'No Handphone', 'ASI No', 'ARK No', 
        'Keperluan', 'Lokasi', 'Tanggal', 'Waktu Masuk', 'Waktu Keluar', 'Checkout By'
    ];
    $sheet->fromArray($headers, NULL, 'A'.$startRow);

    $lastCol = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex(count($headers));

    $headerStyle = [
        'font' => ['bold' => true, 'color' => ['argb' => 'FFFFFFFF']],
        'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,'startColor' => ['argb' => 'FF0D6EFD']],
        'alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER],
        'borders' => ['allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM,'color' => ['argb' => 'FF000000']]]
    ];
    $sheet->getStyle('A'.$startRow.':'.$lastCol.$startRow)->applyFromArray($headerStyle);
    $sheet->getRowDimension($startRow)->setRowHeight(22);

    // =========================
    // 6️⃣ Isi Data
    // =========================
    $row = $startRow + 1;
    $no  = 1;
    foreach ($dataTamu as $tamu) {
        $sheet->setCellValue('A'.$row, $no++);
        $sheet->setCellValue('B'.$row, $tamu->nama);
        $sheet->setCellValue('C'.$row, $tamu->instansi);
        $sheet->setCellValue('D'.$row, $tamu->no_handphone); // 🆕 No Handphone
        $sheet->setCellValue('E'.$row, $tamu->no_visitor);
        $sheet->setCellValue('F'.$row, $tamu->no_tamu);
        $sheet->setCellValue('G'.$row, $tamu->keperluan);
        $sheet->setCellValue('H'.$row, $tamu->location ?? '-');
        $sheet->setCellValue('I'.$row, !empty($tamu->created_at) ? date('d-m-Y', strtotime($tamu->created_at)) : '');
        $sheet->setCellValue('J'.$row, $tamu->waktu_masuk);
        $sheet->setCellValue('K'.$row, $tamu->waktu_keluar);
        $sheet->setCellValue('L'.$row, $tamu->checkout_by ?? ''); // 🆕 Checkout by

        $sheet->getStyle('A'.$row.':'.$lastCol.$row)->applyFromArray([
            'alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER],
            'borders' => ['allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,'color' => ['argb' => 'FF000000']]]
        ]);
        $sheet->getStyle('G'.$row)->getAlignment()->setWrapText(true);
        $sheet->getRowDimension($row)->setRowHeight(18);
        $row++;
    }

    // =========================
    // 7️⃣ Lebar Kolom
    // =========================
    $widths = [5, 20, 20, 15, 10, 10, 25, 15, 12, 12, 12, 15];
    $col = 'A';
    foreach ($widths as $w) {
        $sheet->getColumnDimension($col++)->setWidth($w);
    }

    // =========================
    // 8️⃣ Output Excel
    // =========================
    $filename = 'Laporan_Tamu_' . date('Ymd_His') . '.xlsx';
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    header('Cache-Control: max-age=0');

    $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
    $writer->save('php://output');
    exit;
}


   // EXPORT PDF (pakai Dompdf)
public function export_pdf()
{
    $keyword        = $this->input->get('keyword');
    $tanggal_dari   = $this->input->get('tanggal_dari');
    $tanggal_sampai = $this->input->get('tanggal_sampai');
    $location       = $this->input->get('location');

    // ** Query Database **
    $this->db->from('tamu');

    if (!empty($keyword)) {
        $this->db->group_start();
        $this->db->like('nama', $keyword);
        $this->db->or_like('instansi', $keyword);
        $this->db->or_like('keperluan', $keyword);
        $this->db->group_end();
    }

    if (!empty($tanggal_dari) && !empty($tanggal_sampai)) {
        $this->db->where("DATE(created_at) >=", $tanggal_dari);
        $this->db->where("DATE(created_at) <=", $tanggal_sampai);
    }
    if (!empty($location)) {
        $this->db->where('location', $location);
    }
    // End Filter Lokasi PDF

    // Order
    $this->db->order_by('created_at', 'DESC');

    $tamu_data_mentah = $this->db->get()->result();

    // ** PERBAIKAN: Data Cleaning untuk View PDF **
    $tamu_data_bersih = [];
    foreach ($tamu_data_mentah as $tamu) {
        // 1. Pastikan waktu_keluar statis (bukan tombol/modal)
        if (empty($tamu->waktu_keluar)) {
            $tamu->waktu_keluar = '00:00:00'; 
        }
        // 2. Pastikan properti location ada
        $tamu->location = $tamu->location ?? '-';
        
        $tamu_data_bersih[] = $tamu;
    }
    
    $data['tamu'] = $tamu_data_bersih;
    $data['tanggal_dari'] = $tanggal_dari; 
    $data['tanggal_sampai'] = $tanggal_sampai; 

    // Load view pdf_tamu.php
    $html = $this->load->view('tamu/pdf_tamu', $data, TRUE); // Sesuaikan dengan nama folder/file view Anda
 
    // Inisialisasi Dompdf
    $dompdf = new Dompdf();

// FIX AGAR LOGO MUNCUL
$dompdf->set_option('isRemoteEnabled', true);
$dompdf->set_option('isHtml5ParserEnabled', true);
$dompdf->set_option('isPhpEnabled', true);

$dompdf->setPaper('A4', 'landscape');
$dompdf->loadHtml($html);
$dompdf->render();
$dompdf->stream("data_tamu_".date('Y-m-d').".pdf", ["Attachment" => true]);

}
    // Form admin (example)
    public function form_admin() 
    {
        $data['tamu'] = $this->Tamu_model->get_all();
        $data['no_tamu'] = $this->Tamu_model->generate_no_tamu();
        $this->load->view('tamu/form_tamu_admin');
    }
}
