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

class Receipt extends MY_Controller {

    public function __construct() {
        parent::__construct();
        $this->require_login();
        $this->load->model(['Transaction_model', 'Template_model', 'Store_model']);
        $this->load->library('Escpos');
        $this->load->helper('form');
    }

    private function _can_access($owner_uid) {
        return $this->is_admin || ((int)$owner_uid === (int)$this->auth_user->id);
    }

    public function index() {
        $uid = $this->is_admin ? NULL : $this->auth_user->id;
        $data['transactions'] = $this->Transaction_model->get_all($uid);
        $data['title']        = 'Daftar Transaksi';
        $this->render('receipt/index', $data);
    }

    public function create() {
        $uid = $this->is_admin ? NULL : $this->auth_user->id;
        $data['stores']    = $this->Store_model->get_all($uid);
        $data['templates'] = $this->Template_model->get_all($uid);
        $data['title']     = 'Buat Transaksi';
        $data['trx']       = NULL;
        $this->render('receipt/form', $data);
    }

    public function store() {
        $custom_fields = json_decode($this->input->post('custom_fields'), TRUE) ?: [];
        $items         = json_decode($this->input->post('items'),         TRUE) ?: [];

        $id = $this->Transaction_model->insert([
            'user_id'      => $this->auth_user->id,
            'store_id'     => $this->input->post('store_id'),
            'template_id'  => $this->input->post('template_id'),
            'invoice_no'   => $this->input->post('invoice_no'),
            'items'        => $items,
            'custom_fields'=> $custom_fields,
            'subtotal'     => $this->input->post('subtotal')  ?: 0,
            'discount'     => $this->input->post('discount')  ?: 0,
            'tax'          => $this->input->post('tax')        ?: 0,
            'total'        => $this->input->post('grand_total')?: 0,
            'cashier'      => $this->input->post('cashier'),
            'trx_date'     => $this->input->post('trx_date'),
            'note'         => $this->input->post('note'),
        ]);

        $this->session->set_flashdata('success', 'Transaksi berhasil disimpan.');
        redirect('receipt/print/' . $id . '?auto=1');
    }

    public function edit($id) {
        $trx = $this->Transaction_model->get($id);
        if (!$trx || !$this->_can_access($trx->user_id)) show_404();

        $uid = $this->is_admin ? NULL : $this->auth_user->id;
        $data['stores']    = $this->Store_model->get_all($uid);
        $data['templates'] = $this->Template_model->get_all($uid);
        $data['title']     = 'Edit Transaksi #' . $trx->invoice_no;
        $data['trx']       = $trx;
        $this->render('receipt/form', $data);
    }

    public function update($id) {
        $trx = $this->Transaction_model->get($id);
        if (!$trx || !$this->_can_access($trx->user_id)) show_404();

        $custom_fields = json_decode($this->input->post('custom_fields'), TRUE) ?: [];
        $items         = json_decode($this->input->post('items'),         TRUE) ?: [];

        $this->Transaction_model->update($id, [
            'store_id'     => $this->input->post('store_id'),
            'template_id'  => $this->input->post('template_id'),
            'items'        => $items,
            'custom_fields'=> $custom_fields,
            'subtotal'     => $this->input->post('subtotal')  ?: 0,
            'discount'     => $this->input->post('discount')  ?: 0,
            'tax'          => $this->input->post('tax')        ?: 0,
            'total'        => $this->input->post('grand_total')?: 0,
            'cashier'      => $this->input->post('cashier'),
            'trx_date'     => $this->input->post('trx_date'),
            'note'         => $this->input->post('note'),
        ]);

        $this->session->set_flashdata('success', 'Transaksi berhasil diperbarui.');
        redirect('receipt/print/' . $id . '?auto=1');
    }

    public function delete($id) {
        $trx = $this->Transaction_model->get($id);
        if (!$trx || !$this->_can_access($trx->user_id)) show_404();
        $this->Transaction_model->delete($id);
        $this->session->set_flashdata('success', 'Transaksi berhasil dihapus.');
        redirect('receipt');
    }

    public function print_view($id) {
        $trx = $this->Transaction_model->get($id);
        if (!$trx || !$this->_can_access($trx->user_id)) show_404();
        $data['trx']   = $trx;
        $data['title'] = 'Cetak Struk #' . $trx->invoice_no;
        $this->render('receipt/print', $data);
    }

    // ── Bangun array $data untuk Escpos dari transaksi ────────
    private function _build_escpos_data($trx, $date_format = 'd/m/Y H:i') {
        $ts = !empty($trx->trx_date) ? strtotime($trx->trx_date) : strtotime($trx->created_at);

        // Format items lama (backward compat)
        $items_text = '';
        foreach ($trx->items as $item) {
            $name = mb_substr(trim($item['name'] ?? ''), 0, 32);
            $qty  = (int)($item['qty']   ?? 1);
            $price = (float)($item['price'] ?? 0);
            $sub  = $qty * $price;
            $l    = '  ' . $qty . 'x ' . number_format($price, 0, '.', '.');
            $r    = number_format($sub,  0, '.', '.');
            $pad  = 32 - strlen($l) - strlen($r);
            $items_text .= $name . "\n" . $l . str_repeat(' ', max(1, $pad)) . $r . "\n";
        }

        // Gabungkan system placeholders + custom fields
        $base = [
            'store_name'    => $trx->store_name    ?? '',
            'store_address' => $trx->store_address ?? '',
            'store_phone'   => $trx->store_phone   ?? '',
            'invoice_no'    => $trx->invoice_no,
            'date'          => date($date_format, $ts),
            'cashier'       => $trx->cashier,
            'items'         => $items_text,
            'subtotal'      => number_format($trx->subtotal, 0, '.', '.'),
            'discount'      => number_format($trx->discount, 0, '.', '.'),
            'tax'           => number_format($trx->tax,      0, '.', '.'),
            'total'         => number_format($trx->total,    0, '.', '.'),
            'footer'        => $trx->footer_text ?? '',
            'note'          => $trx->note        ?? '',
        ];

        // Merge custom fields (nilai mentah untuk kalkulasi multiply)
        return array_merge($base, $trx->custom_fields ?? []);
    }

    // ── API: ESC/POS base64 untuk RawBT ───────────────────────
    public function get_rawbt_data($id) {
        header('Content-Type: application/json');
        $trx = $this->Transaction_model->get($id);
        if (!$trx || !$this->_can_access($trx->user_id)) {
            echo json_encode(['status' => 'error', 'message' => 'Tidak ditemukan']);
            return;
        }
        $tpl = $this->Template_model->get($trx->template_id);
        if (!$tpl) {
            echo json_encode(['status' => 'error', 'message' => 'Template tidak ada']);
            return;
        }

        $date_format = 'd/m/Y H:i';
        foreach ($tpl->layout_json as $el) {
            if (($el['label'] ?? '') === 'date' && !empty($el['date_format'])) {
                $date_format = $el['date_format']; break;
            }
        }

        $data = $this->_build_escpos_data($trx, $date_format);
        $this->escpos->render_template($tpl->layout_json, $data);

        echo json_encode([
            'status'     => 'ok',
            'base64'     => $this->escpos->get_base64(),
            'invoice_no' => $trx->invoice_no,
        ]);
    }

    // ── API: Preview live untuk form transaksi ────────────────
    public function preview_data() {
        header('Content-Type: application/json');
        $input = json_decode(file_get_contents('php://input'), TRUE);
        if (!$input) { echo json_encode(['status' => 'error']); return; }

        $tpl   = $this->Template_model->get((int)($input['template_id'] ?? 0));
        $store = $this->Store_model->get((int)($input['store_id']       ?? 0));
        if (!$tpl || !$store) {
            echo json_encode(['status' => 'error', 'message' => 'Template/toko tidak ditemukan']);
            return;
        }

        $date_format = 'd/m/Y H:i';
        foreach ($tpl->layout_json as $el) {
            if (($el['label'] ?? '') === 'date' && !empty($el['date_format'])) {
                $date_format = $el['date_format']; break;
            }
        }
        $ts = !empty($input['trx_date']) ? strtotime($input['trx_date']) : time();

        // Format items lama
        $items_text = '';
        $subtotal   = 0;
        foreach ($input['items'] ?? [] as $item) {
            $name  = mb_substr(trim($item['name'] ?? ''), 0, 32) ?: '(item)';
            $qty   = max(1, (int)($item['qty']   ?? 1));
            $price = (float)($item['price'] ?? 0);
            $sub   = $qty * $price; $subtotal += $sub;
            $l = '  '.$qty.'x '.number_format($price,0,'.','.');
            $r = number_format($sub,0,'.','.'); $pad = 32-strlen($l)-strlen($r);
            $items_text .= $name."\n".$l.str_repeat(' ',max(1,$pad)).$r."\n";
        }

        $discount = (float)($input['discount'] ?? 0);
        $tax      = (float)($input['tax']      ?? 0);

        // custom_fields dari input
        $custom_fields = $input['custom_fields'] ?? [];

        $data = array_merge([
            'store_name'    => $store->name,
            'store_address' => $store->address ?? '',
            'store_phone'   => $store->phone   ?? '',
            'invoice_no'    => $input['invoice_no'] ?? ('INV-'.date('Ymd').'-XXXX'),
            'date'          => date($date_format, $ts),
            'cashier'       => $input['cashier'] ?? 'Admin',
            'items'         => $items_text,
            'subtotal'      => number_format($subtotal,            0,'.', '.'),
            'discount'      => number_format($discount,            0,'.', '.'),
            'tax'           => number_format($tax,                 0,'.', '.'),
            'total'         => number_format($subtotal-$discount+$tax,0,'.','.'),
            'footer'        => $store->footer_text ?? '',
            'note'          => $input['note'] ?? '',
        ], $custom_fields);

        echo json_encode([
            'status'        => 'ok',
            'elements'      => $tpl->layout_json,
            'date_format'   => $date_format,
            'data'          => $data,
            'custom_fields' => $custom_fields,
        ]);
    }
}
