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

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

        // Kalau halaman ini hanya untuk internal admin:
        // cek_session_login();

        $this->load->model('StatusBoard_model', 'board');
        $this->load->helper(['url', 'date','form']);
        $this->load->library('session');
    }

    /**
     * Halaman papan status publik.
     * Tanpa ?date => semua transaksi (non-batal, tidak hidden).
     * Dengan ?date => filter 1 tanggal.
     */
    public function index()
    {
		$tanggal = $this->input->get('date', TRUE) ?: null;
		$orders  = $this->board->getOrders($tanggal);

        $title = $tanggal
            ? 'Status Pesanan ' . mdate('%d %F %Y', strtotime($tanggal))
            : 'Status Pesanan (Semua Transaksi)';

        $data = [
            'title'   => $title,
            'tanggal' => $tanggal,
            'orders'  => $orders,
        ];

        $this->load->view('status_board/index', $data);
    }

    /**
     * Endpoint JSON untuk auto-refresh board.
     */
    public function json()
    {
		$tanggal = $this->input->get('date', TRUE) ?: null;

        $this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        $this->output->set_header('Cache-Control: post-check=0, pre-check=0', false);
        $this->output->set_header('Pragma: no-cache');
        $this->output->set_header('Expires: 0');

		$orders = $this->board->getOrders($tanggal);

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($orders));
    }

    /**
     * Ambil HTML kartu transaksi dari ajax-operator untuk preview modal.
     */
    public function card()
    {
        $trx = $this->input->get('trx', TRUE);
        if (!$trx) {
            $this->output
                ->set_status_header(400)
                ->set_output('invalid');
            return;
        }

        $preview = $this->board->getCardPreviewByTransaction($trx);
        if (!$preview) {
            $this->output
                ->set_status_header(404)
                ->set_output('not found');
            return;
        }

        $data = [
            'order' => $preview['order'],
            'details' => $preview['details'],
        ];

        $this->load->view('status_board/card', $data, false);
    }

    /**
     * Halaman detail catatan finishing dari status board.
     */
    public function detail_catatan()
    {
        $id_detail = (int) $this->input->get('rid', TRUE);
        if ($id_detail <= 0) {
            show_404();
            return;
        }

        $this->load->model('Model_app', 'model_app');
        $row_detail = $this->model_app
            ->view_where('invoice_detail', ['id_rincianinvoice' => $id_detail])
            ->row();

        if (!$row_detail) {
            show_404();
            return;
        }

        $nama_produk = '-';
        if (!empty($row_detail->id_produk)) {
            $row_produk = $this->model_app->view_where('produk', ['id' => $row_detail->id_produk])->row();
            if ($row_produk && isset($row_produk->title) && $row_produk->title !== '') {
                $nama_produk = $row_produk->title;
            }
        }

        $app_info = function_exists('info') ? info() : ['title' => 'Putri Grafika'];
        $data = [
            'title'      => 'Isi Catatan | ' . (isset($app_info['title']) ? $app_info['title'] : 'Putri Grafika'),
            'detail'     => [
                'invoice' => isset($row_detail->id_invoice) ? $row_detail->id_invoice : 0,
                'idr'     => $id_detail,
                'kode'    => isset($row_detail->id_produk) ? $row_detail->id_produk : 0,
                'jenis'   => isset($row_detail->id_jenis) ? $row_detail->id_jenis : 0,
            ],
            'nama_produk' => $nama_produk,
            'desain'      => $this->model_app->view_where('tb_users', ['aktif' => 'Y'])->result(),
            'finishing'   => !empty($row_detail->detail) ? json_decode($row_detail->detail) : null,
        ];

        $this->load->view('status_board/detail_catatan', $data);
    }

    /**
     * Halaman manage untuk sembunyikan / tampilkan TRX Diambil & Dikirim.
     */
    public function manage()
    {
        // Pastikan hanya admin/internal
        // cek_session_login();

        $data = [
            'title'             => 'Atur Tampilan Status Board',
            'flash'             => $this->session->flashdata('msg'),
            'auto_hide_minutes' => $this->board->getAutoHideMinutes(),
            'manage_per_page'   => 10,
        ];

        $this->template->load('main/themes', 'status_board/manage', $data);
    }

    /**
     * Daftar transaksi manage per halaman untuk pagination AJAX.
     */
    public function manage_list($offset = 0)
    {
        $allowedLimits = [10, 20, 50, 100];
        $requestedLimit = (int) $this->input->post('limit', true);
        $perPage = in_array($requestedLimit, $allowedLimits, true) ? $requestedLimit : 10;

        $sort = strtoupper((string) $this->input->post('sort', true));
        if (!in_array($sort, ['ASC', 'DESC'], true)) {
            $sort = 'DESC';
        }

        $offset = max(0, (int) $offset);
        $total = $this->board->countCompletedOrders();

        if ($total > 0 && $offset >= $total) {
            $offset = (int) (floor(($total - 1) / $perPage) * $perPage);
        }

        $config = [
            'target'      => '#statusManageList',
            'base_url'    => site_url('status-board/manage/list'),
            'total_rows'  => $total,
            'per_page'    => $perPage,
            'uri_segment' => 4,
            'num_links'   => 3,
            'link_func'   => 'loadStatusManagePage',
            'show_count'  => true,
        ];
        $this->ajax_pagination->initialize($config);

        $data = [
            'orders' => $this->board->getCompletedOrders($perPage, $offset, $sort),
            'offset' => $offset,
            'total'  => $total,
        ];

        $this->load->view('status_board/manage_list', $data);
    }

    /**
     * Simpan jeda otomatis sembunyikan transaksi Diambil/Dikirim.
     */
    public function save_auto_hide()
    {
        $minutes = (int) $this->input->post('auto_hide_minutes', TRUE);
        $saved = $this->board->saveAutoHideMinutes($minutes);

        if ($saved) {
            $this->session->set_flashdata('msg', 'Jeda otomatis sembunyikan status board berhasil disimpan.');
        } else {
            $this->session->set_flashdata('msg', 'Jeda otomatis sembunyikan status board gagal disimpan.');
        }

        redirect('status-board/manage');
    }

    /**
     * Sembunyikan transaksi yang dipilih.
     */
    public function hide()
    {
        $ids = $this->input->post('selected');
        if (!empty($ids)) {
            $this->board->setHidden($ids, 1);
            $this->session->set_flashdata('msg', 'Transaksi terpilih berhasil disembunyikan dari status board.');
        }
        redirect('status-board/manage');
    }

    /**
     * Tampilkan kembali transaksi yang dipilih.
     */
    public function unhide()
    {
        $ids = $this->input->post('selected');
        if (!empty($ids)) {
            $this->board->setHidden($ids, 0);
            $this->session->set_flashdata('msg', 'Transaksi terpilih ditampilkan kembali di status board.');
        }
        redirect('status-board/manage');
    }

    /**
     * Sembunyikan semua transaksi dengan status Diambil / Dikirim.
     */
    public function hide_all()
    {
        $this->board->hideAllCompleted();
        $this->session->set_flashdata('msg', 'Semua transaksi dengan status Diambil/Dikirim telah disembunyikan.');
        redirect('status-board/manage');
    }
}
