<?php
	session_start();
    include_once"includes/conn.php";
    include_once"functions/Success.php";
    include_once"functions/Error.php";

    if (isset($_POST['Submit'])) {
    	$AD1 = mysqli_real_escape_string($conn,strip_tags($_POST['AD1']));
    	$TN1 = mysqli_real_escape_string($conn,strip_tags($_POST['TN1']));
    	$Origin = mysqli_real_escape_string($conn,strip_tags($_POST['Origin']));
    	$DES = mysqli_real_escape_string($conn,strip_tags($_POST['DES']));
    	$Comment = mysqli_real_escape_string($conn,strip_tags($_POST['Comment']));
    	$Status = mysqli_real_escape_string($conn,strip_tags($_POST['Status']));
        $held = mysqli_real_escape_string($conn,strip_tags($_POST['Held']));

    	/*echo $AD1.$TN1.$Origin.$DES.$Comment.$Status;*/
       
    	if (empty($AD1) || empty($TN1) || empty($Origin) || empty($DES) || empty($Comment) || empty($Status)  ) {
    		$_SESSION['er1'] = 'emp';
			EmptyField2($conn);
			header('Location: Add-Shipment.php?ss=1');
    	}else{
    		$sql0 = "SELECT * FROM details WHERE TrackNum = '$TN1' ";
            $result0 = mysqli_query($conn, $sql0);
            if (mysqli_num_rows($result0)>0) {
                $rows0 = mysqli_fetch_assoc($result0);
            $Tcode = $rows0['TrackNum'];
            $FOrigin = $rows0['Origin'];
            $FLocation = $rows0['Location'];
            $FStatus = $rows0['Held'];
            $FComment = $rows0['Comment'];
                
            if ($TN1 !== $Tcode) {
                $_SESSION['er1'] = 'tce1';
                CodeExist1($conn);
                header('Location: Add-Shipment.php');
            }else{
                // $sql1 = "UPDATE details SET Origin = '$Origin', Location = '$DES', Comment = '$Comment', ART = '$AD1', SS = '$Status', Held = '$held' WHERE TrackNum = '$TN1' ";
                // $res1 = mysqli_query($conn, $sql1);
                
                $sql = "INSERT into tracking_history (origin,location,status,comment,Track_num) values ('$FOrigin','$FLocation','$FStatus','$FComment','$Tcode');";
                $sql1 = "UPDATE details SET Origin = '$Origin', Location = '$DES', Comment = '$Comment', ART = '$AD1', SS = '$Status', Held = '$held' WHERE TrackNum = '$TN1'";
                $res1 = mysqli_query($conn, $sql1) or die($conn);
                $res2 = mysqli_query($conn, $sql) or die($conn);

                if ($res1 && $res2) {
                   // $_SESSION['suc1'] = 'updated';
                    header('Location: Add-Shipment.php?tt=1');
                }
                
            }
            }
    		
    	}
    }
	
?>