<?php
   header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Content-Security-Policy: default-src 'self';");
   require APPPATH . '/libraries/REST_Controller.php';
   use Restserver\Libraries\REST_Controller;
     
class Sale extends REST_Controller {
    
	  /**
     * Get All Data from this method.
     *
     * @return Response
    */
    public function __construct() {
       parent::__construct();
       $this->load->database();
    }
       
    /**
     * Get All Data from this method.
     *
     * @return Response
    */
	public function index_get($id = 0,$isSaleOrCash = 1,$isDelivered= 9,$date = "",$tdate="",$customer = "")
	{
	    $index = 0;
	    $dateFilter = '';
	    $dateCriteriaClause = '';
	    $paymentMethodClause = '';
	    if(empty($tdate)){
	        $tdate = $date;
	    }
	    if($isSaleOrCash == 1){
	        $dateFilter = 'SaleHeader.SaleDate';
	    }
	    else {
	        $dateFilter = 'SaleHeader.PaidDate';
	        $paymentMethodClause = ' (PaymentMethodId < 3) AND IsPaid<>0 AND ';
	    }
	    if(!empty($date)){
	        $dateCriteriaClause = " ((".$dateFilter." BETWEEN '".$date."' AND DATE_ADD('".$tdate."', INTERVAL 1 DAY)) " 
	           ."OR ('".$date."' = '')) AND  ";
	    }
	    $data = null;
	    $sql = "SELECT * FROM SaleHeader LEFT OUTER JOIN Customer ON SaleHeader.CustomerId = Customer.CustomerId " 
	           ."WHERE ".$dateCriteriaClause.$paymentMethodClause." ((Customer.CustomerName LIKE '%".rawurldecode($customer)."%') OR ('".$customer."'='')) AND ((SaleHeader.SaleHeaderId = ".$id.") OR (".$id."=0)) AND  ((SaleHeader.IsDelivered = ".$isDelivered.") OR (".$isDelivered."=9)) AND IsDeleted = 0";
        $saleHead = $this->db->query($sql)->result();
        
        foreach ($saleHead as $sHead){
            $saleDets = $this->db->query("SELECT SaleDetails.SaleDetId,SaleDetails.SaleHeaderId, SaleDetails.ItemId, Item.ItemName,SaleDetails.SaleDetQty, SaleDetails.ItemCost,SaleDetails.SalePrice ItemPrice,SaleDetails.TotalPrice 
FROM SaleDetails JOIN Item ON SaleDetails.ItemId = Item.ItemId WHERE SaleHeaderId=".$sHead->SaleHeaderId)->result();
            $data[$index] = array(
                'SaleHeaderId' => $sHead->SaleHeaderId,
                'SaleVoucherNo' => $sHead->SaleVoucherNo,
                'CustomerId' => $sHead->CustomerId,
                'CustomerName' => $sHead->CustomerName,
                'CustomerAddress' => $sHead->CustomerAddress,
                'CustomerPhone' => $sHead->CustomerPhone,
                'SaleDate' => $sHead->SaleDate,
                'SaleAmount' => $sHead->SaleAmount,
                'DeliveryFees' => $sHead->DeliveryFees,
                'SaleRemark' => $sHead->SaleRemark,
                'IsPaid'=>$sHead->IsPaid,
                'IsDelivered'=>$sHead->IsDelivered,
                'IsDeliToBus'=>$sHead->IsDeliToBus,
                'PaidDate'=>$sHead->PaidDate,
                'DeliveredDate'=>$sHead->DeliveredDate,
                'PaymentMethodId'=>$sHead->PaymentMethodId,
                'IsHappyFamily' => $sHead->IsHappyFamily,
                'SaleDetail' => $saleDets);
            $index++;
        }
     
        $this->response($data, REST_Controller::HTTP_OK);
	}
      
    /**
     * Get All Data from this method.
     *
     * @return Response
    */
    public function index_post($type)
    {
        if($type==='new'){
            $input = $this->input->post();
            $saleHeader = array(
                    'SaleHeaderId' => $input['SaleHeaderId'],
                    'SaleVoucherNo' => $input['SaleVoucherNo'],
                    'CustomerId' => $input['CustomerId'],
                    'SaleDate' => $input['SaleDate'],
                    'SaleAmount' => $input['SaleAmount'],
                    'DeliveryFees' => $input['DeliveryFees'],
                    'SaleRemark' => $input['SaleRemark'],
                    'IsHappyFamily' => intval($input['IsHappyFamily']),
                    'IsDeleted' => 0,
                    'CreatedDateTime' => date("Y-m-d H:i:s"),
                    'CreatedBy' => $input['CreatedBy'],
                    'IsPaid'=>intval($input['IsPaid']),
                    'IsDelivered'=>intval($input['IsDelivered']),
                    'IsDeliToBus'=>intval($input['IsDeliToBus']),
                    'PaidDate'=>$input['PaidDate'],
                    'DeliveredDate'=>$input['DeliveredDate'],
                    'PaymentMethodId'=>$input['PaymentMethodId']
            );
            $this->db->insert('SaleHeader',$saleHeader);
            $insert_id = $this->db->insert_id();
            
            foreach ($input['SaleDetail'] as $rowDet) {
                $saleDet = array(
                        'SaleHeaderId' => $insert_id,
                        'SaleDetId' => '0',
                        'ItemId' => $rowDet['ItemId'],
                        'SalePrice' => $rowDet['ItemPrice'],
                        'ItemCost' => $rowDet['ItemCost'],
                        'SaleDetQty' => $rowDet['SaleDetQty'],
                        'TotalPrice' => $rowDet['TotalPrice'],
                        'SaleDetRemark' => ''
                );
                
                $this->db->insert('SaleDetails',$saleDet);
            }
            $this->response(['Sale created successfully.'], REST_Controller::HTTP_OK);
        }
        else if ($type==='update'){
            $input = $this->input->post();
            $saleHeader = array(
                    'SaleHeaderId' => $input['SaleHeaderId'],
                    'SaleVoucherNo' => $input['SaleVoucherNo'],
                    'CustomerId' => $input['CustomerId'],
                    'SaleDate' => $input['SaleDate'],
                    'SaleAmount' => $input['SaleAmount'],
                    'DeliveryFees' => $input['DeliveryFees'],
                    'SaleRemark' => $input['SaleRemark'],
                    'IsHappyFamily' => intval($input['IsHappyFamily']),
                    'IsDeleted' => 0,
                    'CreatedDateTime' => date("Y-m-d H:i:s"),
                    'CreatedBy' => $input['CreatedBy'],
                    'IsPaid'=>intval($input['IsPaid']),
                    'IsDelivered'=>intval($input['IsDelivered']),
                    'IsDeliToBus'=>intval($input['IsDeliToBus']),
                    'PaidDate'=>$input['PaidDate'],
                    'DeliveredDate'=>$input['DeliveredDate'],
                    'PaymentMethodId'=>$input['PaymentMethodId']
            );
            $this->db->update('SaleHeader', $saleHeader, array('SaleHeaderId'=>$input['SaleHeaderId']));
            $this->db->delete('SaleDetails', array('SaleHeaderId'=>$input['SaleHeaderId']));
            foreach ($input['SaleDetail'] as $rowDet) {
                $saleDet = array(
                        'SaleHeaderId' => $input['SaleHeaderId'],
                        'SaleDetId' => '0',
                        'ItemId' => $rowDet['ItemId'],
                        'SalePrice' => $rowDet['ItemPrice'],
                        'ItemCost' => $rowDet['ItemCost'],
                        'SaleDetQty' => $rowDet['SaleDetQty'],
                        'TotalPrice' => $rowDet['TotalPrice'],
                        'SaleDetRemark' => ''
                );
                
                $this->db->insert('SaleDetails',$saleDet);
            }
         
            $this->response(['Sale updated successfully.'], REST_Controller::HTTP_OK);
        }else if ($type==='delete') {
            $input = $this->input->post();
            $saleHeader = array(
                    'IsDeleted' => 1,
                    'CreatedDateTime' => date("Y-m-d H:i:s")
            );
            $this->db->update('SaleHeader', $saleHeader, array('SaleHeaderId'=>$input['SaleHeaderId']));
            
            $this->response(['Sale delete successfully.'], REST_Controller::HTTP_OK);
        }
        
         
        
    } 
     
    /**
     * Get All Data from this method.
     *
     * @return Response
    */
    public function index_put($id)
    {
        $input = $this->put();
        $this->db->update('products', $input, array('id'=>$id));
     
        $this->response(['Product updated successfully.'], REST_Controller::HTTP_OK);
    }
     
    /**
     * Get All Data from this method.
     *
     * @return Response
    */
    public function index_delete($id)
    {
        $this->db->delete('products', array('id'=>$id));
       
        $this->response(['Product deleted successfully.'], REST_Controller::HTTP_OK);
    }
    	
}