<?php

namespace App\Http\Controllers;

use App\Models\Customers;
use App\Models\QuotationDetails;
use App\Models\QuotationInvoices;
use App\Models\Quotations;
use App\Models\QuotationSrvDetails;
use Illuminate\Http\Request;
use App\Models\StockItems;

class QuotationController extends Controller
{

	public function index()
	{
		return view('admin.quotations');
	}

	public function search_prd(Request $request)
	{
		// $tableName = 'stock_'.$this->session->branch_id;
		$return_arr = array();
		$stk_item = $request->term;
		$stk = StockItems::where('stk_barcode', 'LIKE', $stk_item . '%')->orWhere('stk_name', 'LIKE', $stk_item . '%')->get();
		if ($stk->count() > 0) {
			foreach ($stk as $rows) {
				$return_arr[] = $rows->stk_name . '+' . $rows->stk_barcode;
			}
		}
		echo json_encode($return_arr);
	}
	public function add_items_to_list(Request $request)
	{
		$prd_stk     = $request->prd_stk;
		$stk_barcode = explode('+', $prd_stk);
		$stk_barcode = end($stk_barcode);
		$q = StockItems::where('stk_barcode', $stk_barcode)->first();
		if ($q) {
			$stk_price = 'stk_sprice_b1';
			$sprice = $q->$stk_price;
			$stk_name = $q->stk_name;
			$pprice = $q->stk_pprice;
		} else {
			$sprice = 'no';
			$stk_name = 'no';
		}
		echo json_encode(array('token_value', $sprice, $stk_name, $pprice));
	}

	public function show_stock_items()
	{
		$sno = 0;
		$query = StockItems::with(['category'])->orderBy('dated', 'DESC')->get();
		if ($query->count() > 0) {
			foreach ($query as $rows) {
				$sno++;
				$category_name = $rows->category->category_name ?? 'n/a';
				$stk_price = 'stk_sprice_b1';
				$json[] = array(
					$sno,
					$category_name,
					$rows->stk_barcode,
					$rows->stk_name,
					$rows->stk_pprice,
					$rows->$stk_price,
					$rows->stk_qty,
					$rows->stk_notes,
				);
			}
			$response = array();
			$response['success'] = true;
			$response['aaData'] = $json;
			echo json_encode($response);
		} else {
			$response = array();
			$response['sEcho'] = 0;
			$response['iTotalRecords'] = 0;
			$response['iTotalDisplayRecords'] = 0;
			$response['aaData'] = [];
			echo json_encode($response);
		}
	}

	public function getCustomer(Request $request)
	{

		$customer_contact = $request->customer_contact;
		$customer_name = '';
		$customer = Customers::where('customer_contact', $customer_contact)->first();

		if ($customer) {
			$customer_name = $customer->customer_name;
			$customer_email = $customer->customer_email;
		}

		echo json_encode(['customer_name' => $customer_name, 'customer_email' => $customer_email]);
	}

	public function processItems(Request $request)
	{
		$tableName 			= 'stock_items';
		$type        		= $request->type;
		$customer_contact	= $request->customer_contact;
		$customer_name   	= $request->customer_name;
		$customer_email  	= $request->customer_email;
		$purchases    		= $request->purchases;
		$itm_subtotal 		= $request->itm_subtotal;
		$srv_subtotal 		= $request->srv_subtotal;
		$sub_total   		= $request->subtotal;
		$discount    		= $request->discount;
		$grand_total 		= $request->grandtotal;
		$item_name   		= json_decode($request->item_name);
		$item_pprice 		= json_decode($request->item_pprice);
		$item_price  		= json_decode($request->item_price);
		$item_qty    		= json_decode($request->item_qty);
		$item_total  		= json_decode($request->item_total);
		$notes 			 	= $request->notes;
		$invoice = $this->generate_qinvoice();
		$msg_itm = null;
		$msg_srv = null;
		$msg = null;
		$customer_id = 0;
		if ($customer_contact != "") {
			$customer = Customers::where('customer_contact', $customer_contact)->first();
			if ($customer) {
				$customer_id = $customer->customer_id;
			} else {
				$newCustomer = new Customers();
				$newCustomer->customer_name = $customer_name;
				$newCustomer->customer_contact = $customer_contact;
				$newCustomer->dated = now();
				$newCustomer->save();
				$customer_id = $newCustomer->customer_id;
			}
		}
		$ins_array = array(
			'branch_id' => 1,
			'invoice' => $invoice,
			'type' => $type,
			'customer_id' => $customer_id,
			'purchases' => $purchases,
			'items_subtotal' => $itm_subtotal,
			'services_subtotal' => $srv_subtotal,
			'sub_total' => $sub_total,
			'discount' => $discount,
			'grand_total' => $grand_total,
			'advance' => 0,
			'payments' => 0,
			'delivery_date' => date('Y-m-d'),
			'notes' => $notes,
			'dated' => now()
		);
		$ins_query = Quotations::create($ins_array);
		if ($ins_query) 
		{
			if ($itm_subtotal > 0) {
				for ($i = 0; $i < count($item_name); $i++) {
					$ins_array = array('branch_id' => 1, 'invoice' => $invoice, 'item_name' => $item_name[$i], 'item_pprice' => ($item_pprice[$i] * $item_qty[$i]), 'item_price' => $item_price[$i], 'item_qty' => $item_qty[$i], 'item_total' => $item_total[$i], 'dated' => now());
					$ins_query =QuotationDetails::create($ins_array);
				}
				if ($ins_query) {
					$msg_itm = 1;
				} else {
					$msg_itm = 0;
				}
			}
			
		} 
		else 
		{
			$msg = 0;
		}
		if ($msg_itm != 0) {
			$msg = 1;
			$this->updateInvoiceNumbering($invoice, 0);
		} else {
			$msg = 0;
		}
		echo json_encode(['msg'=>$msg, 'invoice'=>$invoice]);
	}
	public function invoice($invoice)
	{
		$quotation = Quotations::with(['quotationDetails','customer'])->where('invoice', $invoice)->first();
		$data ['quo'] = $quotation;
		return view('admin.quotations_invoice',$data);
	}
	private function generate_qinvoice()
	{
		$branch_id = 0;//$this->session->branch_id;
		$prefix = 'Q-';
		$last_invoice = QuotationInvoices::latest('invoice_uid')->first();
		
		if ($last_invoice) {
			$exp = explode('-',$last_invoice->invoice_number);
			$last_number = (int)end($exp);
			$new_number = $last_number + 1;
			return $prefix. str_pad($new_number, 6, '0', STR_PAD_LEFT);
		} else {
			return $prefix . str_pad(1, 6, '0', STR_PAD_LEFT);
		}
	}
	private function updateInvoiceNumbering($invoice_number, $branch_id = 0)
	{
		QuotationInvoices::create(['invoice_number' => $invoice_number,'branch_id' => $branch_id]);
	}
}
