<?php

class Cierre_config_model extends CI_Model
{
	public function get_default_tasa()
	{
		// Use last used exchange rate when available; fallback to 1
		$row = $this->db->select('cambio_tasa')->order_by('id desc')->limit(1)->get('phppos_cierres')->row();
		return $row && (float)$row->cambio_tasa > 0 ? (float)$row->cambio_tasa : 1.0;
	}
	public function get_margen_error()
	{
		$row = $this->db->get_where('phppos_cierre_config_general', array('id' => 1))->row();
		return $row ? (float)$row->margen_error_usd : 5.0;
	}

	public function set_margen_error($margen)
	{
		$margen = (float)$margen;
		$this->db->replace('phppos_cierre_config_general', array('id' => 1, 'margen_error_usd' => $margen));
	}

	public function get_all_cajas()
	{
		return $this->db->order_by('orden asc, id asc')->get('phppos_cierre_config_cajas')->result();
	}

	public function get_cajas_activo()
	{
		$this->db->where('activo', 1);
		$this->db->order_by('orden asc, id asc');
		return $this->db->get('phppos_cierre_config_cajas')->result();
	}

	public function save_cajas($cajas_post)
	{
		if (!is_array($cajas_post)) return;

		// Simple upsert: deactivate all then update those sent
		$this->db->update('phppos_cierre_config_cajas', array('activo' => 0));

		foreach ($cajas_post as $person_id => $vals)
		{
			$person_id = (int)$person_id;
			$activo = isset($vals['activo']) ? 1 : 0;
			$alias = isset($vals['alias']) ? $vals['alias'] : '';
			$orden = isset($vals['orden']) ? (int)$vals['orden'] : 0;

			// If record exists, update; else insert.
			$existing = $this->db->get_where('phppos_cierre_config_cajas', array('person_id' => $person_id))->row();
			if ($existing)
			{
				$this->db->where('person_id', $person_id);
				$this->db->update('phppos_cierre_config_cajas', array('activo' => $activo, 'alias' => $alias, 'orden' => $orden));
			}
			else
			{
				$this->db->insert('phppos_cierre_config_cajas', array('person_id' => $person_id, 'activo' => $activo, 'alias' => $alias, 'orden' => $orden));
			}
		}
	}

	public function get_all_pagos()
	{
		return $this->db->order_by('orden asc, id asc')->get('phppos_cierre_config_pago')->result();
	}

	public function get_pagos_activos()
	{
		$this->db->where('activo', 1);
		$this->db->order_by('orden asc, id asc');
		return $this->db->get('phppos_cierre_config_pago')->result();
	}

	public function save_pagos($pagos_post)
	{
		if (!is_array($pagos_post)) return;

		foreach ($pagos_post as $id => $vals)
		{
			$id = (int)$id;
			$activo = isset($vals['activo']) ? 1 : 0;
			$contar = isset($vals['contar_en_total']) ? 1 : 0;
			$orden = isset($vals['orden']) ? (int)$vals['orden'] : 0;
			$moneda = isset($vals['moneda_base']) && in_array($vals['moneda_base'], array('USD','BS')) ? $vals['moneda_base'] : 'USD';
			$this->db->where('id', $id);
			$this->db->update('phppos_cierre_config_pago', array(
				'activo' => $activo,
				'contar_en_total' => $contar,
				'orden' => $orden,
				'moneda_base' => $moneda,
			));
		}
	}
}
