<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Mail;
use PDF;
use Auth;
use Log;
use DB;
use Input;
use App\Charge;
use App\Email;
use App\Product;
use App\User;
use App\Tax;
use App\Subscription;
use App\Invoice;
use App\Client;
use App\Transaction;

class InvoiceController extends Controller
{
    //Privileges
    // ACCESS_VIEW_INVOICE - Access to view invoices
    // ACCESS_RAISE_INVOICE - Access to view invoices
    // ACCESS_REFUND_INVOICE - Access to view invoices
    // ACCESS_COPY_INVOICE - Access to view invoices
    // ACCESS_SEARCH_INVOICE - Access to view invoices

	public function __construct()
	{
		$this->middleware('auth');
	}


	public static function view_client_invoices($id,Request $request)
	{
	    if(ConfigController::check_privilege('ACCESS_VIEW_INVOICE'))
	    {

			if($request->ajax()) 
            {
            	$invoices = Invoice::select(
            								'id',
            								'uuid',
            								'client_id',
            								'status',
											'type',
											'payment_type',
											'total_amount',
											'amount_paid',
											'payment_date',
											'due_date',
											'payee_reference',
											'filename',
											'tax',
											'tax_amount',
											'transaction_type',
											'invoice_type',
											'rollback_id',
											'tax_invoice_number',
											'note',
											'frcs_verified',
											'created_at',
											'created_by',
											'updated_by'
											)
            						->where('client_id',$id)
            						->orderBy('id','desc')
            						->get();

                $view = view('clients.invoice_data',compact('invoices','id'))->render();

                return response()->json(['html'=>$view]);
            }

	    }
	    else
	    {
	        return view('errors.not_authorized');
	    }
	}


	public function view_authenticate_pac($status,$uuid)
	{
		if(Auth::user()->pac_status == 'n')
		{

			return view('invoices.pac_auth',compact('uuid','status'));
		}
	}


	public function invoice_pdf_view($uuid)
	{
		$invoice = Invoice::where('uuid',$uuid)->first();
		$invoice_type = $invoice->invoice_type;
		$status = $invoice->status;
		$url = $invoice->url;
		$transaction_type = $invoice->transaction_type;
		$total_amount = $invoice->total_amount;
		$due_date = $invoice->due_date;

		$payment_type = $invoice->payment_type;
		$client_id = $invoice->client_id;
		$client = Client::find($client_id);
		$pos_time = $invoice->pos_time;
		$updated_at = $invoice->updated_at;
		$sdc_time = $invoice->sdc_time;
		$sdc_invoice_no = $invoice->sdc_invoice_no;
		$invoice_counter = $invoice->invoice_counter;

		if($invoice->payment_type == 'SplitPayment')
		{
			$payment_type = 'Other';
		}

		$taxs = Tax::where('invoice_id', $invoice->id)->get();
		$total_tax = Tax::where('invoice_id', $invoice->id)->sum('tax');

		$charges = Charge::where('invoice_id', $invoice->id)->get();
		$transactions = Transaction::where('invoice_id',$invoice->id)->get();
		$transaction_bal = Transaction::where('invoice_id',$invoice->id)->sum('amount');

		if($invoice->invoice_type == 'Copy')
		{
			$charges = Charge::where('invoice_id', $invoice->payee_reference)->get();
			$transactions = Transaction::where('invoice_id',$invoice->payee_reference)->get();
			$transaction_bal = Transaction::where('invoice_id',$invoice->payee_reference)->sum('amount');
		}

		if($invoice->transaction_type == 'Refund')
		{
			$array_of_ids = [$invoice->id,$invoice->payee_reference];
			$charges = Charge::where('invoice_id', $invoice->payee_reference)->get();
			$transactions = Transaction::whereIn('invoice_id',$array_of_ids)->get();
			$transaction_bal = Transaction::whereIn('invoice_id',$array_of_ids)->sum('amount');
		}

		return view('invoices.custom_pdf',compact(
		//return view('invoices.frcs_pdf',compact(
												'invoice_type',
												'status',
												'url',
												'transaction_type',
												'total_amount',
												'due_date',
												'payment_type',
												'client',
												'pos_time',
												'updated_at',
												'taxs',
												'total_tax',
												'sdc_time',
												'sdc_invoice_no',
												'invoice_counter',
												'invoice',
												'charges',
												'transaction_bal',
												'transactions'
												));
		// return view('invoices.sample');
	}

	public function pdf()
	{
		        // $pdf = PDF::loadView('invoices.pdf');  
        		// return $pdf->download('medium.pdf');

		$invoice = Invoice::where('uuid','NM-SALE-15')->first();

        

        //PDF Starts
        $invoice_type = $invoice->invoice_type;
        $status = $invoice->status;
        $url = $invoice->url;
        $transaction_type = $invoice->transaction_type;
        $total_amount = $invoice->total_amount;
        $due_date = $invoice->due_date;
        $payment_type = $invoice->payment_type;
        $status = $invoice->status;
        $client_id = $invoice->client_id;
        $client = Client::find($client_id);
        $created_at = $invoice->created_at;
        $updated_at = $invoice->updated_at;
        $sdc_time = $invoice->sdc_time;
        $pos_time = $invoice->pos_time;
        $sdc_invoice_no = $invoice->sdc_invoice_no;
        $invoice_counter = $invoice->invoice_counter;

        $total_tax = Tax::where('invoice_id', $invoice->id)->sum('tax');
        $taxs = Tax::where('invoice_id', $invoice->id)->get();
        $charges = Charge::where('invoice_id', $invoice->id)->get();
        $transactions = Transaction::where('invoice_id',$invoice->id)->get();
        $transaction_bal = Transaction::where('invoice_id',$invoice->id)->sum('amount');    


        if($invoice->invoice_type == 'Copy')
        {
            $charges = Charge::where('invoice_id', $invoice->payee_reference)->get();
            $transactions = Transaction::where('invoice_id',$invoice->payee_reference)->get();
            $transaction_bal = Transaction::where('invoice_id',$invoice->payee_reference)->sum('amount');
        }   

        if($invoice->transaction_type == 'Refund')
        {
            $array_of_ids = [$invoice->id,$invoice->payee_reference];
            $charges = Charge::where('invoice_id', $invoice->payee_reference)->get();
            $transactions = Transaction::whereIn('invoice_id',$array_of_ids)->get();
            $transaction_bal = Transaction::whereIn('invoice_id',$array_of_ids)->sum('amount');
        }

        //email body data
        $data = array(
                    'invoice_type'  => $invoice_type,
                    'status'  => $status,
                    'url'  => $url,
                    'transaction_type'  => $transaction_type,
                    'total_amount'  => $total_amount,
                    'due_date'  => $due_date,
                    'payment_type'  => $payment_type,
                    'client'  => $client,
                    'created_at'  => $created_at,
                    'updated_at'  => $updated_at,
                    'taxs'  => $taxs,
                    'total_tax'  => $total_tax,
                    'sdc_time'  => $sdc_time,
                    'pos_time'  => $pos_time,
                    'sdc_invoice_no'  => $sdc_invoice_no,
                    'invoice_counter'  => $invoice_counter,
                    'invoice'  => $invoice,
                    'charges'  => $charges,
                    'transaction_bal'  => $transaction_bal,
                    'transactions'  => $transactions,

                    );

        $pdf = PDF::loadView('pdf.custom',array('data'=>$data));
         //PDF ends
        return $pdf->stream('invoice.pdf');
	}

	public function email()
	{
		$subscriptions = Subscription::all();
		$data = ['invoice_id' => '1245',
				 'subscriptions' => $subscriptions];
		$pdf = PDF::loadView('invoices.pdf', array('data' => $data));
		
		Mail::send('emails.test', array('data'=>$data), function($message)use($pdf){
	        $message->to('djkaushiksk1@gmail.com','Kaushik Kumar')
	        		->subject('Test')
	        		->attachData($pdf->output(), "invoice.pdf")
					->from('clouddev@gmail.com','Cloud Development');
	    });

		// return view('emails.test1');

	}


	public function generate_frcs_invoice($uuid)
	{


		$invoice = Invoice::where('uuid',$uuid)->first();

		if($invoice->frcs_verified == 'x')
		{
			return view('invoices.lock');
		}
		
		if($invoice->frcs_verified == '1')
		{
			return view('invoices.frcs_exist');
		}
		
		if($invoice->frcs_verified == '0')
		{

			if(Auth::user()->pac_status == 'n')
			{
				
				return redirect('pac.auth.new.'.$uuid);
			}

			if(Auth::user()->pac_status == 'y')
			{
				//Under status payment type is determined
				switch ($invoice->status) {
					case 'u'://Unpaid
						$payment_type = 'Other';
						break;

					case 'pp'://Partial Payment
						$payment_type = 'Other';
						break;
					
					case 'p'://Paid
						//Check the payment type which is in DB 
						switch ($invoice->payment_type) {
							case 'SplitPayment':
								$payment_type = 'Other';
								break;
							
							default:
								$payment_type = $invoice->payment_type;
								break;
						}
						break;
				}

				$invoice_type = $invoice->invoice_type;
				$id = $invoice->id;

				return view('invoices.frcs_invoice',compact('id','uuid','payment_type','invoice_type'));
			}
		}
	}



	function generate_copy_frcs_invoice($uuid)
	{
		$invoice = Invoice::where('uuid',$uuid)->first();

		if(Auth::user()->pac_status == 'n')
		{
			return redirect('pac.auth.copy.'.$uuid);
		}

		if(Auth::user()->pac_status == 'y')
		{


			$copy = new Invoice;
			$copy->payee_reference = $invoice->id; 
			$copy->transaction_type = $invoice->transaction_type; 
			$copy->uuid = 'temp_'.Auth::user()->id.'_'.rand();
			$copy->created_by = Auth::user()->id;
			$copy->invoice_type = 'Copy'; 
			$copy->save();

			//get copy uuid
			$copy_uuid = ConfigController::get_uuid_invoice($invoice->transaction_type,'Copy',$copy->id);
			$copy->pos_time = date('Y-m-d H:i:s');
			$copy->uuid = $copy_uuid;
			$copy->status = $invoice->status;
			$copy->client_id = $invoice->client_id;
			$copy->frcs_verified = 0;
			$copy->payment_count = $invoice->payment_count;
			$copy->payment_type = $invoice->payment_type;
			$copy->payment_type1 = $invoice->payment_type1;
			$copy->payment_type2 = $invoice->payment_type2;
			$copy->payment_type3 = $invoice->payment_type3;
			$copy->payment_amount1 = $invoice->payment_amount1;
			$copy->payment_amount2 = $invoice->payment_amount2;
			$copy->payment_amount3 = $invoice->payment_amount3;
			$copy->amount_paid = $invoice->amount_paid;
			$copy->total_amount = $invoice->total_amount;
			$copy->send_email = 'y';
			$copy->save();


			//Under status payment type is determined
			switch ($invoice->status) {
				case 'u'://Unpaid
					$payment_type = 'Other';
					break;

				case 'pp'://Partial Payment
					$payment_type = 'Other';
					break;
				
				case 'p'://Paid
					//Check the payment type which is in DB 
					switch ($invoice->payment_type) {
						case 'SplitPayment':
							$payment_type = 'Other';
							break;
						
						default:
							$payment_type = $invoice->payment_type;
							break;
					}
					break;
			}//swicth case ends here

			$uuid = $copy_uuid;
			$invoice_type = $copy->invoice_type;
			$id = $copy->id;

			return view('invoices.frcs_invoice',compact('id','uuid','payment_type','invoice_type'));
		}//end pac status
	}



//refund frcs invoices

	function generate_refund_frcs_invoice($uuid)
	{
		$invoice = Invoice::where('uuid',$uuid)->first();

		if(Auth::user()->pac_status == 'n')
		{
			return redirect('pac.auth.refund.'.$uuid);
		}

		if(Auth::user()->pac_status == 'y')
		{


			$refund = new Invoice;
			$refund->payee_reference = $invoice->id; 
			$refund->transaction_type = 'Refund'; 
			$refund->uuid = 'temp_'.Auth::user()->id.'_'.rand();
			$refund->created_by = Auth::user()->id;
			$refund->invoice_type = $invoice->invoice_type;
			$refund->save();

			//get copy uuid
			$refund_uuid = ConfigController::get_uuid_invoice($refund->transaction_type,$refund->invoice_type,$refund->id);
			$refund->pos_time = date('Y-m-d H:i:s');
			$refund->uuid = $refund_uuid;
			$refund->status = $invoice->status;
			$refund->client_id = $invoice->client_id;
			$refund->frcs_verified = 0;
			$refund->payment_count = $invoice->payment_count;
			$refund->payment_type = $invoice->payment_type;
			$refund->payment_type1 = $invoice->payment_type1;
			$refund->payment_type2 = $invoice->payment_type2;
			$refund->payment_type3 = $invoice->payment_type3;
			$refund->payment_amount1 = $invoice->payment_amount1;
			$refund->payment_amount2 = $invoice->payment_amount2;
			$refund->payment_amount3 = $invoice->payment_amount3;
			$refund->amount_paid = $invoice->amount_paid;
			$refund->total_amount = $invoice->total_amount;
			$refund->send_email = 'y';
			$refund->save();


			//take note of the refund id in original invoice 
			$invoice->rollback_id = $refund->id;
			$invoice->save();


			//Under status payment type is determined
			switch ($invoice->status) {
				case 'u'://Unpaid
					$payment_type = 'Other';
					break;

				case 'pp'://Partial Payment
					$payment_type = 'Other';
					break;
				
				case 'p'://Paid
					//Check the payment type which is in DB 
					switch ($invoice->payment_type) {
						case 'SplitPayment':
							$payment_type = 'Other';
							break;
						
						default:
							$payment_type = $invoice->payment_type;
							break;
					}
					break;
			}//swicth case ends here

			$uuid = $refund_uuid;
			$invoice_type = $refund->invoice_type;
			$id = $refund->id;

			return view('invoices.frcs_invoice',compact('id','uuid','payment_type','invoice_type'));
		}//end pac status
	}

	public function authenticate_pac(Request $request)
	{
		$this->validate($request,['pac_code' => 'required']);

		if(Auth::user()->pac == $request->pac_code)
		{
			$user = User::find(Auth::user()->id);
			$user->pac_status = 'y';
			$user->save();

			if($request->status == 'new')
			{
				return response()->json(['url' => config('app.url').'invoice.frcs.new.'.$request->id]);
			}

			if($request->status == 'copy')
			{
				return response()->json(['url' => config('app.url').'invoice.frcs.copy.'.$request->id]);
			}

			if($request->status == 'refund')
			{
				return response()->json(['url' => config('app.url').'invoice.frcs.refund.'.$request->id]);
			}
			
		}
		else
		{
			return response()->json(['errors' => 'Invalid PAC Code. Please try again.']);
		}
	}

	public function prepare_request(Request $request)
	{
		if($request->ajax()){

			$uuid = $request->uuid;
			$invoice = Invoice::where('uuid',$uuid)->first();
			$transaction_type = $invoice->transaction_type;
			$payment_type = ConfigController::determine_payment_type($invoice->id);
			$b2b = ConfigController::get_b2b($invoice->client_id);
			$total_amount = $invoice->total_amount;

			switch ($invoice->invoice_type) {
				case 'Normal':
					
					$type = 'NORMAL';
					$invoice_id = $invoice->id;
					if($invoice->payee_reference <> '')
					{
						$reference = Invoice::find($invoice->payee_reference);
						$ref = $reference->sdc_invoice_no;
					}
					else
					{
						$ref = '';
					}
					break;

				case 'ProForma':
					$type = 'PROFORMA';
					$ref = '';
					$invoice_id = $invoice->id;
					break;
				
				case 'Copy':
					$type = 'COPY';
					//get ref number tax invoice
					$reference = Invoice::find($invoice->payee_reference);
					$invoice_id = $invoice->payee_reference;
					$ref = $reference->sdc_invoice_no;
					break;


				case 'Training':
					$type = 'TRAINING';
					$invoice_id = $invoice->id;

					if($invoice->payee_reference <> '')
					{
						$reference = Invoice::find($invoice->payee_reference);
						$ref = $reference->sdc_invoice_no;
					}
					else
					{
						$ref = '';
					}
					break;
				
			}

			if($transaction_type == 'Refund')
			{
				$reference = Invoice::find($invoice->payee_reference);
				$invoice_id = $invoice->payee_reference;
				$ref = $reference->sdc_invoice_no;
			}

			

				$view = view('invoices.js_frcs',compact('invoice_id','uuid','transaction_type','payment_type','b2b','type','ref','total_amount'))->render();
			
			return response()->json(['data' => $view]);

		}


		// $type - COPY SALE

	}


	public function change_frcs_status_to_process(Request $request)
	{
		$invoice = Invoice::find($request->id);
		$invoice->frcs_verified = 'x';
		$invoice->save();
	}


	public function close_frcs_invoice(Request $request)
	{
		$this->validate($request,[
			'uuid' => 'required',
			'tax_amount' => 'required',
			'url' => 'required',
			'tax_invoice_number' => 'required',
			'payment_type' => 'required',
		]);

		$status = false;
		try 
		{
			$invoice = Invoice::where('frcs_verified','x')->where('uuid',$request->uuid)->first();
			// $invoice->journal = $request->journal;
			// $invoice->tax_amount = $request->tax_amount;
			$invoice->url = $request->url;
			// $invoice->tax_invoice_number = $request->tax_invoice_number;
			// $invoice->payment_type = $request->payment_type; // This is already updated by system
			$invoice->sdc_time = $request->sdc_time;
			$invoice->sdc_invoice_no = $request->tax_invoice_number;
			$invoice->invoice_counter = $request->invoice_counter;
			$invoice->frcs_verified = '1';
			$invoice->created_by = Auth::user()->id;
			$invoice->pos_time = date('Y-m-d H:i:s');
			$invoice->save();

			foreach ($request->tax_amount as $taxs => $value ) 
			{
				$tax  = new Tax;
				$tax->invoice_id = $invoice->id;
				$tax->label = $value['Label'];
				$tax->name = $value['CategoryName'];
				$tax->rate = $value['Rate'];
				$tax->tax = $value['Amount'];
				$tax->save();
			}

			if($invoice->invoice_type <> 'ProForma') 
			{
				if($invoice->invoice_type <> 'Copy')
				{
					//Transaction creation
					if($invoice->transaction_type == 'Sale')
					{
						switch ($invoice->status) {
							case 'u'://unpaid
								// One transaction will be created here
								$brand_id = '1'; //raise
								
								ConfigController::create_transaction($invoice->id,'1',$invoice->total_amount,$invoice->client_id,Auth::user()->id,'Raise Invoice','','a','','',0,$invoice->invoice_type,null,null,null,null,null,null,null,null);

								break;
							
							case 'pp'://partial
								ConfigController::create_transaction($invoice->id,'1',$invoice->total_amount,$invoice->client_id,Auth::user()->id,'Raise Invoice','','a','','',0,$invoice->invoice_type,null,null,null,null,null,null,null,null);//raise invoice

								ConfigController::create_transaction($invoice->id,'2',$invoice->total_amount,$invoice->client_id,Auth::user()->id,'Partial Payment Invoice','','a','','',$invoice->amount_paid,$invoice->invoice_type,$invoice->payment_type,$invoice->payment_count,$invoice->payment_type1,$invoice->payment_type2,$invoice->payment_type3,$invoice->payment_amount1,$invoice->payment_amount2,$invoice->payment_amount3);//partial invoice

								break;				

							case 'p'://paid
								ConfigController::create_transaction($invoice->id,'1',$invoice->total_amount,$invoice->client_id,Auth::user()->id,'Raise Invoice','','a','','',0,$invoice->invoice_type,null,null,null,null,null,null,null,null);//raise invoice

								ConfigController::create_transaction($invoice->id,'3',$invoice->total_amount,$invoice->client_id,Auth::user()->id,'Full Payment Invoice','','a','','',$invoice->amount_paid,$invoice->invoice_type,$invoice->payment_type,$invoice->payment_count,$invoice->payment_type1,$invoice->payment_type2,$invoice->payment_type3,$invoice->payment_amount1,$invoice->payment_amount2,$invoice->payment_amount3);//partial invoice
								break;			
						}//switch statement ends here
					}//Sale if ends


					//REFUND
					if($invoice->transaction_type == 'Refund')
					{
						//get transactions and then call the refund functions
						$transactions = Transaction::where('invoice_id', $invoice->payee_reference)->get();

						foreach($transactions as $transaction) 
						{
							ConfigController::refund_transaction($transaction->id,$invoice->id,$transaction->brand_id,$transaction->amount,$transaction->client_id,'a',$invoice->payee_reference,$invoice->invoice_type,$transaction->payment_type,$transaction->payment_count,$transaction->payment_type1,$transaction->payment_type2,$transaction->payment_type3,$transaction->payment_amount1,$transaction->payment_amount2,$transaction->payment_amount3);
							
						}
					}
				}
			}


			// create_transaction($invoice_id,$brand_id,$total_amount,$client_id,$created_by,$note,$_transaction_id,$status,$filename,$reference_number)

			

		}
    	catch(\Exception $e)
    	{
    		Log::ERROR('=============Close FRCS Invoice ================');
    		Log::ERROR($e);
    		Log::ERROR('=============Close FRCS Invoice END ================');
    		$status = true;
    		return response()->json(['error'=>'Sorry, Something went wrong. Please contact Admin.']);
    	}

    	// Email 
		if($invoice->send_email == 'y')
		{
			EmailController::send_email($invoice->id);
		}



    	if($status == false)
    	{
    		return response()->json(['url' => config('app.url').'invoice.pdf.view.'.$invoice->uuid]);

    	}


	}

	public function create_invoice()
	{
	    if(ConfigController::check_privilege('ACCESS_RAISE_INVOICE'))
	    {
	    	$clients = Client::select('id','business_name')->get();
	    	$progress = 25;
			return view('invoices.raise', compact('clients','progress'));
	    }
	    else
	    {
	        return view('errors.not_authorized');
	    }
	}

/*
=================================================
Function Raise Invoice
This function takes in 3 params
client_id
transaction_type
invoice_type

=================================================
*/

	public function raise_invoice(Request $request)
	{

	    if(ConfigController::check_privilege('ACCESS_RAISE_INVOICE'))
	    {

			$this->validate($request,[
				'client_id' 		=> 'required',
				'transaction_type' 	=> 'required',
				'invoice_type' 		=> 'required'
			]);

			$status = false;
			$products = Product::select('id','name','amount','type')->get();
			

			try{
				if($request->ajax())
				{				
					$invoice = new Invoice;
					$invoice->uuid = 'temp_'.Auth::user()->id.'_'.rand();
					$invoice->created_by = Auth::user()->id;
					$invoice->transaction_type = $request->transaction_type;
					$invoice->invoice_type = $request->invoice_type;
					$invoice->client_id = $request->client_id;
					$invoice->frcs_verified = 0;
					$invoice->status = 'c';
					$invoice->save();
				
					$uuid = ConfigController::get_uuid_invoice($request->transaction_type,$request->invoice_type,$invoice->id);

					$invoice->uuid = $uuid;
					$invoice->pos_time = date('Y-m-d H:i:s');
					$invoice->save();
				}
				else
				{
					//Invoice 
					$invoice = Invoice::find($request->id);

					//uuid
					$uuid = $invoice->uuid;
				}


				$invoice_id = $invoice->id;
				$transaction_type = $request->transaction_type;
				$invoice_type = $request->invoice_type;
				$client_id = $request->client_id;
				$charges = Charge::select('id','product_id','description','quantity','amount')
								 ->where('invoice_id',$invoice->id)
								 ->get();
			}

	    	catch(\Exception $e)
	    	{
	    		Log::ERROR('============= Raise FRCS Invoice ================');
	    		Log::ERROR($e);
	    		Log::ERROR('============= Raise FRCS Invoice END ================');
	    		$status = true;
	    		return response()->json(['error'=>'Sorry, Something went wrong. Please contact Admin.']);
	    	}

	    	if($status == false )
	    	{	
	    		$progress = 50;

	    		if($request->ajax())
	    		{
		    		$view = view('invoices.add_items',compact(
		    													'progress',
		    													'uuid',
		    													'invoice_id',
		    													'transaction_type',
																'invoice_type',
																'client_id',
																'charges',
																'products'
															))->render();

		    		return response()->json(['html'=> $view, 'progress' => 50]);
		    	}//ajax end
		    	else
		    	{
		    		return view('invoices.add_items_view',compact(
		    													'progress',
		    													'uuid',
		    													'invoice_id',
		    													'transaction_type',
																'invoice_type',
																'client_id',
																'charges',
																'products'
															));
		    	}
	    	}

	    }
	    else
	    {
			return response()->json(['unauthorized_access'=>'Sorry, you do not have access to this service. Please contact Admin.']);
	    }
	}



    public function seachProducts(Request $request)
    {

                if ($request->ajax()) {
                    $products = Product::where('name','like','%'.$request->name.'%')->get();
                    $view = view('invoices.product_data',compact('products'))->render();

                    return response()->json(['products'=>$view]);

                }//Ajax end here
    }




        public function addProductsToCharges(Request $request)
    {
            if(ConfigController::check_privilege('ACCESS_RAISE_INVOICE'))
            {

                //Check if there is any existing products in Charge table with the same ticket number

                $checks = Charge::where('invoice_id',$request->invoice_id)
                               ->where('product_id',$request->product_id)
                               ->get();


                if(count($checks)== 1)
                {
                    foreach($checks as $check)
                    {
                        $post_charge = Charge::find($check->id);
                        $post_charge->quantity = $post_charge->quantity + 1;
                        $post_charge->save();
                    }
                }
                else
                {
                   	if($request->type == 'x')//flexible
                   	{ 
                   		$this->validate($request,[
                   			'amount'	=>		'numeric|required'
                   		]);

	                    $post_charge = new Charge;
	                    $post_charge->invoice_id = $request->invoice_id;
	                    $post_charge->product_id = $request->product_id;
	                    $post_charge->amount = $request->amount;
	                    $post_charge->description = $request->description;
	                    $post_charge->quantity = 1;
	                    $post_charge->save();
	                }

	                if($request->type == 'f')//fixed
	                {
	                	$post_charge = new Charge;
	                    $post_charge->invoice_id = $request->invoice_id;
	                    $post_charge->product_id = $request->product_id;
	                    $post_charge->amount = ConfigController::get_product_price($request->product_id);
	                    $post_charge->description = ConfigController::get_product_desc($request->product_id);
	                    $post_charge->quantity = 1;
	                    $post_charge->save();
	                }
                } 

                //collect all data in charges table
                $charges = Charge::where('invoice_id',$request->invoice_id)
                                 ->get();



                if ($request->ajax()) {
                    $view = view('invoices.charges',compact('charges'))->render();

                    return response()->json(['html'=>$view]);

                }//Ajax end here

            }
            else
            {
                return response()->json(['unauthorized_access'=>'Sorry, you do not have access to this service. Please contact Admin.']);
            }
    }


    public function removeOneProductsToCharges(Request $request)
    {
            if(ConfigController::check_privilege('ACCESS_RAISE_INVOICE'))
            {

                    $data = Charge::find($request->charge_id);

                    if($data->quantity == 1)
                    {
                        $data->delete();
                    }
                    else
                    {
                        $data->quantity = $data->quantity -1;
                        $data->save();
                    }

                $charges = Charge::where('invoice_id',$request->invoice_id)->get();
                if ($request->ajax()) {
                    $view = view('invoices.charges',compact('charges'))->render();

                    return response()->json(['html'=>$view]);

                }//Ajax end here
            }
            else
            {
                return response()->json(['unauthorized_access'=>'Sorry, you do not have access to this service. Please contact Admin.']);
            }
    }


    public function removeProductsToCharges(Request $request)
    {
        if(ConfigController::check_privilege('ACCESS_RAISE_INVOICE'))
        {

                $data = Charge::find($request->charge_id);      
                $data->delete();

            $charges = Charge::where('invoice_id',$request->invoice_id)->get();

            if ($request->ajax()) {
                $view = view('invoices.charges',compact('charges'))->render();

                return response()->json(['html'=>$view]);

            }//Ajax end here
        }
        else
        {
            return response()->json(['unauthorized_access'=>'Sorry, you do not have access to this service. Please contact Admin.']);
        }
    }


    public function checkProducts(Request $request)
    {
    	$invoice = Charge::where('product_id',$request->product_id)
    					 ->where('invoice_id',$request->invoice_id)
    					 ->get();

    	if(count($invoice) == 1)
    	{
    		return response()->json(['result' => '0']);
    	}
    	else
    	{
    		return response()->json(['result' => '1']);
    	}
    }

//Param needed
/*
===================================
Request[id,total_amount]


==================================
*/

    function add_payment_type(Request $request)
    {
    	if($request->ajax())
    	{
		    if(ConfigController::check_privilege('ACCESS_RAISE_INVOICE'))
		    {
				$charges = Charge::where('invoice_id',$request->id)->get();
				$total_amount = 0;
				$id = $request->id;
				$invoice = Invoice::find($id);
				$uuid = $invoice->uuid;

				if(count($charges) > 0)
				{
					foreach ($charges as $charge) 
					{
						$total_amount = $total_amount+($charge->amount * $charge->quantity);
					}

					$invoice->total_amount = $total_amount;
					$invoice->save();
				}




				if(count($charges) < 1)
				{
					return response()->json(['errors' => 'No items added to this invoice']);
				}
				else
				{
					$total_amount = $invoice->total_amount;
					$progress = 75;
					$view = view('invoices.payment_type',compact('id','uuid','total_amount'))->render();

					return response()->json(['html' => $view, 'progress' => $progress]);
				}



		    }
		    else
		    {
				return response()->json(['unauthorized_access'=>'Sorry, you do not have access to this service. Please contact Admin.']);
		    }
		}//ajax finish
		else
		{
			if(ConfigController::check_privilege('ACCESS_RAISE_INVOICE'))
		    {
				$charges = Charge::where('invoice_id',$request->id)->get();
				$id = $request->id;
				$invoice = Invoice::find($id);
				$uuid = $invoice->uuid;

				if(count($charges) > 1)
				{
					foreach ($charges as $charge) 
					{
						$total_amount = $total_amount+($charge->amount * $charge->quantity);
					}

					$invoice->total_amount = $total_amount;
					$invoice->save();
				}

				


				if(count($charges) < 1)
				{
					return response()->json(['errors' => 'No items added to this invoice']);
				}
				else
				{
					$total_amount = $invoice->total_amount;
					$progress = 75;
					
					return view('invoices.payment_type_view',compact('id','uuid','total_amount','progress'));
				}

		    }
		    else
		    {
				return view('errors.not_authorized');
		    }
		}
    }



    //This will update payment type and partial amount that is paid 
    function update_payment_type($uuid,Request $request)
    {
	    if(ConfigController::check_privilege('ACCESS_RAISE_INVOICE'))
	    {
	    	
			$this->validate($request,[
					'amount_paid' 	=> 'required',
					'status' 		=> 'required',
					'payment_type' 	=> 'required',
					
			]);


			if(Input::get('sendemail')=="on")
			{
				$sendemail = 'y';
			}
			else
			{
				$sendemail = 'n';
			}

			//get Invoice Type First
			$invoice = Invoice::where('uuid',$uuid)->first();

			if($invoice->invoice_type <> 'ProForma')
			{

				if($request->status == 'p') //status is paid
				{

					//If there is a split payment
					if($request->payment_type == 'SplitPayment')
					{
			            $count = $request->count;

			            $total_amount = $request->amount_paid;


			            if($count == '2')
			            {
			                //validation
			                $this->validate($request,[
			                    'payment_type1'    =>     'required',
			                    'payment_type2'    =>     'required',
			                    'payment_total1'   =>     'required',
			                    'payment_total2'   =>     'required'
			                ]);

			                $total = $request->payment_total1 + $request->payment_total2;

			                if($total_amount == $total)
			                {
			                    $invoice = Invoice::where('uuid',$uuid)->first();
			                    $invoice->payment_count = $count; 
			                    $invoice->payment_type1 = $request->payment_type1; 
			                    $invoice->payment_type2 = $request->payment_type2; 
			                    $invoice->payment_amount1 = $request->payment_total1; 
			                    $invoice->payment_amount2 = $request->payment_total2; 
			                    $invoice->status = $request->status; 
			                    $invoice->amount_paid = $request->amount_paid; 
			                    $invoice->payment_type = $request->payment_type; 
			                    $invoice->send_email = $sendemail;
			                    $invoice->save();
			                }
			                else
			                {
			                    return response()->json(['error' => 'Total Amount and amount entered does not match']);
			                }
			            }//end count 2


			            if($count == '3')
			            {
			                //validation
			                $this->validate($request,[
			                    'payment_type1'    =>     'required',
			                    'payment_type2'    =>     'required',
			                    'payment_type3'    =>     'required',
			                    'payment_total1'   =>     'required',
			                    'payment_total2'   =>     'required',
			                    'payment_total3'   =>     'required'
			                ]);

			                $total = $request->payment_total1 + $request->payment_total2 + $request->payment_total3;

			                if($total_amount == $total)
			                {
			                    //insert in DB
			                    $invoice = Invoice::where('uuid',$uuid)->first();
			                    $invoice->payment_count = $count; 
			                    $invoice->payment_type1 = $request->payment_type1; 
			                    $invoice->payment_type2 = $request->payment_type2; 
			                    $invoice->payment_type3 = $request->payment_type3; 
			                    $invoice->payment_amount1 = $request->payment_total1; 
			                    $invoice->payment_amount2 = $request->payment_total2; 
			                    $invoice->payment_amount3 = $request->payment_total3; 
			                    $invoice->status = $request->status; 
			                    $invoice->amount_paid = $request->amount_paid; 
			                    $invoice->payment_type = $request->payment_type; 
			                    $invoice->send_email = $sendemail;
			                    $invoice->save();
			                }
			                else
			                {
			                    return response()->json(['error' => 'Total Amount and amount entered does not match']);
			                }
			            }//end count 3
					}//end split payment
					else
					{
						$invoice = Invoice::where('uuid',$uuid)->first();
	                    $invoice->status = $request->status; 
	                    $invoice->amount_paid = $request->amount_paid; 
	                    $invoice->payment_type = $request->payment_type; 
	                    $invoice->send_email = $sendemail;
	                    $invoice->save();
					}
				}//end paid



				if($request->status == 'pp') //status is partial
				{

					//If there is a split payment
					if($request->payment_type == 'SplitPayment')
					{
			            $count = $request->count;

			            $total_amount = $request->amount_paid;


			            if($count == '2')
			            {
			                //validation
			                $this->validate($request,[
			                    'payment_type1'    =>     'required',
			                    'payment_type2'    =>     'required',
			                    'payment_total1'   =>     'required',
			                    'payment_total2'   =>     'required'
			                ]);

			                $total = $request->payment_total1 + $request->payment_total2;

			                if($total_amount == $total)
			                {
			                    $invoice = Invoice::where('uuid',$uuid)->first();
			                    $invoice->payment_count = $count; 
			                    $invoice->payment_type1 = $request->payment_type1; 
			                    $invoice->payment_type2 = $request->payment_type2; 
			                    $invoice->payment_amount1 = $request->payment_total1; 
			                    $invoice->payment_amount2 = $request->payment_total2; 
			                    $invoice->status = $request->status; 
			                    $invoice->amount_paid = $request->amount_paid; 
			                    $invoice->payment_type = $request->payment_type; 
			                    $invoice->send_email = $sendemail;
			                    $invoice->save();
			                }
			                else
			                {
			                    return response()->json(['error' => 'Total Amount and amount entered does not match']);
			                }
			            }//end count 2


			            if($count == '3')
			            {
			                //validation
			                $this->validate($request,[
			                    'payment_type1'    =>     'required',
			                    'payment_type2'    =>     'required',
			                    'payment_type3'    =>     'required',
			                    'payment_total1'   =>     'required',
			                    'payment_total2'   =>     'required',
			                    'payment_total3'   =>     'required'
			                ]);

			                $total = $request->payment_total1 + $request->payment_total2 + $request->payment_total3;

			                if($total_amount == $total)
			                {
			                    //insert in DB
			                    $invoice = Invoice::where('uuid',$uuid)->first();
			                    $invoice->payment_count = $count; 
			                    $invoice->payment_type1 = $request->payment_type1; 
			                    $invoice->payment_type2 = $request->payment_type2; 
			                    $invoice->payment_type3 = $request->payment_type3; 
			                    $invoice->payment_amount1 = $request->payment_total1; 
			                    $invoice->payment_amount2 = $request->payment_total2; 
			                    $invoice->payment_amount3 = $request->payment_total3; 
			                    $invoice->status = $request->status; 
			                    $invoice->amount_paid = $request->amount_paid; 
			                    $invoice->payment_type = $request->payment_type; 
			                    $invoice->send_email = $sendemail;
			                    $invoice->save();
			                }
			                else
			                {
			                    return response()->json(['error' => 'Total Amount and amount entered does not match']);
			                }
			            }//end count 3
					}//end split payment
					else
					{

						$invoice = Invoice::where('uuid',$uuid)->first();
	                    $invoice->status = $request->status; 
	                    $invoice->amount_paid = $request->amount_paid; 
	                    $invoice->payment_type = $request->payment_type; 
	                    $invoice->send_email = $sendemail;
	                    $invoice->save();
					}
				}//end partial payment



				if($request->status == 'u') //status is unpaid
				{

					//If there is a split payment
					if($request->payment_type == 'SplitPayment')
					{
			            $count = $request->count;

			            $total_amount = $request->total_amount;


			            if($count == '2')
			            {
			                //validation
			                $this->validate($request,[
			                    'payment_type1'    =>     'required',
			                    'payment_type2'    =>     'required',
			                    'payment_total1'   =>     'required',
			                    'payment_total2'   =>     'required'
			                ]);

			                $total = $request->payment_total1 + $request->payment_total2;

			                if($total_amount == $total)
			                {
			                    $invoice = Invoice::where('uuid',$uuid)->first();
			                    $invoice->payment_count = $count; 
			                    $invoice->payment_type1 = $request->payment_type1; 
			                    $invoice->payment_type2 = $request->payment_type2; 
			                    $invoice->payment_amount1 = $request->payment_total1; 
			                    $invoice->payment_amount2 = $request->payment_total2; 
			                    $invoice->status = $request->status; 
			                    $invoice->amount_paid = $request->amount_paid; 
			                    $invoice->payment_type = $request->payment_type; 
			                    $invoice->send_email = $sendemail;
			                    $invoice->save();
			                }
			                else
			                {
			                    return response()->json(['error' => 'Total Amount and amount entered does not match']);
			                }
			            }//end count 2


			            if($count == '3')
			            {
			                //validation
			                $this->validate($request,[
			                    'payment_type1'    =>     'required',
			                    'payment_type2'    =>     'required',
			                    'payment_type3'    =>     'required',
			                    'payment_total1'   =>     'required',
			                    'payment_total2'   =>     'required',
			                    'payment_total3'   =>     'required'
			                ]);

			                $total = $request->payment_total1 + $request->payment_total2 + $request->payment_total3;

			                if($total_amount == $total)
			                {
			                    //insert in DB
			                    $invoice = Invoice::where('uuid',$uuid)->first();
			                    $invoice->payment_count = $count; 
			                    $invoice->payment_type1 = $request->payment_type1; 
			                    $invoice->payment_type2 = $request->payment_type2; 
			                    $invoice->payment_type3 = $request->payment_type3; 
			                    $invoice->payment_amount1 = $request->payment_total1; 
			                    $invoice->payment_amount2 = $request->payment_total2; 
			                    $invoice->payment_amount3 = $request->payment_total3; 
			                    $invoice->status = $request->status; 
			                    $invoice->amount_paid = $request->amount_paid; 
			                    $invoice->payment_type = $request->payment_type; 
			                    $invoice->send_email = $sendemail;
			                    $invoice->save();
			                }
			                else
			                {
			                    return response()->json(['error' => 'Total Amount and amount entered does not match']);
			                }
			            }//end count 3
					}//end split payment
					else
					{
						
						$invoice = Invoice::where('uuid',$uuid)->first();
	                    $invoice->status = $request->status; 
	                    $invoice->amount_paid = $request->amount_paid; 
	                    $invoice->payment_type = $request->payment_type; 
	                    $invoice->send_email = $sendemail;
	                    $invoice->save();
					}
				}//end unpaid
			}//if not proforma

			if($invoice->invoice_type == 'ProForma')
			{
                $invoice->status = 'p'; 
                $invoice->amount_paid = 0; 
                $invoice->payment_type = 'Other'; 
                $invoice->send_email = $sendemail;
                $invoice->save();				
			}//Proforma 

			$invoice->due_date = $request->due_date;//
			$invoice->save();

			return response()->json(['url' => config('app.url').'invoice.frcs.new.'.$invoice->uuid]);
	    }
	    else
	    {
			return response()->json(['unauthorized_access'=>'Sorry, you do not have access to this service. Please contact Admin.']);
	    }
    }


    function list_invoice()
    {
	    if(ConfigController::check_privilege('ACCESS_VIEW_INVOICE'))
	    {	
			$invoices = Invoice::orderBy('id','desc')->where('invoice_type','Normal')->paginate(15);

			return view('invoices.list',compact('invoices'));
	    }
	    else if(ConfigController::check_privilege('ACCESS_INVOICE_CLIENT_VIEW'))
	    {
	    	$invoices = Invoice::where('client_id',$client_id)->where('invoice_type','Normal')->orderBy('id','desc')->get();
	    	return view('invoices.list',compact('invoices'));
	    }
	    else
	    {
	        return view('errors.not_authorized');
	    }
    }


    function invoice_view($uuid)
    {
	    if(ConfigController::check_privilege('ACCESS_VIEW_INVOICE'))//For Admin
	    {
	    	$invoice_linked = [];
			$invoice = Invoice::where('uuid',$uuid)->first();
			$transactions = Transaction::where('invoice_id',$invoice->id)->get();
			$taxs = Tax::where('invoice_id',$invoice->id)->get();
			$charges = Charge::where('invoice_id',$invoice->id)->get();
			$emails = Email::where('type_id',$invoice->id)->where('type','Invoice')->orderBy('id','desc')->get();

			if($invoice->invoice_type == 'Copy')
			{
				$charges = Charge::where('invoice_id', $invoice->payee_reference)->get();
				$transactions = Transaction::where('invoice_id',$invoice->payee_reference)->get();
			}

			if($invoice->transaction_type == 'Refund')
			{
				$array_of_ids = [$invoice->id,$invoice->payee_reference];
				$charges = Charge::where('invoice_id', $invoice->payee_reference)->get();
				$transactions = Transaction::whereIn('invoice_id',$array_of_ids)->get();
			}

			if($invoice->invoice_type == 'ProForma')
			{
				$invoice_linked = Invoice::where('payee_reference',$invoice->id)->get();
			}

	    }
	    else if(ConfigController::check_privilege('ACCESS_INVOICE_CLIENT_VIEW'))//for Client
	    {
	    	$invoice_linked = [];
	    	$invoice = Invoice::where('uuid',$uuid)->where('client_id',Auth::user()->client_id)->get();
			$transactions = Transaction::where('invoice_id',$invoice->id)->get();
			$taxs = Tax::where('invoice_id',$invoice->id)->get();
			$charges = Charge::where('invoice_id',$invoice->id)->get();
			$emails = Email::where('type_id',$invoice->id)->where('type','Invoice')->orderBy('id','desc')->get();

			if($invoice->invoice_type == 'Copy')
			{
				$charges = Charge::where('invoice_id', $invoice->payee_reference)->get();
				$transactions = Transaction::where('invoice_id',$invoice->payee_reference)->get();
			}

			if($invoice->transaction_type == 'Refund')
			{
				$array_of_ids = [$invoice->id,$invoice->payee_reference];
				$charges = Charge::where('invoice_id', $invoice->payee_reference)->get();
				$transactions = Transaction::whereIn('invoice_id',$array_of_ids)->get();
			}


			if($invoice->invoice_type == 'ProForma')
			{
				$invoice_linked = Invoice::where('payee_reference',$invoice->id)->get();
			}
	    }
	    else
	    {
	        return view('errors.not_authorized');
	    }

		return view('invoices.view',compact('invoice','transactions','taxs','charges','emails','invoice_linked'));  

    }



    function invoice_by_status($status)
    {
    	$prefix='';
    	switch ($status) {
    		case 'unpaid':
    			$prefix = 'u';
    			break;

    		case 'overdue':
    			$prefix = 'o';
    			break;   

    		case 'partial':
    			$prefix = 'pp';
    			break;    


    		case 'paid':
    			$prefix = 'p';
    			break;   
    	}

	    if(ConfigController::check_privilege('ACCESS_VIEW_INVOICE'))
	    {
	    	if($status <> 'refund')
	    	{		
				$invoices = Invoice::where('status',$prefix)
									->where('invoice_type','Normal')
									->orderBy('id','desc')
									->paginate(10);
			}
			else
			{
				$invoices = Invoice::where('invoice_type','Normal')
					->where('transaction_type','Refund')
					->orderBy('id','desc')
					->paginate(10);
			}
	    }
	    else if(ConfigController::check_privilege('ACCESS_INVOICE_CLIENT_VIEW'))//for Client
     	{
     		if($status <> 'refund')
     		{
    	    	$invoices = Invoice::where('client_id',Auth::user()->client_id)
    	    					->where('invoice_type','Normal')
    	    					->orderBy('id','desc')
    	    					->where('status',$prefix)
    	    					->paginate(10);
    	    }
			else
			{
				$invoices = Invoice::where('client_id',Auth::user()->client_id)
					->where('invoice_type','Normal')
					->where('transaction_type','Refund')
					->orderBy('id','desc')
					->paginate(10);
			}    	    
    	}
	    else
	    {
	        return view('errors.not_authorized');

	    }

	    return view('invoices.invoices_by_status',compact('status','invoices'));
    }


    public function list_training_invoices()
    {
    	$status = 'Training';

	    if(ConfigController::check_privilege('ACCESS_VIEW_INVOICE'))
	    {
			$invoices = Invoice::where('invoice_type','Training')
								->orderBy('id','desc')
								->paginate(10);
	    }
	    else if(ConfigController::check_privilege('ACCESS_INVOICE_CLIENT_VIEW'))//for Client
     	{
    	    $invoices = Invoice::where('client_id',Auth::user()->client_id)
    	    					->where('invoice_type','Training')
    	    					->orderBy('id','desc')
    	    					->paginate(10);
    	}
	    else
	    {
	        return view('errors.not_authorized');
	    }

	    return view('invoices.invoices_by_status',compact('status','invoices'));
    }


    public function list_proforma_invoices()
    {
    	$status = 'ProForma';

	    if(ConfigController::check_privilege('ACCESS_VIEW_INVOICE'))
	    {
			$invoices = Invoice::where('invoice_type',$status)
								->orderBy('id','desc')
								->paginate(10);
	    }
	    else if(ConfigController::check_privilege('ACCESS_INVOICE_CLIENT_VIEW'))//for Client
     	{
    	    $invoices = Invoice::where('client_id',Auth::user()->client_id)
    	    					->where('invoice_type',$status)
    	    					->orderBy('id','desc')
    	    					->paginate(10);
    	}
	    else
	    {
	        return view('errors.not_authorized');
	    }

	    return view('invoices.invoices_by_status',compact('status','invoices'));    	
    }


    public function list_copy_invoices()
    {
    	$status = 'Copy';

	    if(ConfigController::check_privilege('ACCESS_VIEW_INVOICE'))
	    {
			$invoices = Invoice::where('invoice_type',$status)
								->orderBy('id','desc')
								->paginate(10);

	    }
	    else if(ConfigController::check_privilege('ACCESS_INVOICE_CLIENT_VIEW'))//for Client
     	{
    	    $invoices = Invoice::where('client_id',Auth::user()->client_id)
    	    					->where('invoice_type',$status)
    	    					->orderBy('id','desc')
    	    					->paginate(10);
    	}
	    else
	    {
	        return view('errors.not_authorized');
	    }

	    return view('invoices.invoices_by_status',compact('status','invoices'));    	
    }

    public function change_duedate(Request $request,$uuid)
    {
	    if(ConfigController::check_privilege('ACCESS_VIEW_INVOICE'))
	    {

	    	$this->validate($request,[
	    		'duedate'  => 'required'
	    	]);

	    	try
	    	{
				$invoice = Invoice::where('uuid',$uuid)->first();
				$invoice->due_date = $request->duedate;
				$invoice->save();
	    	}
	    	catch(\Exception $e)
	    	{
	    		return response()->json(['error' => 'Sorry, Something went wrong. Please contact support team']);
	    	}

	    	return response()->json(['success' => 'y','due_date' => $request->duedate]);

	    }
	    else
	    {
			return response()->json(['error'=>'Sorry, you do not have access to this service. Please contact support team']);
	    }
    }

    public function unlock_invoice(Request $request)
    {
	    if(ConfigController::check_privilege('ACCESS_VIEW_INVOICE'))
	    {

	    	$this->validate($request,[
	    		'uuid'  => 'required'
	    	]);

	    	try
	    	{
				$invoice = Invoice::where('uuid',$request->uuid)->first();
				$invoice->frcs_verified = 0;
				$invoice->save();
	    	}
	    	catch(\Exception $e)
	    	{
	    		Log::ERROR($e);
	    		return response()->json(['error' => 'Sorry, Something went wrong. Please contact support team']);

	    	}

	    	return response()->json(['success' => 'Invoice Unlocked ']);

	    }
	    else
	    {
			return response()->json(['error'=>'Sorry, you do not have access to this service. Please contact support team']);
	    }    	
    }


    public function set_search_view()
    {
	    if(ConfigController::check_privilege('ACCESS_INVOICE_SEARCH'))
	    {

            $start_date = date('Y-m-d', strtotime('-2 day', strtotime(date("Y-m-d"))));
            $end_date = date('Y-m-d');

            $clients = Client::select('id','business_name')->get();

            return view('invoices.search', compact('start_date','end_date','clients'));
	    }
	    else
	    {
	        return view('errors.not_authorized');
			// return response()->json(['unauthorized_access'=>'Sorry, you do not have access to this service. Please contact Admin.']);
	    }
    }


    public function search_invoice(Request $request)
    {
	    if(ConfigController::check_privilege('ACCESS_INVOICE_SEARCH'))
	    {
			$this->validate($request,[
				'transaction_type'	=>	'required',
				'invoice_type'		=>	'required',
				'client_id'			=>	'required',
				'frcs_verified'		=>	'required',
				'start_date'		=>	'required|date',
				'end_date'			=>	'required|date|after_or_equal:start_date',
			]);


			//Start Date filter
	       $query = Invoice::where('pos_time','>=', $request->start_date.' 00:00:00');

	       //End Date Filter
	       $query->where('pos_time','<=', $request->end_date.' 23:59:59');

	       if($request->invoice_id <> '')
	       {
	       		$query->where('uuid',$request->invoice_id);
	       }

	       if($request->client_id <> 'all')
	       {
	       		$query->where('client_id',$request->client_id);
	       }

	       if($request->frcs_verified <> 'all')
	       {
	       		$query->where('frcs_verified',$request->frcs_verified);
	       }

	       $query->where('transaction_type',$request->transaction_type);
	       $query->where('invoice_type',$request->invoice_type);

	       $invoices = $query->paginate(10);

	       if($request->ajax())
	       {
	       		$data = view('invoices.search_data',compact('invoices'))->render();
	       		return response()->json(['html' => $data]);
	       }

	       
	    }
	    else
	    {
	        //return view('errors.not_authorized');
			return response()->json(['unauthorized_access'=>'Sorry, you do not have access to this service. Please contact Admin.']);
	    }
    }




    public function tally_today()
    {
	    if(ConfigController::check_privilege('ACCESS_TALLY'))
	    {
	    	$transaction_type = ['Sale','Refund'];
			$invoice_nm_sale = Invoice::where('transaction_type','Sale')
									->where('invoice_type','Normal')
									->where('frcs_verified','1')
									
									->where('pos_time','>=',date('Y-m-d').' 00:00:00')
									->where('pos_time','<=',date('Y-m-d').' 23:59:59')
									->sum('total_amount');

			$invoice_nm_refund = Invoice::where('transaction_type','Refund')
									->where('invoice_type','Normal')
									->where('frcs_verified','1')
									
									->where('pos_time','>=',date('Y-m-d').' 00:00:00')
									->where('pos_time','<=',date('Y-m-d').' 23:59:59')
									->sum('total_amount');
			$invoice_nm_total = $invoice_nm_sale - $invoice_nm_refund;
			
			$transactions_amount = DB::table('transactions AS t')
									 ->join('invoices AS i','t.invoice_id','=','i.id')
									 ->whereIn('i.transaction_type',$transaction_type)
									 ->where('i.invoice_type','Normal')
									 ->where('i.frcs_verified','1')
									 // ->whereIn('t.brand_id',[2,3])
									 ->where('t.updated_at','>=',date('Y-m-d').' 00:00:00')
									 ->where('t.updated_at','<=',date('Y-m-d').' 23:59:59')
									 ->sum('amount');


			$invoice_tr_sale = Invoice::where('transaction_type','Sale')
									->where('invoice_type','Training')
									->where('frcs_verified','1')
									->where('pos_time','>=',date('Y-m-d').' 00:00:00')
									->where('pos_time','<=',date('Y-m-d').' 23:59:59')
									->sum('total_amount');

			$invoice_tr_refund = Invoice::where('transaction_type','Refund')
									->where('invoice_type','Training')
									->where('frcs_verified','1')
									->where('pos_time','>=',date('Y-m-d').' 00:00:00')
									->where('pos_time','<=',date('Y-m-d').' 23:59:59')
									->sum('total_amount');
			$invoice_tr_total = $invoice_tr_sale - $invoice_tr_refund;


			$transactions_tr_amount = DB::table('transactions AS t')
									 ->join('invoices AS i','t.invoice_id','=','i.id')
									 ->whereIn('i.transaction_type',$transaction_type)
									 ->where('i.invoice_type','Training')
									 ->where('i.frcs_verified','1')
									 // ->whereIn('t.brand_id',[2,3])
									 ->where('t.updated_at','>=',date('Y-m-d').' 00:00:00')
									 ->where('t.updated_at','<=',date('Y-m-d').' 23:59:59')
									 ->sum('amount');

			return view('tally.today',compact('invoice_nm_total','transactions_amount','invoice_tr_total','transactions_tr_amount'));			


	    }
	    else
	    {
	        return view('errors.not_authorized');
	    }
    }


    public function custom_tally_view()
    {
        if(ConfigController::check_privilege('ACCESS_TALLY'))
        {
            $start_date = date('Y-m-d', strtotime('-2 day', strtotime(date("Y-m-d"))));
            $end_date = date('Y-m-d');

            return view('tally.search',compact('start_date','end_date'));
        }
        else
        {
            return view('errors.not_authorized');
    		//return response()->json(['unauthorized_access'=>'Sorry, you do not have access to this service. Please contact Admin.']);
        }
    }


    public function custom_tally(Request $request)
    {
    	    if(ConfigController::check_privilege('ACCESS_TALLY'))
    	    {
	 			$this->validate($request,[
					'start_date'		=>	'required|date',
					'end_date'			=>	'required|date|after_or_equal:start_date',
				]);      	

	 			$transaction_type = ['Sale','Refund'];


				$invoice_nm_sale = Invoice::where('transaction_type','Sale')
										->where('invoice_type','Normal')
										->where('frcs_verified','1')
										->where('pos_time','>=',$request->start_date.' 00:00:00')
										->where('pos_time','<=',$request->end_date.' 23:59:59')
										->sum('total_amount');

				$invoice_nm_refund = Invoice::where('transaction_type','Refund')
										->where('invoice_type','Normal')
										->where('frcs_verified','1')
										->where('pos_time','>=',$request->start_date.' 00:00:00')
										->where('pos_time','<=',$request->end_date.' 23:59:59')
										->sum('total_amount');

				$invoice_nm_total = $invoice_nm_sale - $invoice_nm_refund;

				$transactions_amount = DB::table('transactions AS t')
										 ->join('invoices AS i','t.invoice_id','=','i.id')
										 ->whereIn('i.transaction_type',$transaction_type)
										 ->where('i.invoice_type','Normal')
										 ->where('i.frcs_verified','1')
										 // ->whereIn('t.brand_id',[2,3])
										 ->where('t.updated_at','>=',$request->start_date.' 00:00:00')
										 ->where('t.updated_at','<=',$request->end_date.' 23:59:59')
										 ->sum('amount');



			


										 //Training
				$invoice_tr_sale = Invoice::where('transaction_type','Sale')
										->where('invoice_type','Training')
										->where('frcs_verified','1')
										->where('pos_time','>=',$request->start_date.' 00:00:00')
										->where('pos_time','<=',$request->end_date.' 23:59:59')
										->sum('total_amount');

				$invoice_tr_refund = Invoice::where('transaction_type','Refund')
										->where('invoice_type','Training')
										->where('frcs_verified','1')
										->where('pos_time','>=',$request->start_date.' 00:00:00')
										->where('pos_time','<=',$request->end_date.' 23:59:59')
										->sum('total_amount');

				$invoice_tr_total = $invoice_tr_sale - $invoice_tr_refund;

				$transactions_tr_amount = DB::table('transactions AS t')
										 ->join('invoices AS i','t.invoice_id','=','i.id')
										 ->whereIn('i.transaction_type',$transaction_type)
										 ->where('i.invoice_type','Training')
										 ->where('i.frcs_verified','1')
										 // ->whereIn('t.brand_id',[2,3])
										 ->where('t.updated_at','>=',$request->start_date.' 00:00:00')
										 ->where('t.updated_at','<=',$request->end_date.' 23:59:59')
										 ->sum('amount');

				$data =  view('tally.data',compact('invoice_nm_total','transactions_amount','invoice_tr_total','transactions_tr_amount'))->render();	

				if($request->ajax())
				{
					return response()->json(['html'=>$data]);
				}				
    	    }
    	    else
    	    {
    	        // return view('errors.not_authorized');
    			return response()->json(['unauthorized_access'=>'Sorry, you do not have access to this service. Please contact Admin.']);
    	    }
 	
    }


    public function raise_training_pf_invoice($pro_uuid)
    {
	    if(ConfigController::check_privilege('ACCESS_RAISE_INVOICE'))
	    {	
			$proforma = Invoice::where('uuid',$pro_uuid)->first();

			$proforma_charges = Charge::where('invoice_id',$proforma->id)->get();

			$invoice = new Invoice;
			$invoice->uuid = 'temp_'.Auth::user()->id.'_'.rand();
			$invoice->transaction_type = 'Sale';
			$invoice->invoice_type = 'Training';
			$invoice->client_id = $proforma->client_id;
			$invoice->frcs_verified = 0;
			$invoice->status = 'c';
			$invoice->payee_reference = $proforma->id;
			$invoice->save();

			$uuid = ConfigController::get_uuid_invoice('Sale','Training',$invoice->id);
			$invoice->pos_time = date('Y-m-d H:i:s');
			$invoice->uuid = $uuid;
			$invoice->save();		


			//charges
			foreach ($proforma_charges as $proforma_charge) {

					    $post_charge = new Charge;
	                    $post_charge->invoice_id = $invoice->id;
	                    $post_charge->product_id = $proforma_charge->product_id;
	                    $post_charge->amount = $proforma_charge->amount;
	                    $post_charge->description = $proforma_charge->description;
	                    $post_charge->quantity = $proforma_charge->quantity;
	                    $post_charge->save();
			}

			$invoice_id = $invoice->id;
			$transaction_type = $invoice->transaction_type;
			$invoice_type = $invoice->invoice_type;
			$client_id = $invoice->client_id;
			$progress= 50;
			$charges = Charge::where('invoice_id',$invoice->id)->get();

			$products = Product::select('id','name','amount','type')->get();

			return view('invoices.add_items_view',compact(
		    													'progress',
		    													'uuid',
		    													'invoice_id',
		    													'transaction_type',
																'invoice_type',
																'client_id',
																'charges',
																'products'
														));
	    }
	    else
	    {
	        return view('errors.not_authorized');
			// return response()->json(['unauthorized_access'=>'Sorry, you do not have access to this service. Please contact Admin.']);
	    }
    }



    public function raise_normal_pf_invoice($pro_uuid)
    {
	    if(ConfigController::check_privilege('ACCESS_RAISE_INVOICE'))
	    {	
			$proforma = Invoice::where('uuid',$pro_uuid)->first();

			$proforma_charges = Charge::where('invoice_id',$proforma->id)->get();

			$invoice = new Invoice;
			$invoice->uuid = 'temp_'.Auth::user()->id.'_'.rand();
			$invoice->transaction_type = 'Sale';
			$invoice->invoice_type = 'Normal';
			$invoice->client_id = $proforma->client_id;
			$invoice->frcs_verified = 0;
			$invoice->status = 'c';
			$invoice->payee_reference = $proforma->id;
			$invoice->save();

			$uuid = ConfigController::get_uuid_invoice('Sale','Normal',$invoice->id);
			$invoice->pos_time = date('Y-m-d H:i:s');
			$invoice->uuid = $uuid;
			$invoice->save();		


			//charges
			foreach ($proforma_charges as $proforma_charge) {

					    $post_charge = new Charge;
	                    $post_charge->invoice_id = $invoice->id;
	                    $post_charge->product_id = $proforma_charge->product_id;
	                    $post_charge->amount = $proforma_charge->amount;
	                    $post_charge->description = $proforma_charge->description;
	                    $post_charge->quantity = $proforma_charge->quantity;
	                    $post_charge->save();
			}

			$invoice_id = $invoice->id;
			$transaction_type = $invoice->transaction_type;
			$invoice_type = $invoice->invoice_type;
			$client_id = $invoice->client_id;
			$progress= 50;
			$charges = Charge::where('invoice_id',$invoice->id)->get();

			$products = Product::select('id','name','amount','type')->get();

			return view('invoices.add_items_view',compact(
		    													'progress',
		    													'uuid',
		    													'invoice_id',
		    													'transaction_type',
																'invoice_type',
																'client_id',
																'charges',
																'products'
														));
	    }
	    else
	    {
	        return view('errors.not_authorized');
			// return response()->json(['unauthorized_access'=>'Sorry, you do not have access to this service. Please contact Admin.']);
	    }
    }


    public function tax_view()
    {
	    if(ConfigController::check_privilege('ACCESS_VIEW_INVOICE'))
	    {
            $start_date = date('Y-m-d', strtotime('-2 day', strtotime(date("Y-m-d"))));
            $end_date = date('Y-m-d');

            return view('tax.search',compact('start_date','end_date'));
	    }
	    else
	    {
	        return view('errors.not_authorized');
			// return response()->json(['unauthorized_access'=>'Sorry, you do not have access to this service. Please contact Admin.']);
	    }
    }


    public function tax_calculate(Request $request)
    {
    	    if(ConfigController::check_privilege('ACCESS_TALLY'))
    	    {
	 			$this->validate($request,[
					'invoice_type'		=>	'required',
					'start_date'		=>	'required|date',
					'end_date'			=>	'required|date|after_or_equal:start_date',
				]);      	


	 			$query = DB::table('taxs AS t')
	 					->join('invoices AS i','t.invoice_id','=','i.id')
	 					->select('t.tax')
	 					->where('i.transaction_type','Sale')
	 					->where('i.rollback_id',null)
						->where('i.updated_at','>=',$request->start_date.' 00:00:00')
						->where('i.updated_at','<=',$request->end_date.' 23:59:59')
	 					->where('i.invoice_type',$request->invoice_type);
	 					
	 			$taxs = $query->sum('t.tax');
	 			$invoices = $query->sum('i.total_amount');


				$data =  view('tax.data',compact('taxs','invoices'))->render();	

				if($request->ajax())
				{
					return response()->json(['html'=>$data]);
				}				
    	    }
    	    else
    	    {
    	        // return view('errors.not_authorized');
    			return response()->json(['unauthorized_access'=>'Sorry, you do not have access to this service. Please contact Admin.']);
    	    }
 	
    }




    public function xml_upload_view()
    {
	    if(ConfigController::check_privilege('ACCESS_XML_UPLOAD'))
	    {
			return view('invoices.xml');
	    }
	    else
	    {
	        return view('errors.not_authorized');
			// return response()->json(['unauthorized_access'=>'Sorry, you do not have access to this service. Please contact Admin.']);
	    }
    }

    public function xml_upload(Request $request)
    {
        if(ConfigController::check_privilege('ACCESS_XML_UPLOAD'))
        {
                $this->validate($request,['file' => 'required']);

                $info = '';
                $success = '';
                $warning = '';

                $xmlString = Input::file('file');
                $xml = simplexml_load_file($xmlString);

                $header = false;
                $response = '';
                $invoices = '';
                foreach($xml as $invoices){
                    
                    //Find ticket number and see if it is on processing status

                    $invoices_count = Invoice::where('uuid',$invoices->PosInvoiceNumber)
                                    ->where('frcs_verified','x')
                                    ->where('invoice_type',$invoices->InvoiceType)
                                    ->where('transaction_type',$invoices->TransactionType)
                                    ->where('sdc_invoice_no',null)
                                    ->get();

                    if(count($invoices_count) == 1){

                    	//get invoice id
                    	$invoice = Invoice::where('uuid',$invoices->PosInvoiceNumber)->first();

                    	$make_date = str_replace('/', '-', $invoices->DateAndTimeOfPos);
                        $date = date_create($make_date);
                        $updated_at = date_format($date,"Y-m-d H:i:s");//2019-05-19 15:47:47

                        $TaxItems = $invoices->TaxItems;
                        $TaxItem = $TaxItems->TaxItem;
                        //tax items
                        foreach ($TaxItem as $value) 
                        {
                        	try
                        	{
	                        	$tax = new Tax;
	                        	$tax->invoice_id = $invoice->id;
	                        	$tax->label = $invoice->Label;
	                        	$tax->name = $invoice->CategoryName;
	                        	$tax->rate = $invoice->Rate;
	                        	$tax->tax = $invoice->Amount;
	                        	$tax->save();
	                        }
	                        catch(\Exception $e)
	                        {
	                        Log::Info(' ');
	                        Log::Info('----------FRCS Tax update for Invoice # '.$invoices->PosInvoiceNumber.' XML Not Updated-------------');
	                        Log::Error($e);
	                        Log::Info('----------FRCS Tax Invoice XML Not UpdateD END-------------');    	                        	
	                        }
                        }

                        try{
                            
                            $invoice->updated_by = Auth::user()->id;
                            $invoice->sdc_invoice_no = $invoices->InvoiceNumber;
                            $invoice->sdc_time = $invoices->SDCTime_ServerTimeZone;
                            $invoice->invoice_counter = $invoices->InvoiceCounter;
                            $invoice->frcs_verified = '1';
                            $invoice->payment_type = $invoices->PaymentMethod;
                            $invoice->pos_time = $updated_at;
                            $invoice->save();
                            $success.='Ticket # '.$invoices->PosInvoiceNumber.' is Closed now.<br>';
                        }
                        catch(\Exception $e)
                        {
	                        Log::Info(' ');
	                        Log::Info('----------FRCS Invoice# '.$invoices->PosInvoiceNumber.' XML Not Updated-------------');
	                        Log::Error($e);
	                        Log::Info('----------FRCS Invoice XML Not UpdateD END-------------');    
                        }

                    }
                    else
                    {
                        $info.='Ticket # '.$invoices->PosInvoiceNumber.' not on Processing Status.<br>';
                    }
                }//End Foreach for XML 

                $checks = Invoice::select('uuid')->where('frcs_verified','x')->where('sdc_invoice_no',null)->get();

                if(count($checks) > 0){
                    foreach ($checks as $check) 
                    {
                        $warning.= 'Invoice # '.$check->uuid.' are still on processing status.<br>';
                    }
                }

                $html = view('invoices.xml_data',compact('info','warning','success'))->render(); 

        return response()->json(['html' => $html]);

        }
        else
        {
            return response()->json(['unauthorized_access'=>'Sorry, you do not have access to this service. Please contact Admin.']);
        }    	
    }

}
