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

class Template extends MY_Controller {

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

    public function index() {
        $uid = $this->is_admin ? NULL : $this->auth_user->id;
        $data['templates'] = $this->Template_model->get_all($uid);
        $data['title']     = 'Template Struk';
        $this->render('template/index', $data);
    }

    public function builder($id = NULL) {
        $tpl = NULL;
        if ($id) {
            $tpl = $this->Template_model->get($id);
            if (!$tpl || !$this->can_access($tpl->user_id)) show_404();
        }
        $uid = $this->is_admin ? NULL : $this->auth_user->id;
        $data['stores']      = $this->Store_model->get_all($uid);
        $data['title']       = $id ? 'Edit Template' : 'Buat Template';
        $data['template']    = $tpl;
        $data['template_id'] = (int)($id ?? 0);
        $this->render('template/builder', $data);
    }

    public function save() {
        header('Content-Type: application/json');
        $input = json_decode(file_get_contents('php://input'), TRUE);
        if (!$input || empty($input['name'])) {
            echo json_encode(['status' => 'error', 'message' => 'Data tidak valid']);
            return;
        }

        $layout   = $input['layout_json'] ?? [];
        $tpl_id   = (int)($input['template_id'] ?? 0);
        $store_id = (int)($input['store_id']    ?? 1);

        if ($tpl_id > 0) {
            $tpl = $this->Template_model->get($tpl_id);
            if (!$tpl || !$this->can_access($tpl->user_id)) {
                echo json_encode(['status' => 'error', 'message' => 'Akses ditolak']);
                return;
            }
            $this->Template_model->update($tpl_id, ['name' => $input['name'], 'paper_width' => (int)($input['paper_width'] ?? 58), 'layout_json' => $layout]);
            $id  = $tpl_id;
            $msg = 'Template berhasil diperbarui!';
        } else {
            $id = $this->Template_model->insert([
                'user_id'     => $this->auth_user->id,
                'paper_width' => (int)($input['paper_width'] ?? 58),
                'store_id'    => $store_id,
                'name'        => $input['name'],
                'layout_json' => $layout,
            ]);
            $msg = 'Template berhasil disimpan!';
        }

        $this->Template_model->sync_elements($id, $layout);
        echo json_encode(['status' => 'ok', 'message' => $msg, 'id' => $id]);
    }

    /**
     * Kembalikan field info untuk form transaksi:
     * - system_fields: placeholder seperti {{store_name}}, {{date}}
     * - input_fields : input custom dari template (input & row2 elements)
     * - elements     : layout lengkap
     * - template_type: 'flexible' (punya input/row2) atau 'classic' (placeholder saja)
     */
    public function get_fields($id) {
        header('Content-Type: application/json');
        $tpl = $this->Template_model->get($id);
        if (!$tpl) {
            echo json_encode(['status' => 'error', 'message' => 'Template tidak ditemukan']);
            return;
        }

        $input_fields = [];
        $has_flexible = FALSE;

        foreach ($tpl->layout_json as $el) {
            $type = $el['element_type'] ?? 'text';

            if ($type === 'input') {
                $has_flexible = TRUE;
                $input_fields[] = [
                    'input_name'  => $el['input_name']  ?? '',
                    'input_label' => $el['input_label'] ?? $el['input_name'] ?? '',
                    'input_type'  => $el['input_type']  ?? 'text',
                    'format'      => $el['format']      ?? 'plain',
                    'required'    => !empty($el['required']),
                    'col'         => 'full',
                ];
            } elseif ($type === 'row2') {
                $has_flexible = TRUE;
                $col1 = $el['col1'] ?? [];
                $col2 = $el['col2'] ?? [];
                if (!empty($col1['input_name'])) {
                    $input_fields[] = [
                        'input_name'  => $col1['input_name'],
                        'input_label' => $col1['input_label'] ?? $col1['input_name'],
                        'input_type'  => $col1['input_type']  ?? 'text',
                        'format'      => $col1['format']      ?? 'plain',
                        'required'    => FALSE,
                        'col'         => 'left',
                        'row_id'      => $el['id'],
                    ];
                }
                if (!empty($col2['input_name'])) {
                    $input_fields[] = [
                        'input_name'  => $col2['input_name'],
                        'input_label' => $col2['input_label'] ?? $col2['input_name'],
                        'input_type'  => $col2['input_type']  ?? 'text',
                        'format'      => $col2['format']      ?? 'plain',
                        'required'    => FALSE,
                        'col'         => 'right',
                        'row_id'      => $el['id'],
                    ];
                }
            }
        }

        // Kumpulkan semua label untuk backward compat
        $labels = array_values(array_unique(array_column($tpl->layout_json, 'label')));

        echo json_encode([
            'status'        => 'ok',
            'labels'        => $labels,
            'elements'      => $tpl->layout_json,
            'input_fields'  => $input_fields,
            'template_type' => $has_flexible ? 'flexible' : 'classic',
            'paper_width'   => (int)($tpl->paper_width ?? 58),
        ]);
    }

    public function set_default($id) {
        $tpl = $this->Template_model->get($id);
        if (!$tpl || !$this->can_access($tpl->user_id)) show_404();
        $this->Template_model->set_default($id, $tpl->user_id);
        $this->session->set_flashdata('success', 'Template default berhasil diubah.');
        redirect('template');
    }

    public function delete($id) {
        $tpl = $this->Template_model->get($id);
        if (!$tpl || !$this->can_access($tpl->user_id)) show_404();
        $this->Template_model->delete($id);
        $this->session->set_flashdata('success', 'Template berhasil dihapus.');
        redirect('template');
    }
}
