<?php
require_once ('config.php');
require_once ('f_logging.php');
//require_once('f_update_budget.php');
$error_message;
$valid = true;
$now = date("Ymdhisa");
$file_name = __DIR__ . "\mobile_log\_insert_time_card.log";

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

$time_card_nos;

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

f_logging($json,"off_insert_time_card",$sync_url,$LOGINID,$sync_step,$sync_time,$site_cd);
	

foreach ($result->Header as $Header)
{

    $site_cd 		= $Header->site_cd;
    $wko_mst_wo_no 	= $Header->wko_mst_wo_no;
    $mst_RowID 		= $Header->mst_RowID;
    $assetno 		= $Header->assetno;
    $originator 	= $Header->originator;
    $craft 			= $Header->craft;
    $hourtype 		= $Header->hourtype;
    $total_hrs 		= $Header->total_hrs;
    $rate 			= $Header->rate;
    $multiplier 	= $Header->multiplier;
    $adder 			= $Header->adder;
    $act_cost 		= $Header->act_cost;
    $chg_costcenter = $Header->chg_costcenter;
    $chg_account 	= $Header->chg_account;
    $time_card_no 	= $Header->time_card_no;
    $datetime1 		= $Header->datetime1;
    $audit_user 	= $Header->audit_user;
    $audit_date 	= $Header->audit_date;
    $datetime2 		= $Header->datetime2;
    $RowId 			= $Header->RowId;

    $time_card_nos 	= "";

	
	$Actual_hour 	= $total_hrs / (1000 * 60 * 60);
	$Actual_hour 	= number_format($Actual_hour, 2);


    if (empty($datetime2))
    {
        // No time card
        
    }
    Else
    {

        $sql = "SELECT 	ls_doc_no = cnt_mst_prefix + SUBSTRING(CONVERT(VARCHAR(7), cnt_mst_counter + 1000000), 2, 6)
				FROM 	cnt_mst WITH (NOLOCK)
				WHERE 	site_cd ='" . $site_cd . "'
				AND 	cnt_mst_module_cd =  'TM'
				
				UPDATE 	cnt_mst WITH (UPDLOCK)
				SET 	cnt_mst_counter = cnt_mst_counter + 1
				WHERE 	site_cd ='" . $site_cd . "' 
				AND 	cnt_mst_module_cd = 'TM'";

        $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 and updating table (cnt_mst)";
            returnError($error_message);
        }
        do
        {
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
            {

                $time_card_nos = $row['ls_doc_no'];
                //echo $time_card_nos;
                
            }
        }
        while (sqlsrv_next_result($stmt));

        $sql_insert_tim_crd = "INSERT tim_crd 
	
		(	site_cd ,					tim_crd_card_no ,			tim_crd_date ,				tim_crd_empl_id ,			tim_crd_craft ,
			tim_crd_hours_type , 		tim_crd_hrs ,				tim_crd_rate ,				tim_crd_multiplier ,		tim_crd_adder ,				
			tim_crd_act_cost ,			tim_crd_wo, 				tim_crd_assetno ,			tim_crd_chg_costcenter ,	tim_crd_chg_account ,		
			tim_crd_crd_costcenter,		tim_crd_crd_account,		tim_crd_status , 			tim_crd_create_by ,			tim_crd_create_date ,	
			audit_user ,				audit_date,					mbl_audit_user,				mbl_audit_date,				tim_crd_datetime1,
			tim_crd_datetime2)
			
	VALUES ('".$site_cd."',				'".$time_card_nos."',		'".$datetime1."',			'".$originator."',			'".$craft."',				
			'".$hourtype."',			'".$Actual_hour."',			'".$rate."',				'".$multiplier."',			'".$adder."',				
			'".$act_cost."',			'".$wko_mst_wo_no."',		'".$assetno."',				'".$chg_costcenter."',		'".$chg_account."',		
			NULL,						NULL,						'P',						'".$audit_user."',			GetDate(),					
			'".$audit_user."',			GetDate(),					'".$LOGINID."',				GetDate(),					'".$datetime1."',
			'".$datetime2."')";

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

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

                    file_put_contents($file_name, $now . "\r\n" . $sql_insert_tim_crd . "\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 (tim_crd)";
            returnError($error_message);
        }
        sqlsrv_free_stmt($stmt);

        //$charge_valid = f_update_budget($datetime1, $chg_costcenter, $chg_account, "CHARGE", $act_cost, $conn, $audit_user);
        //$credit_valid = f_update_budget($datetime1, $itm_mst_crd_costcenter "CHARGE", $act_cost);
        $sql = "SELECT 	rowid 
			FROM 	ast_mst (NOLOCK) 
			WHERE 	site_cd =? 
			AND 	ast_mst_asset_no =? ";

        //echo $sql;
        $params = array(
            $site_cd,
            $assetno
        );

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

        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 (crf_mst)";
            returnError($error_message);
        }
        do
        {
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
            {

                $astrowid = $row['rowid'];

            }
        }
        while (sqlsrv_next_result($stmt));

        $sql1 = "UPDATE 	ast_det 
					SET 	ast_det_ltdlabcost =ast_det_ltdlabcost + '".$act_cost."',
							mbl_audit_user = '".$LOGINID."', 
							mbl_audit_date = GetDate () 					
				WHERE 	ast_det.site_cd = ? 
				AND 	ast_det.mst_rowid = ? ";

        //echo $sql;
        $params1 = array(
            $site_cd,
            $astrowid
        );
        $stmt1 = sqlsrv_query($conn, $sql1, $params1);

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

                    file_put_contents($file_name, $now . "\r\n" . $sql1 . "\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 (ast_det)";
            returnError($error_message);
        }
        sqlsrv_free_stmt($stmt1);

        $sql1 = "UPDATE wko_det 
				SET 	wko_det_lab_cost = wko_det_lab_cost + '".$act_cost."',
						mbl_audit_user = '".$LOGINID."', 
						mbl_audit_date = GetDate () 				
				FROM	wko_mst WITH (NOLOCK),
						wko_det WITH (NOLOCK)
				WHERE 	wko_mst.site_cd = wko_det.site_cd
				AND		wko_mst.RowID = wko_det.mst_RowID
				AND		wko_mst.site_cd = ? 
				AND 	wko_mst.wko_mst_wo_no = ? ";

        //echo $sql;
        $params1 = array(
            $site_cd,
            $wko_mst_wo_no
        );
        $stmt1 = sqlsrv_query($conn, $sql1, $params1);

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

                    file_put_contents($file_name, $now . "\r\n" . $sql1 . "\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 (wko_det)";
            returnError($error_message);
        }
        sqlsrv_free_stmt($stmt1);

    }

    if (empty($RowId))
    {

        if (empty($datetime2))
        {

            $datetimetest = 'Null';
        }
        else
        {
            $datetimetest = "'" . $datetime2 . "'";
        }

        $sql_insert_wko_ls8 = "INSERT wko_ls8 
				
					(	site_cd ,					mst_RowID,					wko_ls8_assetno,				wko_ls8_empl_id,				
						wko_ls8_craft,				wko_ls8_hours_type ,		wko_ls8_hrs ,					wko_ls8_rate ,
						wko_ls8_multiplier ,		wko_ls8_adder ,				wko_ls8_act_cost ,				wko_ls8_chg_costcenter ,
						wko_ls8_chg_account ,		wko_ls8_crd_costcenter ,	wko_ls8_crd_account ,			wko_ls8_time_card_no ,
						wko_ls8_datetime1 ,			audit_user ,				audit_date ,					wko_ls8_datetime2,
						mbl_audit_user,				mbl_audit_date) 
						
			VALUES 	(	'".$site_cd."',				'".$mst_RowID."',			'".$assetno."',					'".$originator."',		
						'".$craft."',				'".$hourtype."',			'".$Actual_hour."',				'".$rate."',							
						'".$multiplier."',			'".$adder."',				'".$act_cost."',				'".$chg_costcenter."',						
						'".$chg_account."',			Null,						Null,							'".$time_card_nos."',	
						'".$datetime1."',			'".$audit_user."',			'".$audit_date."',				".$datetimetest.",
						'".$LOGINID."',				'".$audit_date."')";

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

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

                    file_put_contents($file_name, $now . "\r\n" . $sql_insert_wko_ls8 . "\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_ls8)";
            returnError($error_message);
        }
        sqlsrv_free_stmt($stmt);

    }

    Else
    // RowID Not Empty
    
    {

        if (empty($datetime2))
        {

            $datetimetest = 'Null';
        }
        else
        {
            $datetimetest = "'" . $datetime2 . "'";;
        }

        $sql1 = "UPDATE wko_ls8  SET
							
						wko_ls8_assetno ='" . $assetno . "',		
						wko_ls8_empl_id='" . $originator . "',		
						wko_ls8_craft='" . $craft . "',			
						wko_ls8_hours_type='" . $hourtype . "',		
						wko_ls8_hrs='" . $Actual_hour . "',			
						wko_ls8_rate='" . $rate . "',			
						wko_ls8_multiplier='" . $multiplier . "',		
						wko_ls8_adder='" . $adder . "',			
						wko_ls8_act_cost='" . $act_cost . "',		  
						wko_ls8_chg_costcenter='" . $chg_costcenter . "', 
						wko_ls8_chg_account='" . $chg_account . "',	
						wko_ls8_datetime1='" . $datetime1 . "',		
						wko_ls8_datetime2=" . $datetimetest . ",
						wko_ls8_time_card_no ='" . $time_card_nos . "',
						mbl_audit_user = '".$LOGINID."', 
						mbl_audit_date = GetDate () 
						WHERE 	site_cd = ? 
						AND 	Rowid = ? ;	";

        //echo $sql;
        $params1 = array(
            $site_cd,
            $RowId
        );
        $stmt1 = sqlsrv_query($conn, $sql1, $params1);

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

                    file_put_contents($file_name, $now . "\r\n" . $sql1 . "\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 (wko_ls8)";
            returnError($error_message);
        }
        sqlsrv_free_stmt($stmt1);

    }

} /* 1st lopp */

if ($valid)
{
    returnData($json);
}

//sqlsrv_free_stmt( $stmt);
sqlsrv_close($conn);

function returnData($json)
{

    $returnData = array(
        'status' => 'SUCCESS',
        'message' => 'Time Card Saved Successfully'
    );

    echo json_encode($returnData);
}

function returnError($error_message)
{
    $json = array();

    $returnData = array(
        'status' => 'Alert',
        'message' => $error_message,
        'data' => $json
    );

    echo json_encode($returnData);

    exit();
}

?>
