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

class Snippet_model extends CI_Model {

    public function list($tipo = null, $q = '', $limit = 50, $user_id = null) {
        $this->db->from('snippets');
        if ($user_id !== null) {
            $this->db->where('user_id', $user_id);
        }
        if ($tipo) {
            $this->db->where('tipo', $tipo); // 'servicio' | 'descripcion' | 'observacion'
        }
        if ($q) {
            $this->db->group_start()
                     ->like('titulo', $q)
                     ->or_like('contenido', $q)
                     ->group_end();
        }
        // Asegúrate de TENER estas columnas en la tabla
        $this->db->order_by('pinned', 'DESC');
        $this->db->order_by('updated_at', 'DESC');
        $this->db->limit((int)$limit);

        return $this->db->get()->result_array();
    }

    public function create($data) {
        $row = [
            'user_id'   => $data['user_id'] ?? null,
            'tipo'      => $data['tipo'],
            'titulo'    => $data['titulo'],
            'contenido' => $data['contenido'],
            'pinned'    => (int)($data['pinned'] ?? 0),
            'uso_count' => 0,
            'created_at'=> date('Y-m-d H:i:s'),
            'updated_at'=> date('Y-m-d H:i:s'),
        ];
        $this->db->insert('snippets', $row);
        return $this->db->insert_id();
    }

    public function get($id) {
        return $this->db->get_where('snippets', ['id' => (int)$id])->row_array();
    }

    public function update($id, $data) {
        if (empty($data)) return false;
        $allowed = ['titulo','contenido','tipo','pinned'];
        $upd = [];
        foreach ($allowed as $k) {
            if (array_key_exists($k, $data)) $upd[$k] = $data[$k];
        }
        if (!$upd) return false;
        $upd['updated_at'] = date('Y-m-d H:i:s');
        $this->db->where('id', (int)$id)->update('snippets', $upd);
        return ($this->db->affected_rows() >= 0);
    }

    public function delete($id) {
        $this->db->delete('snippets', ['id' => (int)$id]);
        return ($this->db->affected_rows() > 0);
    }

    public function increment_uso($id) {
        $this->db->set('uso_count', 'uso_count+1', false)
                 ->set('updated_at', date('Y-m-d H:i:s'))
                 ->where('id', (int)$id)
                 ->update('snippets');
        return ($this->db->affected_rows() >= 0);
    }
}
