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

class PurchaseController extends CI_Controller {

	public function index() {

		$this->load->model("PurchaseModel");

		$data["list"] = $this->PurchaseModel->getAllPurchase();

		$data["token_name"] = $this->security->get_csrf_token_name();

		$data["token_key"] = $this->security->get_csrf_hash();

		$data["page"] = "purchase";

		$this->load->view("patron/layout/wrapper", $data);
	}

	public function addPurchase() {

		if( $this->input->is_ajax_request() ) {

			$this->load->model("PurchaseModel");

			$check = $this->PurchaseModel->checkPurchase($this->input->post());

			if( $check->num_rows() >= 1 ) {

				$data = array ( "type" => "danger", "message" => "Product with this data alredy existed." );
			}
			else {

				$add = $this->PurchaseModel->setPurchase($this->input->post());

				if($add) {

					$id = $this->PurchaseModel->getPurchaseMaxId($this->input->post())->row()->id;

					$data = array ( "type" => "success", "message" => "Product added successfully.", "id" => $id);
				}
				else {

					$data = array ( "type" => "danger", "message" => "Somthing went wrong. Try after sometime." );
				}
			}

			$data["token_key"] = $this->security->get_csrf_hash();

			echo json_encode($data);

			exit;
		}
		else {
			redirec(base_url('out'));
		}
	}

	public function editPurchase() {

		if( $this->input->is_ajax_request() ) {

			$this->load->model("PurchaseModel");

			$check = $this->PurchaseModel->checkPurchaseForEdit($this->input->post());

			if( $check->num_rows() >= 1 ) {

				$data = array ( "type" => "danger", "message" => "Product with this data alredy existed." );
			}
			else {

				$edit = $this->PurchaseModel->editPurchase($this->input->post());

				if($edit) {

					$data = array ( "type" => "success", "message" => "Product edited successfully.");
				}
				else {

					$data = array ( "type" => "danger", "message" => "Somthing went wrong. Try after sometime." );
				}
			}

			$data["token_key"] = $this->security->get_csrf_hash();

			echo json_encode($data);

			exit;
		}
		else {
			redirec(base_url('out'));
		}
	}

	public function deletePurchase() {

		if( $this->input->is_ajax_request() ) {

			$this->load->model("PurchaseModel");

			$delete = $this->PurchaseModel->deletePurchase($this->input->get("id"));

			if($delete) {

				$data = array ( "type" => "success", "message" => "Product deleted successfully.");
			}
			else {

				$data = array ( "type" => "danger", "message" => "Somthing went wrong. Try after sometime." );
			}

			$data["token_key"] = $this->security->get_csrf_hash();

			echo json_encode($data);

			exit;
		}
		else {
			redirec(base_url('out'));
		}
	}
}