<?php

    include_once("../include/main.inc.php");



    ini_set('display_errors', 1);

ini_set('display_startup_errors', 1);

error_reporting(E_ALL);

    function orderHistory($dbconn, $invoice_id, $cmnt_type, $remark, $inputs){

		$sql = mysqli_query($dbconn, "INSERT INTO order_item_history (invoice_id, created_at, label, remarks, responcObjects) VALUES ('".$invoice_id."', '".date('Y-m-d H:i:s')."', '".$cmnt_type."', '".$remark."', '".json_encode($inputs)."')");

        if(!$sql){

            echo mysqli_error($dbconn);

        }

	}





    if(isset($_REQUEST['itmId']) && isset($_REQUEST['update_order'])){

        $error = array('success' => true);

        $in = $_POST;

        $updat = '';

        if(isset($_POST['order_status'])){$updat .= 'order_status="'.$in['order_status'].'",';}

        if(isset($_POST['payment_status'])){$updat .= 'payment_status="'.$in['payment_status'].'",';}
        if(isset($_POST['application_number'])){$updat .= 'ApplicationNo="'.$in['application_number'].'",';}

        if(isset($_POST['kyc'])){$updat .= 'ekyc="'.$in['kyc'].'",';}
        if(isset($_POST['ChallengeCode'])){$updat .= 'ChallengeCode="'.$in['ChallengeCode'].'",';}
        if(isset($_POST['eKYCPin'])){$updat .= 'eKYCPin="'.$in['eKYCPin'].'",';}

        if(isset($_POST['caApproval'])){$updat .= 'caApproval="'.$in['caApproval'].'",';}

        if(isset($_POST['video'])){$updat .= 'video="'.$in['video'].'",';}

        if(isset($_POST['download'])){$updat .= 'download_status="'.$in['download'].'",';}

        if(isset($_POST['delivery'])){$updat .= 'delivery_status="'.$in['delivery'].'",';}

        if(isset($_POST['CourierReceipt'])){$updat .= 'delievry_reciept="'.$in['CourierReceipt'].'",';}

        if(isset($_POST['trackinglink'])){$updat .= 'trackingLink="'.$in['trackinglink'].'",';}
        if(isset($_POST['docketNumber'])){$updat .= 'docketNumber="'.$in['docketNumber'].'",';}

        if(isset($_POST['courierpartner'])){$updat .= 'courierPartner="'.$in['courierpartner'].'",';}

        if(isset($_POST['tokenPassword'])){$updat .= 'tokenPassword="'.$in['tokenPassword'].'",';}

        if(isset($_POST['remarks'])){$updat .= 'remarks="'.$in['remarks'].'",';}

        if(isset($_FILES['CourierReceipt']['name']) && !empty($_FILES['CourierReceipt']['name'])){

            $CourierReceipt = uniqid().basename($_FILES["CourierReceipt"]["name"]);

            $target_file = 'images/auth/'.$CourierReceipt;

            if(move_uploaded_file($_FILES["CourierReceipt"]["tmp_name"], $target_file)){

                $updat .= 'delievry_reciept="'.$CourierReceipt.'",';

            }

        }

        $sql = mysqli_query($dbconn, "UPDATE orders_tbl1 SET ".rtrim($updat, ',')." WHERE order_id = ".$in['itmId']);        

        if($sql){

            $rmk = 'Update order status, And Remarks: '.$in['remarks'];

            orderHistory($dbconn, $in['itmInvoiceId'], "UPDATE", $rmk, $in);

            $error['reload'] = true;

        }else{

            $error['msg'] = mysqli_error($dbconn);

        }



        echo json_encode($error);

    }



    if(isset($_REQUEST['itmHistory']) && !empty($_REQUEST['itmHistory'])){

        $error = array('success' => true);

        $in = $_POST;

        $qry = mysqli_query($dbconn, "SELECT * FROM order_item_history  WHERE order_item_id = ".$in['itmHistory']." ORDER BY history_id desc");

        $dd = '';

        while($q = mysqli_fetch_array($qry)){

            $dd .= '<div class="alert alert-light p-1 text-dark"><small class="text-info">'.date('h:ia d M Y', strtotime($q['created_at'])).'</small> <br>'.$q['remarks'].' </div>'; 

        }

        $error['html'] = $dd;

        echo json_encode($error);

    }

    

    if(isset($_REQUEST['updocumentid']) && !empty($_REQUEST['uporderId'])){

        $error = array('success' => false);

        $in = $_POST;

        if(empty($in['uporderId'])){$error['message']['uporderId'] = '<span class="frm-error">Id Not found</span>';}

        if(empty($in['updocumentname'])){$error['message']['uporderId'] = '<span class="frm-error">Id Not found</span>';}

        if(empty($_FILES['upFile']['name'])){$error['message']['uporderId'] = '<span class="frm-error">Please Upload docs</span>';}

        

        if(!isset($error['message'])){

            $name = uniqid().basename($_FILES["upFile"]["name"]);

            $target_file = 'images/auth/'.$name;

            if(move_uploaded_file($_FILES["upFile"]["tmp_name"], $target_file)){

                mysqli_query($dbconn, "UPDATE orders_documents SET docFile = '".$name."' WHERE docID= ".$in['updocumentid']);

                $rmk = $in['updocumentname'].' Updated Successfully by admin';

                orderHistory($dbconn, $in['uporderId'], "UPDATE", $rmk, $in);

                $error['reload'] = true;

                $error['success'] = true;

            }else{

                $error['message']['upitmId'] = '<span class="frm-error">Please Upload docs</span>'; 

            }



        }



        echo json_encode($error);

    }



    if(isset($_REQUEST['add_token_rcd']) && !empty($_REQUEST['add_token_rcd'])){
        $error = array('success' => false);
        $in = $_POST;
        if(empty($in['catname'])){$error['message']['catname'] = '<span class="frm-error">Enter catname</span>';}
        if(empty($_FILES['upFile']['name'])){$error['message']['upFile'] = '<span class="frm-error">Please Upload docs</span>';}

        if(!isset($error['message'])){
            $name = basename($_FILES["upFile"]["name"]);
            $target_file = '../uploaded-files/category/images/'.$name;
            if(move_uploaded_file($_FILES["upFile"]["tmp_name"], $target_file)){

                $data = array(
                    'parentID' => 11,
                    'catName' => $in['catname'], 
                    'displayName' => $in['catDname'],
                    'catDesc' => $in['shortdesc'],
                    'catDesc1' => $in['fulldesc'],
                    'catImage' => $name,
                    //'catprice' => $in['catprice'],
                    'pageTitle'=> $in['metatitle'],
                    'pageKeywords' => $in['metakeyword'],
                    'pageDescription' => $in['metadesc']
                );

                $q = mysqli_query($dbconn, "INSERT INTO category_tbl (".implode(',', array_keys($data)).") VALUES ('".implode("','", array_values($data))."')");

                 // $sql = mysqli_query($GLOBALS['dbconn'], "insert into `$table_name` set parentID='$parentID',catName='" . $catname . "',displayName='" . $catDname . "',usertype='" . $usertype . "',catgurl='$catgurl',catDesc='" . $shortdesc . "',catDesc1='" . $fulldesc . "',catImage='" . $img . "',catIcon='$img1',catprice='$catprice',heading1='" . $heading1 . "',heading2='" . $heading2 . "',heading3='" . $heading3 . "',pageTitle='" . $metatitle . "',pageKeywords='" . $metakeyword . "',pageDescription='" . $metadesc . "', gst='$gst',mca='$mca',epf='$epf',iec='$iec',ptr='$ptr',eticket='$eticket',cp='$cp',cbe='$cbe',etp='$etp',vb='$vb',certificateUsed='$certificateUsed',dgft='$dgft',iet='$iet', required_doc='$required_doc'");

                $error['reload'] = true;
                $error['success'] = true;
            }else{
                $error['message']['upitmId'] = '<span class="frm-error">Please Upload docs</span>'; 
            }
        }

        echo json_encode($error);
    }



    if(isset($_REQUEST['add_agent']) && !empty($_REQUEST['agent_name'])){

        $error = array('success' => false);

        $in = $_POST;

        if(empty($in['agent_type'])){$error['message']['agent_type'] = '<span class="frm-error">Select agent type</span>';}

        if(empty($in['agent_password'])){$error['message']['agent_password'] = '<span class="frm-error">Enter login password</span>';}

        if(empty($in['agent_id'])){$error['message']['agent_id'] = '<span class="frm-error">Enter login id</span>';}

        if(empty($in['agent_name'])){$error['message']['agent_name'] = '<span class="frm-error">Enter agent name</span>';}

        if(empty($in['agent_mobile']) && !ctype_digit($in['agent_mobile']) && strlen($in['agent_mobile']) != 10){$error['message']['agent_mobile'] = '<span class="frm-error">Enter agent mobile</span>';}

        

        if(!isset($error['message'])){

            $data = array(

                'user_id' => $in['agent_id'], 

                'pwd' => $in['agent_password'], 

                'user_type' => $in['agent_type'], 

                'status' => 'Y', 

                'name' => $in['agent_name'], 

                'email' => $in['agent_email'], 

                'mobile' => $in['agent_mobile'],

                'addedOn' => date('Y-m-d')

            );

            $q = mysqli_query($dbconn, "INSERT INTO admin_details (".implode(',', array_keys($data)).") VALUES ('".implode("','", array_values($data))."')");



            if($q){

                $error['reload'] = true;

                $error['success'] = true;

            }else{

                $error['message']['agent_name'] = '<span class="frm-error">'.mysqli_error($dbconn).'</span>';

            }



        }



        echo json_encode($error);

    }



    if(isset($_REQUEST['edit_agent']) && !empty($_REQUEST['eagent_name'])){

        $error = array('success' => false);

        $in = $_POST;

        if(empty($in['eagent_name'])){$error['message']['eagent_name'] = '<span class="frm-error">Enter agent name</span>';}

        if(empty($in['eagent_mobile']) || !ctype_digit($in['eagent_mobile']) || strlen($in['eagent_mobile']) != 10){$error['message']['eagent_mobile'] = '<span class="frm-error">Enter agent mobile</span>';}

        if(empty($in['edit_agent']) && !ctype_digit($in['edit_agent'])){$error['message']['edit_agent'] = '<span class="frm-error">Invalid agent to edit</span>';}

        

        if(!isset($error['message'])){

            $q = mysqli_query($dbconn, "UPDATE admin_details SET user_id='".$in['eagent_id']."', pwd='".$in['eagent_password']."', user_type='".$in['eagent_type']."', name='".$in['eagent_name']."', email='".$in['eagent_email']."', mobile='".$in['eagent_mobile']."' WHERE slno=". $in['edit_agent']);

            if($q){

                $error['reload'] = true;

                $error['success'] = true;

            }else{

                $error['message']['agent_name'] = '<span class="frm-error">'.mysqli_error($dbconn).'</span>';

            }



        }



        echo json_encode($error);

    }



    if(isset($_REQUEST['assign_agent_id']) && !empty($_REQUEST['orderId'])){

        $error = array('success' => false);

        $in = $_POST;

        if(empty($in['assign_agent_id'])){$error['message'] .= 'Select Agent ';}

        if(!isset($error['message'])){

            $q = mysqli_query($dbconn, "UPDATE orders_tbl1 SET agentId=".$in['assign_agent_id']." WHERE order_id IN (".implode(',', $in['orderId']).")" );

            if($q){

                $error['success'] = true;

            }else{

                $error['message'] =  mysqli_error($dbconn);

            }



        }



        echo json_encode($error);

    }

    

    if(isset($_REQUEST['removeDoc_id']) && !empty($_REQUEST['removeDoc_id'])){

        $error = array('success' => false);

        $in = $_POST;

        if(empty($in['removeDoc_id'])){$error['message'] .= 'Select doc id ';}

        if(!isset($error['message'])){

            $q = mysqli_query($dbconn, "UPDATE orders_documents SET docFile=null WHERE docID=".$in['removeDoc_id']);

            if($q){

                $error['success'] = true;

            }else{

                $error['message'] =  mysqli_error($dbconn);

            }

        }

        echo json_encode($error);

    }



    if(isset($_REQUEST['savedoc_remark']) && !empty($_REQUEST['savedoc_remark'])){

        $error = array('success' => false);

        $in = $_POST;

        if(empty($in['docremrk_id'])){$error['message'] .= 'Select doc id ';}

        if(!isset($error['message'])){

            $q = mysqli_query($dbconn, "UPDATE orders_tbl1 SET doc_remarks='".$_REQUEST['savedoc_remark']."' WHERE order_id=".$in['docremrk_id']);

            if($q){

                $error['success'] = true;

            }else{

                $error['message'] =  mysqli_error($dbconn);

            }

        }

        echo json_encode($error);

    }



    if(isset($_REQUEST['upagentid']) && !empty($_REQUEST['update_agent_oid'])){

        $error = array('success' => false);

        $in = $_POST;

        if(empty($in['update_agent_oid'])){$error['message']['update_agent_oid'] = '<span class="frm-error">Select order id</span>';}

        if(empty($in['upagentid'])){$error['message']['update_agent_oid'] = '<span class="frm-error">Select agent id</span>';}

        if(!isset($error['message'])){

            $q = mysqli_query($dbconn, "UPDATE orders_tbl1 SET agentId='".$_REQUEST['upagentid']."' WHERE order_id=".$in['update_agent_oid']);

            if($q){

                $rmk = 'Assigned New Agent';

                orderHistory($dbconn, $in['agent_invoice'], "UPDATE", $rmk, $in);

                $error['success'] = true;

                $error['reload'] = true;

            }else{

                $error['message'] =  mysqli_error($dbconn);

            }

        }

        echo json_encode($error);

    }



    if(isset($_POST['pendingdoc_oId']) && !empty($_POST['pendingdoc_oId'])){

        $error = array('success' => false);

        $in = $_POST;

        if(empty($in['pendingdoc_oId'])){$error['message']['pendingdoc_oId'] = '<span class="frm-error">Select order id</span>';}

        if(empty($in['docmailremark'])){$error['message']['pendingdoc_oId'] = '<span class="frm-error">Enter remark</span>';}

        if(!isset($in['pendingdoc'])){$error['message']['pendingdoc_oId'] = '<span class="frm-error">Select atleat one document</span>';}

        if(!isset($error['message'])){

            $qry =mysqli_fetch_array(mysqli_query($dbconn, "SELECT invoice_id, applicants_email, applicants_name FROM orders_tbl1 WHERE order_id = ".$in['pendingdoc_oId']));



            $name = $qry['applicants_name'];

            $to = $qry['applicants_email'];

            $oid = $qry['invoice_id'];



            $body = get_emailcontent('auto_emails','8');

			$body = str_replace('[user]', $name, $body);

			$body = str_replace('[orderid]',$oid, $body);			

			$body = str_replace('[remarks]',$in['docmailremark'], $body);			

			$body = str_replace('[documents]','<ol><li>'.implode('</li><li>', $in['pendingdoc']).'</li></ol>', $body);			

			$htmlContent = $body;			

			$subject = "Reminder for Pending Document #".$oid;





            $emailadmin = 'order@webpulse.com';

            /* Email For User start*/

            smtp_mailer($to, $emailadmin, $name, $subject, $htmlContent);



            $error['success'] = true;

            $error['reload'] = true;

        }

        echo json_encode($error);

    }



    if(isset($_POST['order_signature']) && isset($_POST['order_token']) && isset($_POST['order_invoice_id'])){
        $error = array('success' => false);
        $in = $_POST;
        if(empty($in['order_invoice_id'])){$error['message']['order_invoice_id'] = '<span class="frm-error">Select order id</span>';}
        if(empty($in['order_remarks'])){$error['message']['order_remarks'] = '<span class="frm-error">Enter remark</span>';}
        if($in['order_token'] == 1){
            if(empty($in['order_token_id'])){$error['message']['order_token_id'] = '<span class="frm-error">Select token</span>';}
            if(empty($in['order_token_type'])){$error['message']['order_token_type'] = '<span class="frm-error">Select type</span>';}
            if(empty($in['order_token_qty']) || !ctype_digit($in['order_token_qty'])){$error['message']['order_token_qty'] = '<span class="frm-error">Enter valid Qty</span>';}
        }
        if(!empty($in['order_signature'])){
            $order_qry = mysqli_fetch_array(mysqli_query($dbconn, "SELECT a.*, b.brandName, c.catName FROM attribute_tbl AS a LEFT JOIN brand_tbl AS b ON a.brand_id=b.slno LEFT JOIN category_tbl AS c ON c.catID=a.cat_id WHERE a.slno = ".$in['order_signature']));
            if($order_qry['user_type'] == 'Organization'){
                if(empty($in['order_bussinesstype'])){$error['message']['order_bussinesstype'] = '<span class="frm-error">Select type</span>';}
            }
        }

        if(!isset($error['message'])){
            $total_price = 0;
            mysqli_query($dbconn, "DELETE FROM order_items WHERE invoice_id='".$in['order_invoice_id']."'");
            $delivery_address = $delivery_city =$delivery_state = $delivery_zip = $delivery_country = '';
            $delivery_status = $ekyc = 'NA';
            if($in['order_token'] == 1){
                $cat_res1 = mysqli_fetch_assoc(mysqli_query($dbconn, "SELECT token_id, price FROM token_price_tbl WHERE min_quantity<=".$in['order_token_qty']." AND max_quantity>=".$in['order_token_qty']." AND token_id=".$in['order_token_id']));
                $total_price += ($cat_res1['price']*$in['order_token_qty']);
                $token = array(
                    'invoice_id' => $in['order_invoice_id'],
                    'category_id' => $in['order_token_id'],
                    'quantity' => $in['order_token_qty'],
                    'token_type' => $in['order_token_type'],
                    'price_each' => $cat_res1['price']
                );

                $itm_instr1 = mysqli_query($dbconn, "INSERT INTO order_items (".implode(',', array_keys($token)).") VALUES ('".implode("','", array_values($token))."')");
                $delivery_status = 'PENDING';
                $delivery_address = strtoupper($in['delivery_address']);
                $delivery_city = strtoupper($in['delivery_city']);
                $delivery_state = strtoupper($in['delivery_state']);
                $delivery_zip = $in['delivery_zip'];
                $delivery_country = 'INDIA';
                $token_name = mysqli_fetch_assoc(mysqli_query($dbconn, "SELECT catName FROM category_tbl WHERE catID=".$in['order_token_id']));
                $token_order = 'Token: '.$token_name['catName'].', Token Type: '.$in['order_token_type'].', Quantity: '.$in['order_token_qty'];
            }

            if(!empty($in['order_signature'])){
                $orgtype = ($order_qry['user_type'] == 'Organization')?$in['order_bussinesstype']:'';
                $items1 = array(
                    'invoice_id' => $in['order_invoice_id'],
                    'category_id' => $order_qry['cat_id'],
                    'brand' => $order_qry['brandName'],
                    'validity' => $order_qry['validity'],
                    'user_type' => $order_qry['user_type'],
                    'organizationType' => $orgtype,
                    'quantity' => 1,
                    'price_each' => $order_qry['price']
                );
                $total_price += $order_qry['price'];
                $itm_instr = mysqli_query($dbconn, "INSERT INTO order_items (".implode(',', array_keys($items1)).") VALUES ('".implode("','", array_values($items1))."')");

                $documnt = mysqli_fetch_assoc(mysqli_query($dbconn, "SELECT documents FROM documents_tbl WHERE user_type='".$items1['user_type']."' and org_type='".$orgtype."'"));

                $docList = '';

                $old_doc = mysqli_query($dbconn, "SELECT docName FROM orders_documents WHERE invoice_id='".$in['order_invoice_id']."' and docFile!=''");
                $olddoclist = [];
                while($odc = mysqli_fetch_array($old_doc)){
                    $olddoclist[] = $odc['docName'];
                }

                foreach(explode(',', $documnt['documents']) as $dl){
                    if(!in_array(trim($dl), $olddoclist)){
                        $docList .= "('".$in['order_invoice_id']."', '".trim($dl)."'),";
                    }
                }

                $signature_order = 'Signature: '.$order_qry['catName'].', Brand: '.$items1['brand'].', Validity: '.$items1['validity'].', User type: '.$items1['user_type'].' '.$orgtype;
               
                $ekyc = 'PENDING';
            }

            $discount = !empty($in['discount_amount'])?$in['discount_amount']:0;

            $q = mysqli_query($dbconn, "UPDATE orders_tbl1 SET total_amount=".round($total_price).", gst_amount=".round(($total_price-$discount)*0.18).", coupon_code='".$in['discount_coupon']."', discount='".$discount."', delivery_address='".$delivery_address."', delivery_city='".$delivery_city."', delivery_state='".$delivery_state."', delivery_zip='".$delivery_zip."', delivery_country='".$delivery_country."', delivery_status='".$delivery_status."', ekyc='".$ekyc."', video='".$ekyc."', caApproval='".$ekyc."', download_status='".$ekyc."', remarks='".$in['order_remarks']."' WHERE invoice_id='".$in['order_invoice_id']."'");
          

            if(isset($docList) && !empty($docList)){                
				$qk = mysqli_query($dbconn, "DELETE FROM orders_documents WHERE invoice_id='".$in['order_invoice_id']."' AND docFile=''");
				$qk = mysqli_query($dbconn, "INSERT INTO orders_documents (invoice_id, docName) VALUES ".rtrim($docList, ','));
				if(!$qk){
					echo mysqli_error($dbconn);
				}
			}

            $new_order = isset($signature_order)?$signature_order:'';
            $new_order .= isset($token_order)?' | '.$token_order:'';

            $rmk = 'Update order products From (Old order: '.$in['old_product'].') to (New Order: '.$new_order.')., Remarks: '.$in['order_remarks'];

            orderHistory($dbconn, $in['order_invoice_id'], "UPDATE", $rmk, $in);
            $edithistory = mysqli_query($dbconn, "INSERT INTO order_edit_history (invoice_id, created_at, old_order) VALUES('".$in['order_invoice_id']."', '".date('Y-m-d H:i:s')."', '".$in['old_product']."')");

            if(!$edithistory){
                echo mysqli_error($dbconn);
            }
            //Email section start
            $user_info = mysqli_fetch_array(mysqli_query($dbconn, "SELECT applicants_name, bill_email FROM orders_tbl1 WHERE invoice_id='".$in['order_invoice_id']."'"));
            $name = $user_info['applicants_name'];
		    $to = $user_info['bill_email'];

            $body = get_emailcontent('auto_emails','9');
            $body = str_replace('[user]', $name, $body);

            $body = str_replace('[orderid]',$in['order_invoice_id'], $body);

            $body = str_replace('[oldorder]',$in['old_product'], $body);

            $body = str_replace('[neworder]',$new_order, $body);

            $body = str_replace('[remarks]',$in['order_remarks'], $body);

            $htmlContent = $body;			

            $subject = "Order modification ORDERID#".$in['order_invoice_id'];



            $emailadmin = 'order@webpulse.com';

            smtp_mailer($to, $emailadmin, $name, $subject, $htmlContent);

            //Email section end





            $error['success'] = true;

            $error['reload'] = true;

        }

        echo json_encode($error);

    }



    if(isset($_POST['pay_amount']) && isset($_POST['pay_invoiceid']) && isset($_POST['pay_id'])){

        $error = array('success' => false);

        $in = $_POST;

        if(empty($in['pay_invoiceid'])){$error['message']['pay_invoiceid'] = '<span class="frm-error">Select order id</span>';}

        if(empty($in['pay_amount']) || !ctype_digit($in['pay_amount'])){$error['message']['pay_amount'] = '<span class="frm-error">Enter valid amount</span>';}

        if(empty($in['pay_mode'])){$error['message']['pay_mode'] = '<span class="frm-error">Enter payment mode</span>';}

        if(empty($in['pay_id'])){$error['message']['pay_id'] = '<span class="frm-error">Payment id</span>';}

        if(empty($in['payremark'])){$error['message']['payremark'] = '<span class="frm-error">Enter remark</span>';}

        if(!isset($error['message'])){

            $success_order_id = $in['success_order_id'];

            if(empty($in['success_order_id'])){
                $success_id = mysqli_fetch_assoc(mysqli_query($dbconn, "SELECT max(SUBSTRING(success_order_id, 11, LENGTH(success_order_id))) as maxid FROM orders_tbl1"));
                if($success_id['maxid']){
                    $sid = $success_id['maxid']+1;
                }else{
                    $sid = 1;
                }
                if(strlen($sid) ==1){$sid = '00'.$sid;}
                if(strlen($sid) ==2){$sid = '0'.$sid;}
                $success_order_id = 'DSC/24-25/'.$sid;
            }

            $responceObject = '{"order_id":"'.$in['pay_invoiceid'].'","tracking_id":"'.$in['pay_id'].'","bank_ref_no":"null","failure_message":"","payment_mode":"'.$in['pay_mode'].'","card_name":"","status_code":"null","status_message":".","currency":"INR","amount":"'.$in['pay_amount'].'"}';

            $paydata = array(

                'invoice_id' => $in['pay_invoiceid'],

                'payment_invoice_id' => $in['pay_invoiceid'],

                'requested_amount' => $in['pay_amount'],

                'tracking_id' => $in['pay_id'],

                'payment_mode' => $in['pay_mode'],

                'payment_remark' => $in['payremark'],

                'responceObject' => $responceObject,

                'created_at' => date('Y-m-d H:i:s')

            );





            $itm_instr1 = mysqli_query($dbconn, "INSERT INTO order_payment_history (".implode(',', array_keys($paydata)).") VALUES ('".implode("','", array_values($paydata))."')");

            if($itm_instr1){

                $total_payment = mysqli_fetch_assoc(mysqli_query($dbconn, "SELECT sum(requested_amount) AS total_paid FROM order_payment_history WHERE invoice_id='".$in['pay_invoiceid']."'"));

                $order_amount = mysqli_fetch_assoc(mysqli_query($dbconn, "SELECT total_amount, discount, gst_amount FROM orders_tbl1 WHERE invoice_id='".$in['pay_invoiceid']."'"));

                $paystts = 'PARTIAL';

                if($total_payment['total_paid'] == (($order_amount['total_amount']-$order_amount['discount'])+$order_amount['gst_amount'])){

                    $paystts = 'SUCCESS';

                }



                $q = mysqli_query($dbconn, "UPDATE orders_tbl1 SET order_status='ACTIVE', payment_status='".$paystts."', success_order_id='".$success_order_id."' WHERE invoice_id='".$in['pay_invoiceid']."'");

                



                $rmk = 'Added new payment of '.$in['pay_amount'].' & Payment Mode is '.$in['pay_mode'].', Remarks: '.$in['payremark'];

                orderHistory($dbconn, $in['pay_invoiceid'], "UPDATE", $rmk, $in);

                $error['success'] = true;

                $error['reload'] = true;

            }else{



            }

        }

        echo json_encode($error);

    }



    if(isset($_POST['epay_amount']) && isset($_POST['epay_id']) && isset($_POST['pay_editid'])){
        $error = array('success' => false);
        $in = $_POST;
        if(empty($in['epay_invoiceid'])){$error['message']['epay_invoiceid'] = '<span class="frm-error">Select order id</span>';}
        if(empty($in['epay_amount']) || !ctype_digit($in['epay_amount'])){$error['message']['epay_amount'] = '<span class="frm-error">Enter valid amount</span>';}
        if(empty($in['epay_id'])){$error['message']['pay_id'] = '<span class="frm-error">Payment id</span>';}
        if(!isset($error['message'])){
            mysqli_query($dbconn, "UPDATE order_payment_history SET requested_amount='".$in['epay_amount']."', tracking_id='".$in['epay_id']."' WHERE payment_id=".$in['pay_editid']);
            $total_payment = mysqli_fetch_assoc(mysqli_query($dbconn, "SELECT sum(requested_amount) AS total_paid FROM order_payment_history WHERE invoice_id='".$in['epay_invoiceid']."'"));

            $order_amount = mysqli_fetch_assoc(mysqli_query($dbconn, "SELECT total_amount, discount, gst_amount FROM orders_tbl1 WHERE invoice_id='".$in['epay_invoiceid']."'"));

            $paystts = 'PARTIAL';

            if($total_payment['total_paid'] == (($order_amount['total_amount']-$order_amount['discount'])+$order_amount['gst_amount'])){

                $paystts = 'SUCCESS';

            }

            $q = mysqli_query($dbconn, "UPDATE orders_tbl1 SET payment_status='".$paystts."' WHERE invoice_id='".$in['epay_invoiceid']."'");

            

            $error['success'] = true;

            $error['reload'] = true;

        }

        echo json_encode($error);

    }



    if(isset($_POST['dosc_invoiceid']) && isset($_POST['document_name'])){

        $error = array('success' => false);

        $in = $_POST;

        if(empty($in['dosc_invoiceid'])){$error['message']['dosc_invoiceid'] = '<span class="frm-error">Select invoice id</span>';}

        if(empty($in['document_name'])){$error['message']['document_name'] = '<span class="frm-error">Enter document name</span>';}

        if(!isset($error['message'])){

            $itm_instr1 = mysqli_query($dbconn, "INSERT INTO orders_documents (invoice_id, docName) VALUES ('".$in['dosc_invoiceid']."', '".$in['document_name']."')");

            if($itm_instr1){

                $error['success'] = true;

                $error['reload'] = true;

            }else{

                $error['message']['document_name'] = '<span class="frm-error">'.(mysqli_error($dbconn)).'</span>';

            }

        }

        echo json_encode($error);

    }


    if(isset($_POST['delete_docs']) && !empty($_POST['delete_docs'])){
        $error = array('success' => false);
        $in = $_POST;
        if(empty($in['delete_docs'])){$error['message']['delete_docs'] = '<span class="frm-error">Select invoice id</span>';}
        if(!isset($error['message'])){
            $delete = mysqli_query($dbconn, "DELETE FROM orders_documents WHERE docID=".$in['delete_docs']);
            if($delete){
                $error['success'] = true;
                $error['reload'] = true;
            }else{
                $error['message']['delete_docs'] = '<span class="frm-error">'.(mysqli_error($dbconn)).'</span>';
            }
        }

        echo json_encode($error);

    }

    if(isset($_REQUEST['add_brand']) && !empty($_REQUEST['add_brand'])){
        $error = array('success' => false);
        $in = $_POST;
        if(empty($in['brandname'])){$error['message']['brandname'] = '<span class="frm-error">Enter brand name</span>';}
        if(empty($in['brandtitle'])){$error['message']['brandtitle'] = '<span class="frm-error">Enter brand title</span>';}
        if(empty($_FILES['upFile']['name'])){$error['message']['upFile'] = '<span class="frm-error">Please upload brand image</span>';}

        if(!isset($error['message'])){
            $name = basename($_FILES["upFile"]["name"]);
            $target_file = '../uploaded-files/brand-logo/'.$name;
            if(move_uploaded_file($_FILES["upFile"]["tmp_name"], $target_file)){

                $data = array(
                    'parentID' => 14,
                    'catName' => $in['catDname'], 
                    'displayName' => $in['catDname'],
                    'catDesc' => $in['shortdesc'],
                    'catDesc1' => $in['fulldesc'],
                    'catImage' => $name,
                    'pageTitle'=> $in['metatitle'],
                    'pageKeywords' => $in['metakeyword'],
                    'pageDescription' => $in['metadesc']
                );

                $q = mysqli_query($dbconn, "INSERT INTO category_tbl (".implode(',', array_keys($data)).") VALUES ('".implode("','", array_values($data))."')");

                if($q){
                    $catID = mysqli_insert_id($dbconn);
                    
                    $brandData = array(
                        'brandName' => $in['brandname'], 
                        'brandTitle' => $in['brandtitle'],
                        'brandImage' => $name,
                        'status' => 'Y',
                        'catID' => $catID
                    );
    
                    $q = mysqli_query($dbconn, "INSERT INTO brand_tbl (".implode(',', array_keys($brandData)).") VALUES ('".implode("','", array_values($brandData))."')");
                    $error['reload'] = true;
                    $error['success'] = true;
                }

            }else{
                $error['message']['upitmId'] = '<span class="frm-error">Please Upload Brand image</span>'; 
            }
        }

        echo json_encode($error);
    }


    if(isset($_REQUEST['enquiry_agent_id']) && !empty($_REQUEST['enquiry_agent_id'])){
        $error = array('success' => false);
        $in = $_POST;
        if(empty($in['enquiryId'])){$error['message'] .= 'Select Agent ';}
        if(!isset($error['message'])){
            $q = mysqli_query($dbconn, "UPDATE crm_tbl SET agentId=".$in['enquiry_agent_id']." WHERE id IN (".implode(',', $in['enquiryId']).")" );
            if($q){
                $error['success'] = true;
            }else{
                $error['message'] =  mysqli_error($dbconn);
            }
        }
        echo json_encode($error);
    }

    if(isset($_REQUEST['applicantsUpdate']) && isset($_REQUEST['NameasperPAN'])){

        $error = array('success' => true);

        $in = $_POST;

        $updat = '';

        if(isset($_POST['OrgTradeName'])){$updat .= 'OrgTradeName="'.$in['OrgTradeName'].'",';}
        if(isset($_POST['OrgLegalName'])){$updat .= 'OrgLegalName="'.$in['OrgLegalName'].'",';}
        if(isset($_POST['OrgGSTNo'])){$updat .= 'OrgGSTNo="'.$in['OrgGSTNo'].'",';}
        if(isset($_POST['AadhaarNo'])){$updat .= 'AadhaarNo="'.$in['AadhaarNo'].'",';}
        if(isset($_POST['dob'])){$updat .= 'dob="'.$in['dob'].'",';}
        if(isset($_POST['NameasperPAN'])){$updat .= 'NameasperPAN="'.$in['NameasperPAN'].'",';}
        if(isset($_POST['ApplicantPAN'])){$updat .= 'ApplicantPAN="'.$in['ApplicantPAN'].'",';}
        if(isset($_POST['applicants_name'])){$updat .= 'applicants_name="'.$in['applicants_name'].'",';}
        if(isset($_POST['applicants_org'])){$updat .= 'applicants_org="'.$in['applicants_org'].'",';}
        if(isset($_POST['applicants_mobile'])){$updat .= 'applicants_mobile="'.$in['applicants_mobile'].'",';}
        if(isset($_POST['applicants_email'])){$updat .= 'applicants_email="'.$in['applicants_email'].'",';}
        $sql = mysqli_query($dbconn, "UPDATE orders_tbl1 SET ".rtrim($updat, ',')." WHERE order_id = ".$in['applicantsUpdate']);

        if($sql){
            $error['reload'] = true;
        }else{

            $error['msg'] = mysqli_error($dbconn);

        }



        echo json_encode($error);

    }


?>