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

class Tamu extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('session');
        if (!$this->session->userdata('logged_in')) { redirect('auth'); }
        $this->load->model('Tamu_model');
        $this->load->model('TamuFoto_model');
    }

    // Cek apakah user adalah warga biasa (bukan admin/pengurus)
    private function _is_warga_only() {
        $role = $this->session->userdata('role');
        return ($role === 'warga');
    }

    private function _deny_warga() {
        if ($this->_is_warga_only()) {
            $this->session->set_flashdata('error', 'Akses ditolak. Warga hanya bisa melihat data tamu.');
            redirect('tamu');
        }
    }

    // ─── INDEX ────────────────────────────────────────────────
    public function index() {
        $params = [
            'status'  => $this->input->get('status'),
            'tipe'    => $this->input->get('tipe'),
            'tanggal' => $this->input->get('tanggal'),
            'keyword' => $this->input->get('q'),
        ];
        $data['title']     = 'E-Visitor';
        $data['tamu']      = $this->Tamu_model->get_filter($params);
        $data['statistik'] = $this->Tamu_model->get_statistik();
        $data['filter']    = $params;
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('tamu/index', $data);
        $this->load->view('templates/footer');
    }

    // ─── REGISTRASI FORM ──────────────────────────────────────
    public function registrasi() {
        $this->_deny_warga();
        $data['title'] = 'Registrasi Tamu';
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('tamu/registrasi', $data);
        $this->load->view('templates/footer');
    }

    // ─── SIMPAN REGISTRASI ────────────────────────────────────
    public function simpan() {
        $this->_deny_warga();
        $tipe = $this->input->post('tipe_kunjungan') ?: 'singkat';

        // Fix: datetime-local kirim format "2026-03-15T14:30", MySQL butuh "2026-03-15 14:30:00"
        $checkin_raw = $this->input->post('checkin_at');
        if (!empty($checkin_raw)) {
            // Ganti T dengan spasi, tambah detik jika belum ada
            $checkin_raw = str_replace('T', ' ', $checkin_raw);
            if (strlen($checkin_raw) === 16) $checkin_raw .= ':00';
            $checkin = $checkin_raw;
        } else {
            $checkin = date('Y-m-d H:i:s');
        }

        $data = [
            'nama_tamu'        => $this->input->post('nama_tamu'),
            'nik_tamu'         => $this->input->post('nik_tamu') ?: null,
            'no_hp'            => $this->input->post('no_hp') ?: null,
            'no_kendaraan'     => $this->input->post('no_kendaraan') ?: null,
            'jenis_kendaraan'  => $this->input->post('jenis_kendaraan') ?: null,
            'tujuan_blok'      => $this->input->post('tujuan_blok') ?: null,
            'nama_tuan_rumah'  => $this->input->post('nama_tuan_rumah') ?: null,
            'keperluan'        => $this->input->post('keperluan') ?: 'kunjungan',
            'keperluan_detail' => $this->input->post('keperluan_detail') ?: null,
            'tipe_kunjungan'   => $tipe,
            'checkin_at'       => $checkin,
            'rencana_checkout' => ($tipe === 'menginap' && $this->input->post('rencana_checkout'))
                                   ? $this->input->post('rencana_checkout') : null,
            'status'           => 'checkin',
            'catatan'          => $this->input->post('catatan') ?: null,
            'dicatat_oleh'     => $this->session->userdata('user_id'),
        ];

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

        // ── Upload multi foto ──
        $ada_foto = !empty($_FILES['foto_tamu']['name'])
                    && is_array($_FILES['foto_tamu']['name'])
                    && !empty($_FILES['foto_tamu']['name'][0])
                    && $_FILES['foto_tamu']['error'][0] !== UPLOAD_ERR_NO_FILE;

        if ($ada_foto) {
            $label  = $this->input->post('foto_label') ?: null;
            $result = $this->TamuFoto_model->upload_batch($tamu_id, $_FILES['foto_tamu'], $label);

            if (!empty($result['fail'])) {
                // Tampilkan warning tapi tetap redirect (data tamu sudah tersimpan)
                $this->session->set_flashdata('warning',
                    'Tamu tersimpan, tapi ' . count($result['fail']) . ' foto gagal: '
                    . implode(', ', $result['fail'])
                );
                redirect('tamu');
                return;
            }
        }

        $this->session->set_flashdata('success', 'Tamu berhasil dicatat. Check-in berhasil!');
        redirect('tamu');
    }

    // ─── CHECKOUT ─────────────────────────────────────────────
    public function checkout($id) {
        $this->_deny_warga();
        $this->Tamu_model->checkout($id);
        $this->session->set_flashdata('success', 'Tamu berhasil checkout.');
        redirect('tamu');
    }

    // ─── CHECKOUT AJAX ────────────────────────────────────────
public function checkout_ajax() {
    header('Content-Type: application/json');
    if ($this->_is_warga_only()) {
        echo json_encode(['status'=>'error','msg'=>'Akses ditolak']); return;
    }
    $id = (int) $this->input->post('id');
    if (!$id) { echo json_encode(['status'=>'error','msg'=>'ID tidak valid']); return; }

    $this->Tamu_model->checkout($id);       // simpan dengan app_now() = timezone benar
    $tamu = $this->Tamu_model->get_by_id($id); // ambil kembali dari DB

    echo json_encode([
        'status'      => 'ok',
        'msg'         => 'Checkout berhasil',
        'checkout_at' => $tamu->checkout_at  // "2026-03-16 11:30:00" sudah timezone benar
    ]);
}

    // ─── DETAIL ───────────────────────────────────────────────
    public function detail($id) {
        $data['title'] = 'Detail Tamu';
        $data['tamu']  = $this->Tamu_model->get_by_id($id);
        if (!$data['tamu']) { redirect('tamu'); }
        $data['fotos'] = $this->TamuFoto_model->get_by_tamu($id);
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('tamu/detail', $data);
        $this->load->view('templates/footer');
    }

    // ─── UPLOAD FOTO (AJAX – bisa dari detail page) ───────────
    public function upload_foto($tamu_id) {
        header('Content-Type: application/json');
        if ($this->_is_warga_only()) {
            echo json_encode(['status'=>'error','msg'=>'Akses ditolak']); return;
        }
        $tamu = $this->Tamu_model->get_by_id($tamu_id);
        if (!$tamu) { echo json_encode(['status'=>'error','msg'=>'Tamu tidak ditemukan']); return; }
        if (empty($_FILES['foto']['name']) || (is_array($_FILES['foto']['name']) && empty($_FILES['foto']['name'][0]))) {
            echo json_encode(['status'=>'error','msg'=>'Tidak ada file yang diupload']); return;
        }

        $label  = $this->input->post('label') ?: null;
        $result = $this->TamuFoto_model->upload_batch($tamu_id, $_FILES['foto'], $label);

        // Kembalikan data foto terbaru untuk update UI
        $fotos = $this->TamuFoto_model->get_by_tamu($tamu_id);
        $list  = [];
        foreach ($fotos as $f) {
            $list[] = [
                'id'       => $f->id,
                'url'      => base_url('uploads/foto_tamu/' . $f->nama_file),
                'label'    => $f->label,
                'created'  => date('d/m/Y H:i', strtotime($f->created_at)),
            ];
        }

        echo json_encode([
            'status'    => 'ok',
            'uploaded'  => count($result['ok']),
            'failed'    => $result['fail'],
            'fotos'     => $list,
            'total'     => count($fotos),
        ]);
    }

    // ─── HAPUS SATU FOTO (AJAX) ───────────────────────────────
    public function hapus_foto() {
        header('Content-Type: application/json');
        if ($this->_is_warga_only()) {
            echo json_encode(['status'=>'error','msg'=>'Akses ditolak']); return;
        }
        $foto_id = (int) $this->input->post('foto_id');
        if (!$foto_id) { echo json_encode(['status'=>'error','msg'=>'ID foto tidak valid']); return; }

        $foto = $this->TamuFoto_model->get_by_id($foto_id);
        if (!$foto) { echo json_encode(['status'=>'error','msg'=>'Foto tidak ditemukan']); return; }

        $this->TamuFoto_model->delete($foto_id);
        $total = $this->TamuFoto_model->count_by_tamu($foto->tamu_id);
        echo json_encode(['status'=>'ok','msg'=>'Foto dihapus','total'=>$total]);
    }

    // ─── UPDATE LABEL FOTO (AJAX) ─────────────────────────────
    public function update_label_foto() {
        header('Content-Type: application/json');
        $foto_id = (int) $this->input->post('foto_id');
        $label   = $this->security->xss_clean($this->input->post('label'));
        if (!$foto_id) { echo json_encode(['status'=>'error']); return; }
        $this->TamuFoto_model->update_label($foto_id, $label ?: null);
        echo json_encode(['status'=>'ok','label'=>$label]);
    }

    // ─── EDIT FORM ────────────────────────────────────────────
    public function edit($id) {
        $this->_deny_warga();
        $data['title'] = 'Edit Data Tamu';
        $data['tamu']  = $this->Tamu_model->get_by_id($id);
        if (!$data['tamu']) {
            $this->session->set_flashdata('error', 'Data tamu tidak ditemukan');
            redirect('tamu');
        }
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('tamu/edit', $data);
        $this->load->view('templates/footer');
    }

    // ─── UPDATE DATA ──────────────────────────────────────────
    public function update($id) {
        $this->_deny_warga();

        $tamu = $this->Tamu_model->get_by_id($id);
        if (!$tamu) { redirect('tamu'); }

        $tipe = $this->input->post('tipe_kunjungan') ?: 'singkat';

        // Fix datetime-local format
        $checkin_raw = $this->input->post('checkin_at');
        if (!empty($checkin_raw)) {
            $checkin = str_replace('T', ' ', $checkin_raw);
            if (strlen($checkin) === 16) $checkin .= ':00';
        } else {
            $checkin = $tamu->checkin_at;
        }

        // Checkout jika diisi
        $checkout_raw = $this->input->post('checkout_at');
        $checkout = null;
        if (!empty($checkout_raw)) {
            $checkout = str_replace('T', ' ', $checkout_raw);
            if (strlen($checkout) === 16) $checkout .= ':00';
        }

        $data = [
            'nama_tamu'        => $this->input->post('nama_tamu'),
            'nik_tamu'         => $this->input->post('nik_tamu') ?: null,
            'no_hp'            => $this->input->post('no_hp') ?: null,
            'no_kendaraan'     => $this->input->post('no_kendaraan') ?: null,
            'jenis_kendaraan'  => $this->input->post('jenis_kendaraan') ?: null,
            'tujuan_blok'      => $this->input->post('tujuan_blok') ?: null,
            'nama_tuan_rumah'  => $this->input->post('nama_tuan_rumah') ?: null,
            'keperluan'        => $this->input->post('keperluan') ?: 'kunjungan',
            'keperluan_detail' => $this->input->post('keperluan_detail') ?: null,
            'tipe_kunjungan'   => $tipe,
            'checkin_at'       => $checkin,
            'checkout_at'      => $checkout,
            'rencana_checkout' => ($tipe === 'menginap' && $this->input->post('rencana_checkout'))
                                   ? $this->input->post('rencana_checkout') : null,
            'status'           => $checkout ? 'checkout' : $this->input->post('status'),
            'catatan'          => $this->input->post('catatan') ?: null,
        ];

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

    // ─── HAPUS DATA TAMU ──────────────────────────────────────
    public function hapus($id) {
        if ($this->session->userdata('role') !== 'admin') {
            $this->session->set_flashdata('error', 'Akses ditolak');
            redirect('tamu');
        }
        // Hapus semua foto dulu
        $this->TamuFoto_model->delete_by_tamu($id);
        $this->Tamu_model->delete($id);
        $this->session->set_flashdata('success', 'Data tamu dihapus.');
        redirect('tamu');
    }
}