<?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 = $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'];
        $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'];
            $tax                = $product['tax_amount'];
            $product_total      = ($product['unit_price']*$product_quantity);
            $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;
            }
			//designacion de esatdo de orden
//is_order

//1 sin entrega
//2 con entregas
//0 presupuesto

$is_order = 0;

          //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, 0, $taxrate_id, 1, $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') {
					$is_order = 1;
		
		  }
        }

        $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, is_order, 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, $is_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
        ));

        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();

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

    // Pagos (otros medios)
    $importe_pesos     = isset($request->post['importe-pesos']) ? (float)$request->post['importe-pesos'] : 0;
    $metodopago        = isset($request->post['pmethod-id']) ? $request->post['pmethod-id'] : null;

    $numero_deposito   = isset($request->post['numero-deposito']) ? $request->post['numero-deposito'] : 0;
    $fecha_deposito    = isset($request->post['fecha-deposito']) ? $request->post['fecha-deposito'] : null;
    $importe_deposito  = isset($request->post['importe-deposito']) ? (float)$request->post['importe-deposito'] : 0;

    $numero_tarjeta    = isset($request->post['numero-tarjeta']) ? $request->post['numero-tarjeta'] : null;
    $fecha_tarjeta     = isset($request->post['fecha-tarjeta']) ? $request->post['fecha-tarjeta'] : null;
    $importe_tarjeta   = isset($request->post['importe-tarjeta']) ? (float)$request->post['importe-tarjeta'] : 0;

    $importe_dolar     = isset($request->post['importe-dolar']) ? (float)$request->post['importe-dolar'] : 0;
    $cotizacion_dolar  = isset($request->post['importe-cotizacion']) ? (float)$request->post['importe-cotizacion'] : 0;

    // Para cuotas (evita variable indefinida)
    $paid_amount                 = isset($request->post['paid-amount']) ? (float)$request->post['paid-amount'] : 0;
    $is_installment_order        = isset($request->post['is_installment_order']) ? $request->post['is_installment_order'] : '';
    $installment_interest_percentage = 0;
    $installment_interest_amount     = 0;
    if (defined('INSTALLMENT') && INSTALLMENT && $is_installment_order) {
        $installment_initial_amount     = $paid_amount;
        $installment_duration           = isset($request->post['installment_duration']) ? (int)$request->post['installment_duration'] : 0;
        $installment_interval_count     = isset($request->post['installment_interval_count']) ? (int)$request->post['installment_interval_count'] : 0;
        $installment_count              = isset($request->post['installment_count']) ? (int)$request->post['installment_count'] : 0;
        $installment_interest_percentage= isset($request->post['installment_interest_percentage']) ? (float)$request->post['installment_interest_percentage'] : 0;
        $installment_interest_amount    = isset($request->post['installment_interest_amount']) ? (float)$request->post['installment_interest_amount'] : 0;
        $installmentEndDate             = date('Y-m-d H:i:s', strtotime(' + '.$installment_duration.' days'));
    }

    // -------- CHEQUES (leer SIEMPRE de los arrays y calcular total) --------
    $num_cheques      = isset($_POST['num_cheque'])      ? $_POST['num_cheque']      : array();
    $fechas_emision   = isset($_POST['fecha_emision'])   ? $_POST['fecha_emision']   : array();
    $fechas_pago      = isset($_POST['fecha_cheque'])    ? $_POST['fecha_cheque']    : array();
    $importes_cheques = isset($_POST['importe_cheque'])  ? $_POST['importe_cheque']  : array();
    $cuits_titulares  = isset($_POST['cuit_titular'])    ? $_POST['cuit_titular']    : array();
    $bancos           = isset($_POST['banco'])           ? $_POST['banco']           : array();
    $observaciones    = isset($_POST['observaciones'])   ? $_POST['observaciones']   : array();
    $tipos_cheque     = isset($_POST['tipo_cheque'])     ? $_POST['tipo_cheque']     : array(); // radios por fila: 2=f�sico, 17=echeq

    // Total de cheques desde el array (ignora importe-chequet del form)
    $importe_cheque_t = 0.0;
    foreach ($importes_cheques as $v) {
        $v = str_replace('.', '', (string)$v);
        $v = str_replace(',', '.', $v);
        $importe_cheque_t += (float)$v;
    }

    // -------- VALIDACIONES DE PAGO --------
    $payment_status = 'due';
    $pagostotales   = $importe_cheque_t + $importe_tarjeta + $importe_pesos + $importe_deposito + ($importe_dolar * $cotizacion_dolar);

    if ($status === 'presupuesto' && $pagostotales != 0) {
        throw new Exception(trans('Atencion, este documento no puede ser de tipo presupuesto por que tiene pagos debes cambiar a venta anticipada, o bien no declarar pagos'));
    }

   if ($payable_amount > 0 && $status !== 'presupuesto') {
    $pagostotales   = round((float) str_replace(',', '.', $pagostotales), 2);
    $payable_amount = round((float) str_replace(',', '.', $payable_amount), 2);

    if (abs($pagostotales - $payable_amount) > 0.001) {
        $payment_status = 'due';
        throw new Exception(
            trans(
                'ERROR, El importe del comprobante NO es igual que la contrapartida de pagos. ' .
                'Comprobante: ' . $payable_amount . ' | Pagos: ' . $pagostotales
            )
        );
    } else {
        $payment_status = 'paid';
    }
}


    // -------- �TEMS --------
    $product_discount = $total_items > 0 ? ($discount_amount / $total_items) : 0;

    // recalcular subtotal desde los �tems
    $subtotal = 0;
    $igst = $cgst = $sgst = 0;
    $tgst = $tigst = $tcgst = $tsgst = 0;
    $total_purchase_price = 0;

    $statement = $this->db->prepare("DELETE 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_info['category_id'];
        $brand_id         = $product_info['brand_id'];
        $sup_id           = $product_info['sup_id'];
        $product_quantity = (float)$product['quantity'];
        $product_price    = (float)$product['unit_price'];
        $taxrate          = (float)$product['taxrate'];
        $tax              = (float)$product['tax_amount'];
        $product_total    = $product_price * $product_quantity;
        $item_tax         = 0; // no se usa en tu l�gica
        $purchase_invoice_id  = NULL;
        $item_purchase_price  = 0;

        $subtotal += $product_total;
        $taxrate_id = $product_info['taxrate_id'];

        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("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, 1, $taxrate, $cgst, $sgst, $igst,
            $product_quantity, $product_quantity, $product_total, $purchase_invoice_id
        ));

        // Ventas a entregar
        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));
        }
    }

    // -------- MOVIMIENTOS DE CAJA/BANCO --------
    $title             = 'Ingreso por venta anticipada';
    $image             = null;
    $is_order          = 0;
    $transaction_type  = 'deposit';

    if ($status !== 'presupuesto') {
        $is_order = 1;

        // --- CHEQUES (insertar por fila; caja 2=f�sico, 17=echeq) ---
        if (!empty($num_cheques)) {
            $status_che = 'in';
            $ref_no     = $reference_no;

            $n = count($importes_cheques);
            for ($i = 0; $i < $n; $i++) {
                $num_cheque   = isset($num_cheques[$i]) ? trim($num_cheques[$i]) : '';
                $raw          = isset($importes_cheques[$i]) ? (string)$importes_cheques[$i] : '0';
                $importe_norm = (float) str_replace(',', '.', str_replace('.', '', $raw));
                if ($num_cheque === '' || $importe_norm <= 0) continue;

                $fecha_emision = !empty($fechas_emision[$i]) ? $fechas_emision[$i] : date('Y-m-d');
                $fecha_pago    = !empty($fechas_pago[$i])    ? $fechas_pago[$i]    : $fecha_emision;
                $cuit_titular  = isset($cuits_titulares[$i]) ? $cuits_titulares[$i] : '';
                $banco         = isset($bancos[$i])          ? $bancos[$i] : '';
                $observacion   = isset($observaciones[$i])   ? $observaciones[$i] : '';

                $account_id = 2; // default f�sico
                if (isset($tipos_cheque[$i]) && in_array((string)$tipos_cheque[$i], ['2','17'], true)) {
                    $account_id = (int)$tipos_cheque[$i];
                }
                $tipo_txt = ($account_id === 17) ? 'electronico' : 'fisico';

                // bank_transaction_info
                $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, customer_id)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $statement->execute(array(
                    $store_id, $account_id, $store_id, $ref_no, $ref_no, $transaction_type, $title, $quotation_note,
                    $num_cheque, $fecha_pago, $importe_norm, $image, $user_id, $created_at, $customer_id
                ));
                $info_id = $this->db->lastInsertId();

                // bank_transaction_price
                $statement = $this->db->prepare("INSERT INTO `bank_transaction_price` (store_id, info_id, ref_no, amount, account_id_) VALUES (?, ?, ?, ?, ?)");
                $statement->execute(array($store_id, $info_id, $ref_no, $importe_norm, $account_id));

                // actualizar saldos
                $statement = $this->db->prepare("UPDATE `bank_account_to_store` SET `deposit` = `deposit` + {$importe_norm} WHERE `store_id` = ? AND `account_id` = ?");
                $statement->execute(array($store_id, $account_id));

                $statement = $this->db->prepare("UPDATE `bank_accounts` SET `total_deposit` = `total_deposit` + {$importe_norm} WHERE `id` = ?");
                $statement->execute(array($account_id));

                // cheques
                $statement = $this->db->prepare("INSERT INTO `cheques`
                    (numero, fecha, fecha_pago, importe, cuit, ref_id, invoice_no, caja_id, status, invoice_id, tipo_cheque, banco, observaciones)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $statement->execute(array(
                    $num_cheque, $fecha_emision, $fecha_pago, $importe_norm, $cuit_titular,
                    $info_id, $ref_no, $account_id, $status_che, $ref_no, $tipo_txt, $banco, $observacion
                ));
            }
        }

        // --- CAJA DIARIA PESOS (account_id = 1) ---
        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, customer_id)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $statement->execute(array($store_id, 1, $store_id, $reference_no, $reference_no, $transaction_type, $title, $customer_id, $image, $user_id, $created_at, $customer_id));
            $info_id = $this->db->lastInsertId();

            $statement = $this->db->prepare("INSERT INTO `bank_transaction_price` (store_id, info_id, ref_no, amount, account_id_) VALUES (?, ?, ?, ?, ?)");
            $statement->execute(array($store_id, $info_id, $reference_no, $importe_pesos, 1));

            $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));
        }

        // --- TARJETA (account_id = 16) ---
        if ($importe_tarjeta != 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, customer_id)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $statement->execute(array($store_id, 16, $store_id, $reference_no, $reference_no, $transaction_type, $title, $customer_id, $numero_tarjeta, $fecha_tarjeta, $importe_tarjeta, $image, $user_id, $created_at, $customer_id));
            $info_id = $this->db->lastInsertId();

            $statement = $this->db->prepare("INSERT INTO `bank_transaction_price` (store_id, info_id, ref_no, amount, account_id_) VALUES (?, ?, ?, ?, ?)");
            $statement->execute(array($store_id, $info_id, $reference_no, $importe_tarjeta, 16));

            $statement = $this->db->prepare("UPDATE `bank_account_to_store` SET `deposit` = `deposit` + {$importe_tarjeta} WHERE `store_id` = ? AND `account_id`  = ?");
            $statement->execute(array($store_id, 16));

            $statement = $this->db->prepare("UPDATE `bank_accounts` SET `total_deposit` = `total_deposit` + {$importe_tarjeta} WHERE `id` = ?");
            $statement->execute(array(16));
        }

        // --- DEP�SITO (account_id = 11) ---
        if (!empty($numero_deposito) && $importe_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, customer_id)
                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, $customer_id));
            $info_id = $this->db->lastInsertId();

            $statement = $this->db->prepare("INSERT INTO `bank_transaction_price` (store_id, info_id, ref_no, amount, account_id_ ) VALUES (?, ?, ?, ?, ?)");
            $statement->execute(array($store_id, $info_id, $reference_no, $importe_deposito, 11));

            $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));
        }

        // --- D�LAR (account_id = 5) ---
        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, cotizacion_dolar, image, created_by, created_at, customer_id)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $statement->execute(array($store_id, 5, $store_id, $reference_no, $reference_no, $transaction_type, $title, $customer_id, $cotizacion_dolar, $image, $user_id, $created_at, $customer_id));
            $info_id = $this->db->lastInsertId();

            $statement = $this->db->prepare("INSERT INTO `bank_transaction_price` (store_id, info_id, ref_no, amount, account_id_ ) VALUES (?, ?, ?, ?, ?)");
            $statement->execute(array($store_id, $info_id, $reference_no, $importe_dolar, 5));

            $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));
        }
    }

    // -------- ESTADO DE LA COTIZACI�N --------
    $restriccion = ($status === "venta anticipada") ? 1 : "";

    $statement = $this->db->prepare("UPDATE `quotation_info`
        SET `customer_id` = ?, `customer_mobile` = ?, `quotation_note` = ?, `total_items` = ?, `status` = ?, `payment_status` = ?, `is_installment` = ?, `is_order` = ?, `restriccion` = ?
        WHERE `reference_no` = ? AND `store_id` = ?");
    $statement->execute(array($customer_id, $customer_mobile, $quotation_note, $total_items, $status, $payment_status, $is_installment_order, $is_order, $restriccion, $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;
    }
}