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

class Template_model extends CI_Model {

    const TABLE      = 'receipt_templates';
    const TABLE_ELEM = 'template_elements';

    public function get_all($user_id = NULL) {
        if ($user_id) $this->db->where('t.user_id',(int)$user_id);
        return $this->db
            ->select('t.*, s.name as store_name, u.name as owner_name')
            ->from(self::TABLE.' t')
            ->join('stores s',  's.id = t.store_id', 'left')
            ->join('users u',   'u.id = t.user_id',  'left')
            ->order_by('t.is_default','DESC')
            ->order_by('t.id','DESC')
            ->get()->result();
    }

    public function get($id, $user_id = NULL) {
        $this->db->where('id',(int)$id);
        if ($user_id) $this->db->where('user_id',(int)$user_id);
        $row = $this->db->get(self::TABLE)->row();
        if ($row) {
            $decoded = json_decode($row->layout_json, TRUE);
            $row->layout_json = is_array($decoded) ? $decoded : [];
        }
        return $row;
    }

    public function get_default($user_id) {
        $row = $this->db
            ->where('user_id',(int)$user_id)
            ->where('is_default',1)
            ->limit(1)->get(self::TABLE)->row();
        if (!$row) {
            $row = $this->db
                ->where('user_id',(int)$user_id)
                ->order_by('id','ASC')
                ->limit(1)->get(self::TABLE)->row();
        }
        if ($row) {
            $decoded = json_decode($row->layout_json, TRUE);
            $row->layout_json = is_array($decoded) ? $decoded : [];
        }
        return $row;
    }

    public function insert($data) {
        $insert = [
            'user_id'     => (int)($data['user_id']    ?? 1),
            'store_id'    => (int)($data['store_id']   ?? 1),
            'name'        => $data['name'],
            'paper_width' => (int)($data['paper_width'] ?? 58),
            'layout_json' => is_array($data['layout_json'])
                             ? json_encode($data['layout_json'], JSON_UNESCAPED_UNICODE)
                             : $data['layout_json'],
            'is_default'  => 0,
        ];
        $this->db->insert(self::TABLE, $insert);
        return $this->db->insert_id();
    }

    public function update($id, $data) {
        $update = [];
        if (isset($data['name']))        $update['name']        = $data['name'];
        if (isset($data['paper_width'])) $update['paper_width'] = (int)$data['paper_width'];
        if (isset($data['layout_json'])) {
            $update['layout_json'] = is_array($data['layout_json'])
                ? json_encode($data['layout_json'], JSON_UNESCAPED_UNICODE)
                : $data['layout_json'];
        }
        $this->db->where('id',(int)$id)->update(self::TABLE, $update);
        return $this->db->affected_rows();
    }

    public function set_default($id, $user_id) {
        $this->db->where('user_id',(int)$user_id)->update(self::TABLE,['is_default'=>0]);
        $this->db->where('id',(int)$id)->update(self::TABLE,['is_default'=>1]);
    }

    public function delete($id) {
        $this->db->where('template_id',(int)$id)->delete(self::TABLE_ELEM);
        $this->db->where('id',(int)$id)->delete(self::TABLE);
    }

    public function sync_elements($template_id, array $elements) {
        $this->db->where('template_id',(int)$template_id)->delete(self::TABLE_ELEM);
        foreach ($elements as $i => $el) {
            $this->db->insert(self::TABLE_ELEM, [
                'template_id'  => (int)$template_id,
                'element_type' => $el['element_type'] ?? 'text',
                'label'        => $el['label']        ?? '',
                'value'        => $el['value']        ?? '',
                'x'            => (int)($el['x']        ?? 0),
                'y'            => (int)($el['y']        ?? $i),
                'font_size'    => (int)($el['font_size'] ?? 1),
                'align'        => $el['align']        ?? 'left',
                'bold'         => (int)($el['bold']     ?? 0),
                'sort_order'   => (int)($el['y']        ?? $i),
                'date_format'  => $el['date_format'] ?? '',
            ]);
        }
    }
}
