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

class Snippets extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Snippet_model');
        $this->load->library(['session','auth_check']);
        $this->load->helper('security');

        // Verificar sesión
        if (!$this->session->userdata('logged_in')) {
            if ($this->input->is_ajax_request()) {
                header('Content-Type: application/json; charset=utf-8');
                echo json_encode([
                    'ok'   => false,
                    'auth' => false,
                    'msg'  => 'Sesión expirada o no iniciada'
                ]);
                exit;
            } else {
                $this->auth_check->verificar();
            }
        }

        header('Content-Type: application/json; charset=utf-8');
    }

    private function userId() {
        return $this->session->userdata('user_id') ?: null;
    }

    private function csrf_data() {
        return [
            'name' => $this->security->get_csrf_token_name(),
            'hash' => $this->security->get_csrf_hash()
        ];
    }

    public function index() {
        $tipo = $this->input->get('tipo');
        $q    = $this->input->get('q', TRUE) ?: '';
        $items = $this->Snippet_model->list($tipo, $q, 50, $this->userId());
        echo json_encode([
            'ok' => true,
            'items' => $items,
            'csrf' => $this->csrf_data()
        ]);
    }

    public function create() {
        $data = [
            'user_id'   => $this->userId(),
            'tipo'      => $this->input->post('tipo', true),
            'titulo'    => trim((string)$this->input->post('titulo')),
            'contenido' => $this->input->post('contenido'),
            'pinned'    => (int)$this->input->post('pinned') ? 1 : 0,
        ];

        if (!$data['tipo'] || !$data['titulo'] || !$data['contenido']) {
            echo json_encode(['ok'=>false,'msg'=>'Campos obligatorios','csrf'=>$this->csrf_data()]);
            return;
        }

        $id = $this->Snippet_model->create($data);
        echo json_encode(['ok'=>true,'id'=>$id,'csrf'=>$this->csrf_data()]);
    }

    public function get($id) {
        $row = $this->Snippet_model->get($id);
        echo json_encode(['ok'=> (bool)$row, 'item' => $row, 'csrf'=>$this->csrf_data()]);
    }

    public function update($id) {
        $data = [];
        foreach (['titulo','contenido','tipo'] as $k) {
            $v = $this->input->post($k);
            if ($v !== null) $data[$k] = $v;
        }
        if ($this->input->post('pinned') !== null) {
            $data['pinned'] = (int)$this->input->post('pinned') ? 1 : 0;
        }
        $ok = $this->Snippet_model->update($id, $data);
        echo json_encode(['ok'=>$ok,'csrf'=>$this->csrf_data()]);
    }

    public function delete($id) {
        $ok = $this->Snippet_model->delete($id);
        echo json_encode(['ok'=>$ok,'csrf'=>$this->csrf_data()]);
    }

    public function used($id) {
        $this->Snippet_model->increment_uso($id);
        echo json_encode(['ok'=>true,'csrf'=>$this->csrf_data()]);
    }
}
