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

class BotRepository_model extends CI_Model
{
    /** @var CI_DB_query_builder */
    private $db;

    public function __construct()
    {
        parent::__construct();
        $this->db = $this->load->database('default', true);
    }

    public function ensureUser($userId)
    {
        $row = $this->db->select('user_id')->from('colvot_users')->where('user_id', $userId)->get()->row_array();
        if ($row) {
            return;
        }

        $this->db->insert('colvot_users', [
            'user_id' => $userId,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
    }

    public function getState($userId)
    {
        $row = $this->db->from('colvot_state')->where('user_id', $userId)->get()->row_array();
        if (!$row) {
            return [
                'current_cycle' => 0,
                'context' => [],
            ];
        }

        $context = [];
        if (!empty($row['context_json'])) {
            $decoded = json_decode($row['context_json'], true);
            if (is_array($decoded)) {
                $context = $decoded;
            }
        }

        return [
            'current_cycle' => isset($row['current_cycle']) ? (int) $row['current_cycle'] : 0,
            'context' => $context,
        ];
    }

    public function saveState($userId, $cycle, array $context)
    {
        $data = [
            'current_cycle' => (int) $cycle,
            'context_json' => json_encode($context),
            'last_message_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ];

        $exists = $this->db->select('user_id')->from('colvot_state')->where('user_id', $userId)->get()->row_array();
        if ($exists) {
            $this->db->where('user_id', $userId)->update('colvot_state', $data);
            return;
        }

        $data['user_id'] = $userId;
        $this->db->insert('colvot_state', $data);
    }

    public function upsertMovilizadorData($userId, $nombre, $cedula)
    {
        $this->db->where('user_id', $userId)->update('colvot_users', [
            'nombre' => $nombre,
            'cedula' => $cedula,
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
    }

    public function isMovilizadorCedulaForUser($userId, $cedula)
    {
        return (int) $this->db
            ->from('colvot_users')
            ->where('user_id', $userId)
            ->where('cedula', $cedula)
            ->count_all_results() > 0;
    }

    public function existsVotante($cedula)
    {
        return (int) $this->db
            ->from('colvot_voters')
            ->where('cedula', $cedula)
            ->count_all_results() > 0;
    }

    public function movilizadorTieneVotantes($userId)
    {
        return (int) $this->db
            ->from('colvot_voters')
            ->where('movilizador_user_id', $userId)
            ->count_all_results() > 0;
    }

    public function votantePerteneceAMovilizador($userId, $cedulaVotante)
    {
        return (int) $this->db
            ->from('colvot_voters')
            ->where('movilizador_user_id', $userId)
            ->where('cedula', $cedulaVotante)
            ->count_all_results() > 0;
    }

    public function getVotanteByCedulaForUser($userId, $cedula)
    {
        return $this->db
            ->from('colvot_voters')
            ->where('movilizador_user_id', $userId)
            ->where('cedula', $cedula)
            ->get()
            ->row_array();
    }

    public function createVotante($userId, array $data)
    {
        $insert = [
            'movilizador_user_id' => $userId,
            'nombre' => $data['nombre'],
            'cedula' => $data['cedula'],
            'centro_votacion' => $data['centro_votacion'],
            'telefono' => $data['telefono'],
            'instagram' => $data['instagram'],
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ];

        return (bool) $this->db->insert('colvot_voters', $insert);
    }

    public function votanteYaVoto($voterId)
    {
        return (int) $this->db
            ->from('colvot_votes')
            ->where('voter_id', (int) $voterId)
            ->count_all_results() > 0;
    }

    public function createVote($userId, $voterId)
    {
        $insert = [
            'voter_id' => (int) $voterId,
            'movilizador_user_id' => $userId,
            'hora_voto' => date('Y-m-d H:i:s'),
            'created_at' => date('Y-m-d H:i:s'),
        ];

        return (bool) $this->db->insert('colvot_votes', $insert);
    }
}
