<?php
require_once ('config.php');
require_once ('send_notification.php');
require_once ('f_insert_notification_log.php');
require_once ('find_online_tablet.php');
require_once ('f_logging.php');

$insert_ntf = false;
$error_message;
$valid = true;
$now = date("Ymdhisa");
$file_name = __DIR__ . "\mobile_log\_insert_workorder.log";

/* Begin the transaction. */
if (sqlsrv_begin_transaction($conn) === false)
{
    die(print_r(sqlsrv_errors() , true));
}

$json = file_get_contents('php://input');

// Converts it into a PHP object
$data = json_decode($json, true);

$site_cd = $data['site_cd'];
$sync_step = $data['sync_step'];
$sync_time = $data['sync_time'];
$sync_status = $data['sync_status'];
$sync_url = $data['sync_url'];
$LOGINID = $data['LOGINID'];

if ($sync_status == "online")
{

}
else
{
    f_logging($json, "insert_workorder.php", $sync_url, $LOGINID, $sync_step, $sync_time, $site_cd);
}

$EmpID = $data['EmpID'];
$EmpName = $data['EmpName'];

$wko_mst_originator = $data['wko_mst_originator'];
$wko_mst_phone = $data['wko_mst_phone'];

$ast_mst_asset_no = $data['ast_mst_asset_no'];
$ast_mst_asset_shortdesc = $data['ast_mst_asset_shortdesc'];
$ast_mst_asset_group = $data['ast_mst_asset_group'];
$mst_war_work_area = $data['mst_war_work_area'];
$ast_mst_asset_locn = $data['ast_mst_asset_locn'];
$ast_mst_asset_lvl = $data['ast_mst_asset_lvl'];
$ast_mst_asset_code = $data['ast_mst_asset_code'];
$ast_mst_perm_id = $data['ast_mst_perm_id'];
$ast_det_cus_code = $data['ast_det_cus_code'];
$ast_mst_asset_status = $data['ast_mst_asset_status'];

$wko_mst_wo_no = $data['wko_mst_wo_no'];
$wko_mst_chg_costcenter = $data['wko_mst_chg_costcenter'];

$wko_det_laccount = $data['wko_det_laccount'];
$wko_det_caccount = $data['wko_det_caccount'];
$wko_det_maccount = $data['wko_det_maccount'];

$wko_mst_orig_priority = $data['wko_mst_orig_priority'];
$wko_mst_plan_priority = $data['wko_mst_plan_priority'];
$wko_mst_org_date = $data['wko_mst_org_date'];
$wko_mst_due_date = $data['wko_mst_due_date'];
$wko_mst_status = $data['wko_mst_status'];
$wko_det_work_type = $data['wko_det_work_type'];
$wko_mst_flt_code = $data['wko_mst_flt_code'];
$wko_mst_descs = $data['wko_mst_descs'];

$wko_det_assign_to = $data['wko_det_assign_to'];
$cnt_mst_numbering = $data['cnt_mst_numbering'];
$dvc_id = $data['dvc_id'];

$LOGINID = $data['LOGINID'];

$wko_mst_project_id = $data['wko_mst_project_id'];
$wko_det_numeric1 = $data['wko_det_numeric1'];
$wko_det_numeric2 = $data['wko_det_numeric2'];
$wko_det_numeric3 = $data['wko_det_numeric3'];

$sql = "select 	wrk_typ_option, wrk_typ_prefix + SUBSTRING(CONVERT(VARCHAR(7), wrk_typ_counter + 1000000), 2, 6)  ls_doc_no 
		from 	wrk_typ (NOLOCK)  where wrk_typ_typ_cd ='" . $wko_det_work_type . "'";

$stmt = sqlsrv_query($conn, $sql);

if ($stmt === false)
{
    if (($errors = sqlsrv_errors()) != null)
    {
        foreach ($errors as $error)
        {

            file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
        }
    }
    sqlsrv_rollback($conn);
    sqlsrv_close($conn);

    $error_message = "(" . $now . ") Error selecting table (wrk_typ)";
    returnError($error_message);
}

do
{
    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
    {
        $wrk_typ_option = $row['wrk_typ_option'];
        $ls_doc_no = $row['ls_doc_no'];
        $wko_mst_wo_no = $ls_doc_no;

    }
}
while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);

if ($wrk_typ_option == "0")
{

    switch ($cnt_mst_numbering)
    {

        case 'A':

            $sql = "Select cnt_mst_prefix + SUBSTRING(CONVERT(VARCHAR(7), cnt_mst_counter + 1000000), 2, 6)  ls_doc_no
					From 	cnt_mst WITH (NOLOCK) 
					Where 	site_cd ='" . $site_cd . "'
					And 	cnt_mst_module_cd =  'WKO'";

            $stmt = sqlsrv_query($conn, $sql);

            if ($stmt === false)
            {
                if (($errors = sqlsrv_errors()) != null)
                {
                    foreach ($errors as $error)
                    {

                        file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
                    }
                }
                sqlsrv_rollback($conn);
                sqlsrv_close($conn);

                $error_message = "(" . $now . ") Error selecting table (cnt_mst)";
                returnError($error_message);
            }

            do
            {
                while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
                {

                    $ls_doc_no = $row['ls_doc_no'];
                    $wko_mst_wo_no = $ls_doc_no;

                }
            }
            while (sqlsrv_next_result($stmt));
            sqlsrv_free_stmt($stmt);

            $sql = "Select Count(*) ll_dup_cnt	From wko_mst (NOLOCK)
						Where site_cd = '" . $site_cd . "'
						And wko_mst_wo_no = '" . $ls_doc_no . "'";

            $stmt = sqlsrv_query($conn, $sql);

            if ($stmt === false)
            {
                if (($errors = sqlsrv_errors()) != null)
                {
                    foreach ($errors as $error)
                    {

                        file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
                    }
                }
                sqlsrv_rollback($conn);
                sqlsrv_close($conn);

                $error_message = "(" . $now . ") Error selecting table (wko_mst)";
                returnError($error_message);
            }

            do
            {
                while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
                {
                    $ll_dup_cnt = $row['ll_dup_cnt'];

                }
            }
            while (sqlsrv_next_result($stmt));
            sqlsrv_free_stmt($stmt);

            if ($ll_dup_cnt == 1)
            {
                $error_message = "Asset number is already exists";
                returnError($error_message);
                die(print_r(sqlsrv_errors() , true));
            }

            break;

        case 'M':

            $sql = "Select Count(*) ll_dup_cnt	From wko_mst (NOLOCK)
					Where site_cd = '" . $site_cd . "'
					And wko_mst_wo_no = '" . $wko_mst_wo_no . "'";

            $stmt = sqlsrv_query($conn, $sql);

            if ($stmt === false)
            {
                if (($errors = sqlsrv_errors()) != null)
                {
                    foreach ($errors as $error)
                    {

                        file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
                    }
                }
                sqlsrv_rollback($conn);
                sqlsrv_close($conn);

                $error_message = "(" . $now . ") Error selecting table (wko_mst)";
                returnError($error_message);
            }

            do
            {
                while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
                {
                    $ll_dup_cnt = $row['ll_dup_cnt'];

                }
            }
            while (sqlsrv_next_result($stmt));
            sqlsrv_free_stmt($stmt);

            if ($ll_dup_cnt == 1)
            {
                $error_message = "Asset number is already exists";
                returnError($error_message);
                die(print_r(sqlsrv_errors() , true));
            }

            break;
        }

    }

    $sql_insert_ast_mst = "INSERT INTO wko_mst 
		(	site_cd,						wko_mst_wo_no,					wko_mst_originator,			wko_mst_phone,				
			wko_mst_asset_level,			wko_mst_assetno,				wko_mst_flt_code,			wko_mst_status,				
			wko_mst_due_date,				wko_mst_descs,					wko_mst_project_id,			wko_mst_org_date,			
			wko_mst_chg_costcenter,			wko_mst_work_area,				wko_mst_asset_location,		wko_mst_asset_group_code,	
			wko_mst_orig_priority,			wko_mst_plan_priority,			wko_mst_type,				wko_mst_pm_grp,				
			wko_mst_ast_cod,				audit_user,						audit_date,					wko_mst_create_by,		
			wko_mst_create_date,			column1,						column2,					column3,					
			column4,						column5,						wko_mst_asset_status,  		mbl_audit_user,
			mbl_audit_date) 
			
VALUES 	(	?,								?,								?,							?,
			?,								?,								?,							?,
			?,								?,								?,						?,
			?,								?,								?,							?,
			?,								?,								?,						NULL,						
			?,								?,								GetDate(),					?,
			GetDate(),						NULL,							NULL,						NULL,						
			NULL,							NULL,							?,							?,
			GetDate()) ";

    $params_wko_mst = array(
        $site_cd,
        $wko_mst_wo_no,
        $wko_mst_originator,
        $wko_mst_phone,
        $ast_mst_asset_lvl,
        $ast_mst_asset_no,
        $wko_mst_flt_code,
        $wko_mst_status,
        $wko_mst_due_date,
        $wko_mst_descs,
		$wko_mst_project_id,
        $wko_mst_org_date,
        $wko_mst_chg_costcenter,
        $mst_war_work_area,
        $ast_mst_asset_locn,
        $ast_mst_asset_group,
        $wko_mst_orig_priority,
        $wko_mst_plan_priority,
        'C',
        $ast_mst_asset_code,
        $LOGINID,
        $LOGINID,
        $ast_mst_asset_status,
		$LOGINID
    );

    $stmt_wko_mst = sqlsrv_query($conn, $sql_insert_ast_mst, $params_wko_mst);

    if ($stmt_wko_mst === false)
    {
        if (($errors = sqlsrv_errors()) != null)
        {
            foreach ($errors as $error)
            {

                file_put_contents($file_name, $now . "\r\n" . $sql_insert_ast_mst . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
            }
        }
        sqlsrv_rollback($conn);
        sqlsrv_close($conn);

        $error_message = "(" . $now . ") Error inserting table (wko_mst)";
        returnError($error_message);
    }
    sqlsrv_free_stmt($stmt_wko_mst);

    $sql = "SELECT Rowid From wko_mst (NOLOCK) WHERE site_cd = '" . $site_cd . "' AND wko_mst_wo_no = '" . $wko_mst_wo_no . "'";

    $stmt = sqlsrv_query($conn, $sql);

    if ($stmt === false)
    {
        if (($errors = sqlsrv_errors()) != null)
        {
            foreach ($errors as $error)
            {

                file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
            }
        }
        sqlsrv_rollback($conn);
        sqlsrv_close($conn);

        $error_message = "(" . $now . ") Error selecting table (wko_mst)";
        returnError($error_message);
    }
    do
    {
        while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
        {

            $ROW_ID = $row['Rowid'];

        }
    }
    while (sqlsrv_next_result($stmt));

    $sql = " select emp_det_wo_approval_limit from emp_det (NOLOCK) ,emp_mst (NOLOCK) 
		where emp_det.site_cd = emp_mst.site_cd 
		and emp_det.mst_RowID = emp_mst.RowID 
		and emp_mst_empl_id ='" . $EmpID . "'";

    $stmt = sqlsrv_query($conn, $sql);

    if ($stmt === false)
    {
        if (($errors = sqlsrv_errors()) != null)
        {
            foreach ($errors as $error)
            {

                file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
            }
        }
        sqlsrv_rollback($conn);
        sqlsrv_close($conn);

        $error_message = "(" . $now . ") Error selecting table (emp_mst, emp_det)";
        returnError($error_message);
    }
    do
    {
        while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
        {

            $emp_det_wo_approval_limit = $row['emp_det_wo_approval_limit'];

        }
    }
    while (sqlsrv_next_result($stmt));

    $sql_insert_ast_mst = "INSERT INTO wko_det 
		(		site_cd,								mst_RowID,						wko_det_wr_no,					wko_det_supv_id, 
				wko_det_planner,						wko_det_approver,				wko_det_perm_id,				wko_det_approved, 
				wko_det_safety,							wko_det_pm_grp,					wko_det_grp_code,				wko_det_task_id, 
				wko_det_pm_idno,						wko_det_route_id,				wko_det_work_type,				wko_det_work_locn, 
				wko_det_work_grp,						wko_det_exc_date,				wko_det_sched_date,				wko_det_cmpl_date, 
				wko_det_sc_date,						wko_det_ent_date,				wko_det_clo_date,				wko_det_act_code, 
				wko_det_critical_ratio,					wko_det_est_lab_cost,			wko_det_est_mtl_cost,			wko_det_est_con_cost,
				wko_det_lab_cost,						wko_det_mtl_cost,				wko_det_con_cost,				wko_det_support_rqmt, 
				wko_det_corr_action,					wko_det_chg_costcenter,			wko_det_crd_costcenter,			wko_det_laccount, 
				wko_det_maccount,						wko_det_caccount,				wko_det_work_class,				wko_det_finance_clo, 
				wko_det_budget,							wko_det_wo_limit,				wko_det_fund_src,				wko_det_wo_open,
				wko_det_dispatch,						wko_det_current_location,		wko_det_cause_code,				wko_det_wo_print, 
				wko_det_on_dispatch_q,					wko_det_check_out,				wko_det_assign_to,				wko_det_parent_wo,				
				wko_det_varchar1,						wko_det_varchar2,				wko_det_varchar3,				wko_det_varchar4, 
				wko_det_varchar5,						wko_det_varchar6,				wko_det_varchar7,				wko_det_varchar8, 
				wko_det_varchar9,						wko_det_varchar10,				wko_det_varchar11,				wko_det_varchar12,				
				wko_det_varchar13,						wko_det_varchar14, 				wko_det_varchar15,				wko_det_varchar16,	
				wko_det_varchar17,						wko_det_varchar18, 				wko_det_varchar19,				wko_det_varchar20,
				wko_det_varchar21,						wko_det_varchar22,				wko_det_varchar23,				wko_det_varchar24, 
				wko_det_varchar25,						wko_det_varchar26,				wko_det_varchar27,				wko_det_varchar28, 
				wko_det_varchar29,						wko_det_varchar30,				wko_det_varchar31,				wko_det_varchar32,				
				wko_det_varchar33,						wko_det_varchar34, 				wko_det_varchar35,				wko_det_varchar36,	
				wko_det_varchar37,						wko_det_varchar38, 				wko_det_varchar39,				wko_det_varchar40,
				wko_det_numeric1,						wko_det_numeric2, 				wko_det_numeric3,				wko_det_numeric4,
				wko_det_numeric5,						wko_det_datetime1,				wko_det_datetime2,				wko_det_datetime3,				
				wko_det_datetime4,						wko_det_datetime5, 				wko_det_note1,					wko_det_saccount,				
				wko_det_est_misc_cost,					wko_det_misc_cost, 				wko_det_customer_cd,			wko_det_temp_asset,				
				wko_det_contract_no,					wko_det_delay_cd, 				audit_user,						audit_date,						
				column1,								column2,						column3,						column4,						
				column5,								mbl_audit_user,					mbl_audit_date ) 
			
VALUES 	(		?,											?,								NULL,							NULL,
				NULL,										NULL,							?,								'0',
				'0',										NULL,							NULL,							NULL,
				NULL,										NULL,							?,								NULL,
				NULL,										NULL,							NULL,							NULL,
				NULL,										NULL,							NULL,							NULL,
				NULL,										'0.0000',						'0.0000',						'0.0000',
				'0.0000',									'0.0000',						'0.0000',						NULL,
				NULL,										NULL,							NULL,							?,
				?,											?,								NULL,							NULL,
				?,											'0.0000',						NULL,							'Y',
				NULL,										NULL,							NULL,							NULL,
				NULL,										NULL,							?,								NULL,
				'0', 										'0',							'0',							'0',     
				NULL,										NULL,							'0',							'0',
				'0',										'0',							'0',							'0',
				'0',										'0',							'0',							'0',
				'0',										'0',							'0',							'0',
				'0',										'0',							'0',							'0',
				'0',										'0',							'0',							'0',
				NULL,										'0',							'0',							'0',
				'0',										'0',							'0',							'0',
				'0',										NULL,							NULL,							NULL,
				
				?,											?,								?,								NULL,							
				NULL,										NULL,							NULL,							NULL,							
				NULL,										NULL,							NULL,							NULL,							
				'0.0000',									'0.0000',						?,								'0',							
				NULL,										NULL,							?,								GetDate(),						
				NULL,										NULL,							NULL,							NULL,							
				NULL,										?,								GetDate()) ";

    $params_wko_det = array(
        $site_cd,
        $ROW_ID,
        $ast_mst_perm_id,
        $wko_det_work_type,
        $wko_det_laccount,
        $wko_det_maccount,
        $wko_det_caccount,
        $emp_det_wo_approval_limit,
        $wko_det_assign_to,
		$wko_det_numeric1,
		$wko_det_numeric2,
		$wko_det_numeric3,
        $ast_det_cus_code,
        $LOGINID,
		$LOGINID
    );
    $stmt_wko_det = sqlsrv_query($conn, $sql_insert_ast_mst, $params_wko_det);

    if (!$stmt_wko_det)
    {
        $error_message = "Error insert table (INSERT Table wko_mst)";
        returnError($error_message);
        die(print_r(sqlsrv_errors() , true));
    }
    if ($stmt_wko_det === false)
    {
        if (($errors = sqlsrv_errors()) != null)
        {
            foreach ($errors as $error)
            {

                file_put_contents($file_name, $now . "\r\n" . $sql_insert_ast_mst . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
            }
        }
        sqlsrv_rollback($conn);
        sqlsrv_close($conn);

        $error_message = "(" . $now . ") Error inserting table (wko_mst)";
        returnError($error_message);
    }
    sqlsrv_free_stmt($stmt_wko_det);

    $sql_insert_wko_sts = "	INSERT wko_sts 
						(	site_cd ,					mst_RowID ,					wko_sts_wo_no ,					wko_sts_status , 
							wko_sts_originator ,		wko_sts_start_date ,		wko_sts_end_date ,				wko_sts_duration , 
							audit_user ,				audit_date,					mbl_audit_user,					mbl_audit_date ) 
				VALUES 
						(	?,							?,							?,								?,
							?,							GetDate(),					NULL,							NULL,
							?,							GetDate(),					?,								GetDate())";

    $params_wko_sts = array(
        $site_cd,
        $ROW_ID,
        $wko_mst_wo_no,
        $wko_mst_status,
        $wko_mst_originator,
        $LOGINID,
        $LOGINID
    );
    $stmt_wko_sts = sqlsrv_query($conn, $sql_insert_wko_sts, $params_wko_sts);

    if ($stmt_wko_sts === false)
    {
        if (($errors = sqlsrv_errors()) != null)
        {
            foreach ($errors as $error)
            {

                file_put_contents($file_name, $now . "\r\n" . $sql_insert_wko_sts . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
            }
        }
        sqlsrv_rollback($conn);
        sqlsrv_close($conn);

        $error_message = "(" . $now . ") Error inserting table (wko_sts)";
        returnError($error_message);
    }
    sqlsrv_free_stmt($stmt_wko_sts);

    //null to Values
    if (!empty($wko_det_assign_to))
    {

        // $title = "Work Order Assigned";
        // $body = "The work order " . $wko_mst_wo_no . " been assigned to you.";
        // $module = "Work Order";
        // $message_assign = "Asset No: " . $ast_mst_asset_no . " 
		// \r\nAsset Desc: " . $ast_mst_asset_shortdesc . "
		// \r\nWork Area: " . $ast_mst_asset_shortdesc . "
		// \r\nLocation: " . $ast_mst_asset_locn . "";

        $sql_wko_ls7_max = "select max_level = coalesce( MAX (wko_ls7_level ),0) + 1 from  wko_ls7 where site_cd =? and mst_RowID = ?";

        $params_wko_ls7_max = array(
            $site_cd,
            $ROW_ID
        );
        $stmt_wko_ls7_max = sqlsrv_query($conn, $sql_wko_ls7_max, $params_wko_ls7_max);

        if ($stmt_wko_ls7_max === false)
        {
            if (($errors = sqlsrv_errors()) != null)
            {
                foreach ($errors as $error)
                {

                    file_put_contents($file_name, $now . "\r\n" . $sql_wko_ls7_max . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
                }
            }
            sqlsrv_rollback($conn);
            sqlsrv_close($conn);

            $error_message = "(" . $now . ") Error selecting table (wko_ls7)";
            returnError($error_message);
        }
        do
        {

            while ($row = sqlsrv_fetch_array($stmt_wko_ls7_max, SQLSRV_FETCH_ASSOC))
            {

                $max_level = $row['max_level'];

            }

        }
        while (sqlsrv_next_result($stmt_wko_ls7_max));
        //sqlsrv_free_stmt( $stmt_wko_ls7_max);
        

        $sql_insert_wko_ls7 = "	INSERT wko_ls7 
								(	site_cd ,					mst_rowid ,					wko_ls7_level ,					wko_ls7_emp_id , 
									wko_ls7_due_days ,			wko_ls7_wo_org_date ,		wko_ls7_due_date ,				wko_ls7_total_days , 
									audit_user ,				audit_date,					mbl_audit_user,					mbl_audit_date) 
						VALUES 
								(	?,							?,							?,								?,
									'1',						GetDate(),					NULL,							'1',
									?,							GetDate(),					?,								GetDate())";

        $params_insert_wko_ls7 = array(
            $site_cd,
            $ROW_ID,
            $max_level,
            $wko_det_assign_to,
            $LOGINID,
			$LOGINID
        );
        $stmt_insert_wko_ls7 = sqlsrv_query($conn, $sql_insert_wko_ls7, $params_insert_wko_ls7);

        if ($stmt_insert_wko_ls7 === false)
        {
            if (($errors = sqlsrv_errors()) != null)
            {
                foreach ($errors as $error)
                {

                    file_put_contents($file_name, $now . "\r\n" . $sql_insert_wko_ls7 . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
                }
            }
            sqlsrv_rollback($conn);
            sqlsrv_close($conn);

            $error_message = "(" . $now . ") Error inserting table (wko_ls7)";
            returnError($error_message);
        }
        sqlsrv_free_stmt($stmt_insert_wko_ls7);

        // $insert_ntf1 = insert_notification_log($site_cd, $EmpID, $wko_det_assign_to, $wko_mst_wo_no, $title, $body, $message_assign, $module, $dvc_id, $LOGINID);

        // foreach ($insert_ntf1 as $x => $val)
        // {

            // $row = $x = $val["row"];
            // $insert_ntf = $x = $val["insert_ntf"];

            //echo '<pre>'; print_r($row); echo '</pre>';
            //echo '<pre>'; print_r($insert_ntf); echo '</pre>';
            

            
        // }

        //Get New Value Assignto Online Token
        //$tkn_token_1 = get_online($wko_det_assign_to, $site_cd);

        //echo '<pre>'; print_r($tkn_token_2); echo '</pre>';
        //Notify token user
        // if (sizeof($tkn_token_1) > 0)
        // {

            // foreach ($tkn_token_1 as $x => $val)
            // {
                // $tokenlist = $x = $val["token"];
                // $RowID = $x = $val["RowID"];
                // $tkn_site = $x = $val["tkn_site"];

                //echo '<pre>'; print_r($tkn_site); echo '</pre>';
                //echo '<pre>'; print_r($RowID); echo '</pre>';
                // push_notification_android($tokenlist, 'The work order ' . $wko_mst_wo_no . ' been assigned to you', "Work Order Assigned(" . $site_cd . ")", $site_cd, $tokenlist, $RowID, $row, $tkn_site, $LOGINID);

            // }

        // }

    }

    if ($stmt_wko_mst && $stmt_wko_det && $stmt_wko_sts)
    {

        if ($wrk_typ_option == "0")
        {

            $sql = "UPDATE 	cnt_mst WITH (UPDLOCK)
				SET 	cnt_mst_counter = cnt_mst_counter + 1
				WHERE 	site_cd ='" . $site_cd . "' 
				AND 	cnt_mst_module_cd = 'WKO'";

            $stmt = sqlsrv_query($conn, $sql);

            if ($stmt === false)
            {
                if (($errors = sqlsrv_errors()) != null)
                {
                    foreach ($errors as $error)
                    {

                        file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
                    }
                }
                sqlsrv_rollback($conn);
                sqlsrv_close($conn);

                $error_message = "(" . $now . ") Error updating table (cnt_mst)";
                returnError($error_message);
            }
            sqlsrv_free_stmt($stmt);

        }
        else
        {

            $sql = "UPDATE 	wrk_typ WITH (UPDLOCK)
			SET 	wrk_typ_counter = wrk_typ_counter + 1
			WHERE 	site_cd ='" . $site_cd . "' 
			AND 	wrk_typ_typ_cd = '" . $wko_det_work_type . "'";

            $stmt = sqlsrv_query($conn, $sql);

            if ($stmt === false)
            {
                if (($errors = sqlsrv_errors()) != null)
                {
                    foreach ($errors as $error)
                    {

                        file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
                    }
                }
                sqlsrv_rollback($conn);
                sqlsrv_close($conn);

                $error_message = "(" . $now . ") Error updating table (wrk_typ)";
                returnError($error_message);
            }
            sqlsrv_free_stmt($stmt);

        }

        if (!empty($wko_det_assign_to))
        {
			
			sqlsrv_commit($conn);
			sqlsrv_close($conn);
			returnData($ROW_ID, $wko_mst_wo_no);
            // if ($insert_ntf)
            // {
                // sqlsrv_commit($conn);
                // sqlsrv_close($conn);
                // returnData($ROW_ID, $wko_mst_wo_no);
            // }
            // else
            // {
                // sqlsrv_rollback($conn);
                // $error_message = "Transaction rolled back.<br />";
                // returnError($error_message);
            // }
        }
        else
        {
            sqlsrv_commit($conn);
            sqlsrv_close($conn);
            returnData($ROW_ID, $wko_mst_wo_no);
        }

    }
    else
    {
        sqlsrv_rollback($conn);
        $error_message = "Transaction rolled back.<br />";
        returnError($error_message);
    }

    function returnData($ROW_ID, $wko_mst_wo_no)
    {
        $returnData = array(
            'status' => 'SUCCESS',
            'ROW_ID' => $ROW_ID,
            'WorkOrderno' => $wko_mst_wo_no,
            'message' => 'Work Order No: ' . $wko_mst_wo_no . ' created successfully'
        );
        echo json_encode($returnData);
    }

    function returnError($error_message)
    {

        $returnData = array(
            'status' => 'ERROR',
            'message' => $error_message
        );
        echo json_encode($returnData);
        exit();
    }

?>
