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

class Giftcards extends CI_Controller {

    public function __construct() {
        parent::__construct();
        if (!$this->Usuario->try()) {
            redirect('login');
        }

        // Load form helper library
        $this->load->helper('form');

        // Load form validation library
        $this->load->library('form_validation');

        // Load database
        $this->load->model('Giftcard_model', 'Giftcard', true);
    }

    /**
     * Muestra listado de giftcards creadas
     * En la parte superior existe un cotón para crear
     */
    public function index() {
        //Se consultan proveedores ordenados por nombre
        $data['giftcards'] = $this->Giftcard->listado();
        $data['estados_giftcards'] = [
            1 => 'Creada',
            2 => 'Enviada'
        ];

        $data['title'] = 'Giftcards';
        $data['content'] = $this->load->view('giftcards/index', $data , true);
        $this->load->view('default', $data);
    }





    /* Funciones Json */

    /*
     * Entrega información de la giftcard por id
     */
    public function info() {
        if ($this->input->post_get('id')) {
            $result['giftcard'] = $this->Giftcard->info($this->input->post_get('id'));
            if ($result['giftcard']) {
                $result['status'] = 'success';
            }
            else {
                $result['status'] = 'error';
                $result['message'] = 'Giftcard no encontrada';
            }
        }
        else {
            $result['status'] = 'error';
            $result['message'] = 'No se recibe id de giftcard';
        }

        header('Content-type: application/json');
        echo json_encode($result);
    }

    public function guardar(){
        if (!empty($this->input->post())) {
            // Validaciones se realizarán en modelo
            $data = $this->input->post();
            $result = $this->Giftcard->guardar($data);

            header('Content-type: application/json');
            echo json_encode($result);
        }
        else {
            pr('No hay datos');
        }
    }

    /**
     * Envía giftcard al destinatario
     * y actualiza registro a estado = 2 y fecha_envio = date()
     */
    public function enviar_giftcard() {
        $id = $this->input->post('id');
        if (!empty($id)) {
            $data['g'] = $this->Giftcard->info($id);

            $to = $data['g']['email_destinatario'];
            $subject = 'Has recibido una Giftcard!';

            $message = $this->load->view('giftcards/email_giftcard', $data , true);



            $this->load->model('Email_model', 'Email');
            $result = $this->Email->send_email($to, $subject, $message);

            if ($result == 1) {
                //Marcar giftcard como estado = 2
                $gc['id'] = $id;
                $gc['estado'] = 2;
                $gc['fecha_envio'] = date('Y-m-d H:i:s');

                $result = $this->Giftcard->guardar($gc);

                if ($result) {
                    $return['status'] = 'success';
                    $return['id'] = $id;
                }
                else {
                    $return['status'] = 'error';
                    $return['message'] = 'Error al modificar giftcard';
                    return $return;
                }
            }
            else {
                $return['status'] = 'error';
                $return['message'] = 'Error al enviar el Email';
                return $return;
            }
        }
        header('Content-type: application/json');
        echo json_encode($return);
    }


	/**
     * Envía giftcards de forma masiva
     * y actualiza registro a estado = 2 y fecha_envio = date()
     */
    public function enviar_navidad() {
		$id = $this->input->post('id');
		//$return = 'No hay ID';
        if (!empty($id)) {
            $data['g'] = $this->Giftcard->info($id);

            $to = $data['g']['email_destinatario'];
            $subject = 'Jo jo jo! Te han enviado una Giftcard!';

			if ($data['g']['monto'] == 20000) {
				$data['gcClass'] = 'giftcard-20';
			}
			elseif ($data['g']['monto'] == 30000) {
				$data['gcClass'] = 'giftcard-30';
			}
			elseif ($data['g']['monto'] == 50000) {
				$data['gcClass'] = 'giftcard-50';
			}
			elseif ($data['g']['monto'] == 100000) {
				$data['gcClass'] = 'giftcard-100';
			}

            $message = $this->load->view('giftcards/email_navidad_giftcard', $data , true);

            $this->load->model('Email_model', 'Email');
            $result = $this->Email->send_email($to, $subject, $message);

            if ($result == 1) {
                //Marcar giftcard como estado = 2
                $gc['id'] = $id;
                $gc['estado'] = 2;
                $gc['fecha_envio'] = date('Y-m-d H:i:s');

                $result = $this->Giftcard->guardar($gc);

                if ($result) {
                    $return['status'] = 'success';
                    $return['id'] = $id;
                }
                else {
                    $return['status'] = 'error';
                    $return['message'] = 'Error al modificar giftcard';
                    return $return;
                }
            }
            else {
                $return['status'] = 'error';
                $return['message'] = 'Error al enviar el Email';
                return $return;
            }
        }
        header('Content-type: application/json');
        echo json_encode($return);
    }


    public function test_email($id){
        $data['g'] = $this->Giftcard->info($id);
        $this->load->view('giftcards/email_giftcard', $data);
    }


    /**
     * Elimina un dinero de la lista, llevandolo a deleted 1
     */
    public function delete() {
        if ($this->input->post('id')) {
            $gc = [
                'id' => $this->input->post('id'),
                'deleted' => 1
            ];
            $result = $this->Giftcard->guardar($gc);
            return true;
            die;
        }
        return false;
    }

}
