<?php
class ModelQuotation extends Model 
{
    public function createQuotation($request, $store_id = null)
    {
        $store_id = $store_id ? $store_id : store_id();
        $user_id = user_id();
        $created_at   = date_time();
         //$reference_no = unique_transaction_ref_no();
        $reference_no = $request->post['reference_no'];
        $product_items  = $request->post['products'];
        $total_items  = count($product_items);
        $quotation_note   = $request->post['quotation-note'];
        $customer_id    = $request->post['customer_id'];
        $customer_mobile  = isset($request->post['customer-mobile']) ? $request->post['customer-mobile'] : '';
        $subtotal      = $request->post['total-amount'];
        $discount_type  = isset($request->post['discount-type']) ? $request->post['discount-type'] : 'plain';
        $discount_amount= $request->post['discount-amount'] ? $request->post['discount-amount'] : 0;
        $shipping_type  = isset($request->post['shipping-type']) ? $request->post['shipping-type'] : 'plain';
        $shipping_amount= $request->post['shipping-amount'] ? $request->post['shipping-amount'] : 0;
        $others_charge = $request->post['others-charge'] ? $request->post['others-charge'] : 0;
        $order_tax     = $request->post['order-tax'] ? $request->post['order-tax'] : 0; 
        $item_tax     = $request->post['total-tax'] ? $request->post['total-tax'] : 0;
        $payable_amount = $request->post['payable-amount'];
		$importe_pesos = $request->post['importe-pesos'];
		$metodopago= $request->post['pmethod-id'];
		
		$numero_cheque1 = $request->post['numero-cheque1'];
		$fecha_cheque1 = $request->post['fecha-cheque1'];
		$importe_cheque1 = $request->post['importe-cheque1'];
		
		$numero_cheque2 = $request->post['numero-cheque2'];
		$fecha_cheque2 = $request->post['fecha-cheque2'];
		$importe_cheque2 = $request->post['importe-cheque2'];
		
		$numero_cheque3 = $request->post['numero-cheque3'];
		$fecha_cheque3 = $request->post['fecha-cheque3'];
		$importe_cheque3 = $request->post['importe-cheque3'];
		
		$numero_cheque4 = $request->post['numero-cheque4'];
		$fecha_cheque4 = $request->post['fecha-cheque4'];
		$importe_cheque4 = $request->post['importe-cheque4'];
		
		$numero_cheque5 = $request->post['numero-cheque5'];
		$fecha_cheque5 = $request->post['fecha-cheque5'];
		$importe_cheque5 = $request->post['importe-cheque5'];
		
		$importe_deposito = $request->post['importe-deposito'];
		$numero_deposito = $request->post['numero-deposito'];
		$fecha_deposito = $request->post['fecha-deposito'];
		
		
		$importe_dolar = $request->post['importe-dolar'];
		
		$cotizacion_dolar = $request->post['importe-cotizacion'];
		
		if ($importe_cheque1 <= 0) {
		$importe_cheque1 = 0;
		}
		if ($importe_cheque2 <= 0) {
		$importe_cheque2 = 0;
		}
		if ($importe_cheque3 <= 0) {
		$importe_cheque3 = 0;
		}
		if ($importe_cheque4 <= 0) {
		$importe_cheque4 = 0;
		}
		if ($importe_cheque5 <= 0) {
		$importe_cheque5 = 0;
		}
		if ($importe_pesos <= 0) {
		$importe_pesos = 0;
		}
		if ($importe_deposito <= 0) {
		$importe_deposito = 0;
		}
		if ($importe_dolar <= 0) {
		$importe_dolar = 0;
		}
		if ($cotizacion_dolar <= 0) {
		$cotizacion_dolar = 0;
		}
		
		$pagostotales = $importe_cheque1 + $importe_cheque2 + $importe_cheque3 + $importe_cheque4 + $importe_cheque5 + $importe_pesos + $importe_deposito + ($importe_dolar * $cotizacion_dolar);
		$texto = 'Error contrapartida';
		if ($metodopago == 1 && $payable_amount > 0 ) {
	            if ($pagostotales != $payable_amount ) {
			
         
				throw new Exception(trans('ERROR, El importe del comprobante NO es igual que la contrapartida de pagos'));
            }
		}
		
        $status = $request->post['status'];
        $is_installment_order = isset($request->post['is_installment_order']) ? $request->post['is_installment_order'] : '';
        $installment_interest_percentage = 0;
        $installment_interest_amount = 0;
        if (INSTALLMENT && $is_installment_order) {
            $installment_initial_amount = $paid_amount;
            $installment_duration = $request->post['installment_duration'];
            $installment_interval_count = $request->post['installment_interval_count'];
            $installment_count = $request->post['installment_count'];
            $installment_interest_percentage = $request->post['installment_interest_percentage'];
            $installment_interest_amount = $request->post['installment_interest_amount'];
            $installmentEndDate = date('Y-m-d H:i:s', strtotime(' + '.$installment_duration.' days'));
        }

        $product_discount = $discount_amount / $total_items;
        $payment_status = 'due';

        $subtotal = 0;
        $igst = 0;
        $cgst = 0;
        $sgst = 0;

        $tgst = 0;
        $tigst = 0;
        $tcgst = 0;
        $tsgst = 0;
        $total_purchase_price = 0;

        foreach ($product_items as $product) 
        {
            $product_id         = $product['item_id'];
            $product_info       = get_the_product($product_id);
            $product_name       = $product['item_name'];
            $category_id        = $product_info['category_id'];
            $brand_id           = $product_info['brand_id'];
            $sup_id             = $product_info['sup_id'];
            $product_quantity   = $product['quantity'];
            $product_price      = $product['unit_price'];
            $taxrate            = $product['taxrate']; //$product['taxrate'];
            $tax                =  $product['tax_amount'];//aqui recibe la variable con valor del impuesto $product['tax_amount'];
            $product_total      = $product['unit_price']*$product_quantity;//aqui se quito la suma del impuesto
			$item_tax = 0; // aqui se deja en cero el sub total sin uso
            $purchase_invoice_id  = NULL;
            $item_purchase_price = 0;

            $subtotal += $product['unit_price']*$product_quantity; 
            $taxrate_id = $product_info['taxrate_id'];
            
            $quantity_exist = $product_quantity;
            $sell_quantity = $product_quantity;

            if (get_the_customer($customer_id, 'customer_state') == get_preference('business_state')) 
            {
              $cgst = $tax / 2;
              $sgst = $tax / 2;
              $tcgst += $tax / 2;
              $tsgst += $tax / 2;
            } else {
              $igst = $tax;
              $tigst += $tax;
            }
//aqui se indica la cantidad registrada de venta anticipada
            $statement = $this->db->prepare("INSERT INTO `quotation_item` (reference_no, store_id, sup_id, category_id, brand_id, item_id, item_name, item_purchase_price, item_price, item_discount, item_tax, taxrate_id, tax, gst, cgst, sgst, igst, item_quantity, cantidad_comprada, item_total, purchase_invoice_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $statement->execute(array($reference_no, $store_id, $sup_id, $category_id, $brand_id,  $product_id, $product_name, $item_purchase_price, $product_price, $product_discount, $tax, $taxrate_id, $taxrate, $taxrate, $cgst, $sgst, $igst, $product_quantity, $product_quantity, $product_total, $purchase_invoice_id));
			
			//AQUI SE ACTUALIZA EL STOCK DE VENTAS A AENTREAżGAR QQUE SE REFLEJA EN PRODUCTOS
			if ($status != 'presupuesto') {
					
			$statement = $this->db->prepare("UPDATE `product_to_store` SET `venta_anticipada` = `venta_anticipada` + {$product_quantity} WHERE `store_id` = ? AND `product_id` = ?");
          $statement->execute(array($store_id, $product_id));
		  }
        }

        $statement = $this->db->prepare("INSERT INTO `quotation_info` (reference_no, store_id, customer_id, customer_mobile, quotation_note, total_items, status, payment_status, is_installment, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $statement->execute(array($reference_no, $store_id, $customer_id, $customer_mobile, $quotation_note, $total_items, $status, $payment_status, $is_installment_order, $user_id, $created_at));

        $statement = $this->db->prepare("INSERT INTO `quotation_price` (reference_no, store_id, subtotal, discount_type, discount_amount, interest_amount, interest_percentage, item_tax, order_tax, cgst, sgst, igst, total_purchase_price, shipping_type, shipping_amount, others_charge, payable_amount) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $statement->execute(array($reference_no, $store_id, $subtotal, $discount_type, $discount_amount, $installment_interest_amount, $installment_interest_percentage, $item_tax, $order_tax, $tcgst, $tsgst, $tigst, $total_purchase_price, $shipping_type, $shipping_amount, $others_charge, $payable_amount
        ));
//agregado aqui se agrego para que impute entrada en caja modificado
            $title = 'Ingreso por venta anticipada';
            $image = 'NULL';
            
            $transaction_type = 'deposit';
			
			
			if ($status != 'presupuesto' ) {
			
			if ($importe_pesos > 0 ) {
            $statement = $this->db->prepare("INSERT INTO `bank_transaction_info` (store_id, account_id, source_id, ref_no, invoice_id, transaction_type, title, details, image, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $statement->execute(array($store_id, 1, $store_id, $reference_no, $reference_no, $transaction_type, $title, $customer_id, $image, $user_id, $created_at));
			 $info_id = db()->lastInsertId();
			
			$statement = $this->db->prepare("INSERT INTO `bank_transaction_price` (store_id, info_id, ref_no, amount) VALUES (?, ?, ?, ?)");
            $statement->execute(array($store_id, $info_id, $reference_no, $importe_pesos));
			
			
			//aqui actualiza en caja diaria saravia
			$statement = $this->db->prepare("UPDATE `bank_account_to_store` SET `deposit` = `deposit` + {$importe_pesos} WHERE `store_id` = ? AND `account_id`  = ?");
        $statement->execute(array($store_id, 1 ));
		
		 $statement = $this->db->prepare("UPDATE `bank_accounts` SET `total_deposit` = `total_deposit` + {$importe_pesos} WHERE `id` = ?");
            $statement->execute(array(1));
		}
		
		if ($numero_cheque1 > 0) {
            $statement = $this->db->prepare("INSERT INTO `bank_transaction_info` (store_id, account_id, source_id, ref_no, invoice_id, transaction_type, title, details, numero_cheque, fecha_cheque, importe_cheque, image, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $statement->execute(array($store_id, 2, $store_id, $reference_no, $reference_no, $transaction_type, $title, $customer_id, $numero_cheque1, $fecha_cheque1,$importe_cheque1, $image, $user_id, $created_at));
			 $info_id = db()->lastInsertId();
			 
						 
			
			$statement = $this->db->prepare("INSERT INTO `bank_transaction_price` (store_id, info_id, ref_no, amount) VALUES (?, ?, ?, ?)");
            $statement->execute(array($store_id, $info_id, $reference_no, $importe_cheque1));
			
			
			//aqui actualiza en caja diaria saravia
			$statement = $this->db->prepare("UPDATE `bank_account_to_store` SET `deposit` = `deposit` + {$importe_cheque1} WHERE `store_id` = ? AND `account_id`  = ?");
        $statement->execute(array($store_id, 2 ));
		
		 $statement = $this->db->prepare("UPDATE `bank_accounts` SET `total_deposit` = `total_deposit` + {$importe_cheque1} WHERE `id` = ?");
            $statement->execute(array(2));
		}
		if ($numero_cheque2 > 0) {
            $statement = $this->db->prepare("INSERT INTO `bank_transaction_info` (store_id, account_id, source_id, ref_no, invoice_id, transaction_type, title, details, numero_cheque, fecha_cheque, importe_cheque, image, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $statement->execute(array($store_id, 2, $store_id, $reference_no, $reference_no, $transaction_type, $title, $customer_id, $numero_cheque2, $fecha_cheque2,$importe_cheque2, $image, $user_id, $created_at));
			 $info_id = db()->lastInsertId();
			 
						 
			
			$statement = $this->db->prepare("INSERT INTO `bank_transaction_price` (store_id, info_id, ref_no, amount) VALUES (?, ?, ?, ?)");
            $statement->execute(array($store_id, $info_id, $reference_no, $importe_cheque2));
			
			
			//aqui actualiza en caja diaria saravia
			$statement = $this->db->prepare("UPDATE `bank_account_to_store` SET `deposit` = `deposit` + {$importe_cheque2} WHERE `store_id` = ? AND `account_id`  = ?");
        $statement->execute(array($store_id, 2 ));
		
		 $statement = $this->db->prepare("UPDATE `bank_accounts` SET `total_deposit` = `total_deposit` + {$importe_cheque2} WHERE `id` = ?");
            $statement->execute(array(2));
		}
		if ($numero_cheque3 > 0) {
            $statement = $this->db->prepare("INSERT INTO `bank_transaction_info` (store_id, account_id, source_id, ref_no, invoice_id, transaction_type, title, details, numero_cheque, fecha_cheque, importe_cheque, image, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $statement->execute(array($store_id, 2, $store_id, $reference_no, $reference_no, $transaction_type, $title, $customer_id, $numero_cheque3, $fecha_cheque3,$importe_cheque3, $image, $user_id, $created_at));
			 $info_id = db()->lastInsertId();
			 
						 
			
			$statement = $this->db->prepare("INSERT INTO `bank_transaction_price` (store_id, info_id, ref_no, amount) VALUES (?, ?, ?, ?)");
            $statement->execute(array($store_id, $info_id, $reference_no, $importe_cheque3));
			
			
			//aqui actualiza en caja diaria saravia
			$statement = $this->db->prepare("UPDATE `bank_account_to_store` SET `deposit` = `deposit` + {$importe_cheque3} WHERE `store_id` = ? AND `account_id`  = ?");
        $statement->execute(array($store_id, 2 ));
		
		 $statement = $this->db->prepare("UPDATE `bank_accounts` SET `total_deposit` = `total_deposit` + {$importe_cheque3} WHERE `id` = ?");
            $statement->execute(array(2));
		}
		if ($numero_cheque4 > 0) {
            $statement = $this->db->prepare("INSERT INTO `bank_transaction_info` (store_id, account_id, source_id, ref_no, invoice_id, transaction_type, title, details, numero_cheque, fecha_cheque, importe_cheque, image, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $statement->execute(array($store_id, 2, $store_id, $reference_no, $reference_no, $transaction_type, $title, $customer_id, $numero_cheque4, $fecha_cheque4,$importe_cheque4, $image, $user_id, $created_at));
			 $info_id = db()->lastInsertId();
			 
						 
			
			$statement = $this->db->prepare("INSERT INTO `bank_transaction_price` (store_id, info_id, ref_no, amount) VALUES (?, ?, ?, ?)");
            $statement->execute(array($store_id, $info_id, $reference_no, $importe_cheque4));
			
			
			//aqui actualiza en caja diaria saravia
			$statement = $this->db->prepare("UPDATE `bank_account_to_store` SET `deposit` = `deposit` + {$importe_cheque4} WHERE `store_id` = ? AND `account_id`  = ?");
        $statement->execute(array($store_id, 2 ));
		
		 $statement = $this->db->prepare("UPDATE `bank_accounts` SET `total_deposit` = `total_deposit` + {$importe_cheque4} WHERE `id` = ?");
            $statement->execute(array(2));
		}
		if ($numero_cheque5 > 0) {
            $statement = $this->db->prepare("INSERT INTO `bank_transaction_info` (store_id, account_id, source_id, ref_no, invoice_id, transaction_type, title, details, numero_cheque, fecha_cheque, importe_cheque, image, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $statement->execute(array($store_id, 2, $store_id, $reference_no, $reference_no, $transaction_type, $title, $customer_id, $numero_cheque5, $fecha_cheque5,$importe_cheque5, $image, $user_id, $created_at));
			 $info_id = db()->lastInsertId();
			 
						 
			
			$statement = $this->db->prepare("INSERT INTO `bank_transaction_price` (store_id, info_id, ref_no, amount) VALUES (?, ?, ?, ?)");
            $statement->execute(array($store_id, $info_id, $reference_no, $importe_cheque1));
			
			
			//aqui actualiza en caja diaria saravia
			$statement = $this->db->prepare("UPDATE `bank_account_to_store` SET `deposit` = `deposit` + {$importe_cheque5} WHERE `store_id` = ? AND `account_id`  = ?");
        $statement->execute(array($store_id, 2 ));
		
		 $statement = $this->db->prepare("UPDATE `bank_accounts` SET `total_deposit` = `total_deposit` + {$importe_cheque5} WHERE `id` = ?");
            $statement->execute(array(2));
		}
		
		if ($numero_deposito > 0) {
            $statement = $this->db->prepare("INSERT INTO `bank_transaction_info` (store_id, account_id, source_id, ref_no, invoice_id, transaction_type, title, details, numero_cheque, fecha_cheque, importe_cheque, image, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $statement->execute(array($store_id, 11, $store_id, $reference_no, $reference_no, $transaction_type, $title, $customer_id, $numero_deposito, $fecha_deposito,$importe_deposito, $image, $user_id, $created_at));
			 $info_id = db()->lastInsertId();
			 
						 
			
			$statement = $this->db->prepare("INSERT INTO `bank_transaction_price` (store_id, info_id, ref_no, amount) VALUES (?, ?, ?, ?)");
            $statement->execute(array($store_id, $info_id, $reference_no, $importe_deposito));
			
			
			
			$statement = $this->db->prepare("UPDATE `bank_account_to_store` SET `deposit` = `deposit` + {$importe_deposito} WHERE `store_id` = ? AND `account_id`  = ?");
        $statement->execute(array($store_id, 11 ));
		
		 $statement = $this->db->prepare("UPDATE `bank_accounts` SET `total_deposit` = `total_deposit` + {$importe_deposito} WHERE `id` = ?");
            $statement->execute(array(11));
		}
		
		if ($importe_dolar > 0) {
            $statement = $this->db->prepare("INSERT INTO `bank_transaction_info` (store_id, account_id, source_id, ref_no, invoice_id, transaction_type, title, details, image, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $statement->execute(array($store_id, 5, $store_id, $reference_no, $reference_no, $transaction_type, $title, $customer_id, $image, $user_id, $created_at));
			 $info_id = db()->lastInsertId();
			
			$statement = $this->db->prepare("INSERT INTO `bank_transaction_price` (store_id, info_id, ref_no, amount) VALUES (?, ?, ?, ?)");
            $statement->execute(array($store_id, $info_id, $reference_no, $importe_dolar));
			
			
			//aqui actualiza en caja diaria saravia
			$statement = $this->db->prepare("UPDATE `bank_account_to_store` SET `deposit` = `deposit` + {$importe_dolar} WHERE `store_id` = ? AND `account_id`  = ?");
        $statement->execute(array($store_id, 5 ));
		
		 $statement = $this->db->prepare("UPDATE `bank_accounts` SET `total_deposit` = `total_deposit` + {$importe_dolar} WHERE `id` = ?");
            $statement->execute(array(5));
		}
		
		}

	//aqui se inserta balance de compra anticipada
  
 // $statement = db()->prepare("INSERT INTO `customer_transactions` SET `type` = ?, `reference_no` = ?, `customer_id` = ?, `store_id` = ?, `pmethod_id` = ?, `notes` = ?, `amount` = ?, `balance` = ?, `created_by` = ?, `created_at` = ?");
//  $statement->execute(array('add_balance', $reference_no, $customer_id, $store_id, $store_id, $quotation_note, $payable_amount, $payable_amount, $user_id, date_time()));

 // $statement = db()->prepare("UPDATE `customer_to_store` SET `balance` = `balance` + {$payable_amount} WHERE `store_id` = ? AND `customer_id` = ?");
 // $statement->execute(array($store_id, $customer_id)); 
//
        return $reference_no;
    }

    public function updateQuotation($reference_no, $request, $store_id = null)
    {
        $store_id = $store_id ? $store_id : store_id();
        $user_id = user_id();
        $created_at   = date_time();

        $product_items  = $request->post['products'];
        $total_items  = count($product_items);
        $quotation_note   = $request->post['quotation-note'];
        $customer_id    = $request->post['customer_id'];
        $customer_mobile  = isset($request->post['customer-mobile']) ? $request->post['customer-mobile'] : '';
        $subtotal      = $request->post['total-amount'];
        $discount_type  = isset($request->post['discount-type']) ? $request->post['discount-type'] : 'plain';;
        $discount_amount= $request->post['discount-amount'] ? $request->post['discount-amount'] : 0;
        $shipping_type  = isset($request->post['shipping-type']) ? $request->post['shipping-type'] : 'plain';
        $shipping_amount= $request->post['shipping-amount'] ? $request->post['shipping-amount'] : 0;
        $others_charge = $request->post['others-charge'] ? $request->post['others-charge'] : 0;
        $order_tax     = $request->post['order-tax'] ? $request->post['order-tax'] : 0; 
        $item_tax     = $request->post['total-tax'] ? $request->post['total-tax'] : 0;
        $payable_amount = $request->post['payable-amount'];
		
        $status = $request->post['status'];

        $is_installment_order = isset($request->post['is_installment_order']) ? $request->post['is_installment_order'] : '';
        $installment_interest_percentage = 0;
        $installment_interest_amount = 0;
        if (INSTALLMENT && $is_installment_order) {
            $installment_initial_amount = $paid_amount;
            $installment_duration = $request->post['installment_duration'];
            $installment_interval_count = $request->post['installment_interval_count'];
            $installment_count = $request->post['installment_count'];
            $installment_interest_percentage = $request->post['installment_interest_percentage'];
            $installment_interest_amount = $request->post['installment_interest_amount'];
            $installmentEndDate = date('Y-m-d H:i:s', strtotime(' + '.$installment_duration.' days'));
        }

        $product_discount = $discount_amount / $total_items;
        $payment_status = 'due';

        $subtotal = 0;
        $igst = 0;
        $cgst = 0;
        $sgst = 0;

        $tgst = 0;
        $tigst = 0;
        $tcgst = 0;
        $tsgst = 0;
        $total_purchase_price = 0;

        $statement = $this->db->prepare("SELECT * FROM `quotation_item` WHERE `reference_no` = ? AND `store_id` = ?");
        $statement->execute(array($reference_no, $store_id));

        foreach ($product_items as $product) 
        {
            $product_id         = $product['item_id'];
            $product_info       = get_the_product($product_id);
            $product_name       = $product['item_name'];
            $category_id        = $product['category_id'];
            $brand_id           = $product_info['brand_id'];
            $sup_id             = $product_info['sup_id'];
            $product_quantity   = $product['quantity'];
            $product_price      = $product['unit_price'];
            $taxrate            = $product['taxrate'];
             $tax                = $product['tax_amount']; //aqui se cambio esta variable por una valor numerico fijo
            $product_total      = ($product['unit_price']*$product_quantity); //aqui se dejo de sumar tax
            $purchase_invoice_id  = NULL;
            $item_purchase_price = 0;

            $subtotal += $product['unit_price']*$product_quantity;
            $taxrate_id = $product_info['taxrate_id'];
            $quantity_exist = $product_quantity;
            $sell_quantity = $product_quantity;

            if (get_the_customer($customer_id, 'customer_state') == get_preference('business_state')) 
            {
              $cgst = $tax / 2;
              $sgst = $tax / 2;
              $tcgst += $tax / 2;
              $tsgst += $tax / 2;
            } else {
              $igst = $tax;
              $tigst += $tax;
            }
//$statement = $this->db->prepare("SELECT `cantidad_entregada` FROM `quotation_item` WHERE `reference_no` = ? AND `store_id` = ?");
  //      $statement->execute(array($reference_no, $store_id));
		

			
            $statement = $this->db->prepare("INSERT INTO `quotation_item` (reference_no, store_id, sup_id, category_id, brand_id, item_id, item_name, item_purchase_price, item_price, item_discount, item_tax, taxrate_id, tax, gst, cgst, sgst, igst , item_quantity, cantidad_comprada, item_total, purchase_invoice_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $statement->execute(array($reference_no, $store_id, $sup_id, $category_id, $brand_id, $product_id, $product_name, $item_purchase_price, $product_price, $product_discount, $tax, $taxrate_id, $taxrate, $taxrate, $cgst, $sgst, $igst,$product_quantity, $product_quantity, $product_total, $purchase_invoice_id));
			
			

        }

        $statement = $this->db->prepare("UPDATE `quotation_info` SET `customer_id` = ?, `customer_mobile` = ?, `quotation_note` = ?, `total_items` = ?, `status` = ?, `payment_status` = ?, `is_installment` = ? WHERE `reference_no` = ? AND `store_id` = ?");
        $statement->execute(array($customer_id, $customer_mobile, $quotation_note, $total_items, $status, $payment_status, $is_installment_order, $reference_no, $store_id));

        $statement = $this->db->prepare("UPDATE `quotation_price` SET `subtotal` = ?, `discount_type` = ?, `discount_amount` = ?, `interest_amount` = ?, `interest_percentage` = ?, `item_tax` = ?, `order_tax` = ?, `cgst` = ?, `sgst` = ?, `igst` = ?, `total_purchase_price` = ?, `shipping_type` = ?, `shipping_amount` = ?, `others_charge` = ?, `payable_amount` = ? WHERE `reference_no` = ? AND `store_id` = ?");
        $statement->execute(array($subtotal, $discount_type, $discount_amount, $installment_interest_amount, $installment_interest_percentage, $item_tax, $order_tax, $tcgst, $tsgst, $tigst, $total_purchase_price, $shipping_type, $shipping_amount, $others_charge, $payable_amount, $reference_no, $store_id));

        return $reference_no;
    }

    public function getQuotations($store_id = null, $limit = 100000, $customer_id = null) 
    {
        $store_id = $store_id ? $store_id : store_id();
        $where_query = "`quotation_info`.`store_id` = {$store_id}";
        if ($customer_id) {
            $where_query .= " AND `quotation_info`.`customer_id` = {$customer_id}";
        }
        $statement = $this->db->prepare("SELECT `quotation_info`.*, `quotation_price`.*, `customers`.`customer_id`, `customers`.`customer_name`, `customers`.`customer_mobile`, `customers`.`customer_email` FROM `quotation_info` 
            LEFT JOIN `quotation_price` ON `quotation_info`.`reference_no` = `quotation_price`.`reference_no` 
            LEFT JOIN `customers` ON `quotation_info`.`customer_id` = `customers`.`customer_id` 
            WHERE {$where_query} ORDER BY `quotation_info`.`created_at` DESC LIMIT $limit");
        $statement->execute(array());
        return $statement->fetchAll(PDO::FETCH_ASSOC);
    }

    public function getQuotationInfo($reference_no, $store_id = null) 
    {
        $store_id = $store_id ? $store_id : store_id();
        $statement = $this->db->prepare("SELECT `quotation_info`.*, `quotation_price`.*, `customers`.`customer_id`, `customers`.`customer_name`, `customers`.`customer_mobile` AS `mobile_number`, `customers`.`customer_email` FROM `quotation_info` 
            LEFT JOIN `quotation_price` ON `quotation_info`.`reference_no` = `quotation_price`.`reference_no` 
            LEFT JOIN `customers` ON `quotation_info`.`customer_id` = `customers`.`customer_id` 
            WHERE `quotation_info`.`store_id` = ? AND (`quotation_info`.`reference_no` = ? OR `quotation_info`.`customer_id` = ?) ORDER BY `quotation_info`.`reference_no` DESC");
        $statement->execute(array($store_id, $reference_no, $reference_no));
        $quotation = $statement->fetch(PDO::FETCH_ASSOC);
        if ($quotation) {
            $quotation['by'] = get_the_user($quotation['created_by'], 'username');
            $quotation['date'] = date('Y-m-d', strtotime($quotation['created_at']));
        }
        return $quotation;
    }

    public function getQuotationItems($reference_no, $store_id = null) 
    {
        $store_id = $store_id ? $store_id : store_id();
        $statement = $this->db->prepare("SELECT * FROM `quotation_item` WHERE `store_id` = ? AND `reference_no` = ?");
        $statement->execute(array($store_id, $reference_no));
        $rows = $statement->fetchAll(PDO::FETCH_ASSOC);
        $array = array();
        $i = 0;
        foreach ($rows as $row) {
            $array[$i] = $row;
            $array[$i]['p_type'] = get_the_product($row['item_id'],'p_type');
            $array[$i]['unitName'] = get_the_unit(get_the_product($row['item_id'])['unit_id'],'unit_name');
            $array[$i]['item_code'] = get_the_product($row['item_id'],'p_code');
            $i++;
        }
        return $array;
    }
}