<?php
date_default_timezone_set("Australia/Hobart");

//error_reporting(E_ERROR | E_PARSE);
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');

require_once 'connection.php';
include_once "vendor/autoload.php";

$accessToken = getenv('HUBSPOT_TOKEN') ?: '';

$enquiry_date = date("l dS M \'y");
$drg = isset($_GET['drg']) ? $_GET['drg'] : '';

if (!empty($_GET['drg'])) {
    include "table.php";
}
?>
<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title><?php echo $drg ? "{$drg} - " : ''; ?>Payment Plan Tracker</title>
        <link rel="shortcut icon" href="images/blueprint.ico" type="image/x-icon">
        <link href="https://modulosdesign.com.au/internal/css/bootstrap.css" rel="stylesheet">
        <link href="https://modulosdesign.com.au/internal/css/blueprint.css" rel="stylesheet">
        <link href="https://modulosdesign.com.au/internal/css/print.css" rel="stylesheet" media="print">

        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">

        <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
        <script type="text/javascript" src="https://use.fontawesome.com/1e2844bb90.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-throttle-debounce/1.1/jquery.ba-throttle-debounce.min.js" integrity="sha512-JZSo0h5TONFYmyLMqp8k4oPhuo6yNk9mHM+FY50aBjpypfofqtEWsAgRDQm94ImLCzSaHeqNvYuD9382CEn2zw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    </head>

    <body>

        <nav class="navbar bg-brown-dark brown-light border-bottom border-body d-print-none" data-bs-theme="dark">
            <div class="container-fluid">
                <a class="navbar-brand brown-light" href="dashboard.php">
                    <img src="images/blueprint-logo-light.png" alt="Logo" width="30" height="24" class="d-inline-block align-text-top">
                    Modulos Design
                </a>
                <div class="ms-auto d-flex gap-2">
                    <a href="dashboard.php" class="btn btn-sm btn-outline-light"><i class="bi bi-grid-fill"></i> Dashboard</a>
                    <?php if (!empty($drg)): ?><a href="client-brief.php?drg=<?= (int)$drg ?>" class="btn btn-sm btn-outline-light"><i class="bi bi-person-fill"></i> Client Brief</a><?php endif; ?>
                </div>
            </div>
        </nav>

        <div class="container">

            <div class="row pt-2">
                <div class="col-sm-4 col-md-4 pt-3">
                    <img class="img-fluid logo pt-2" src="images/blueprint-full-logo-medium.png" alt="Blueprint Studio">
                </div>
                <div class="col-sm-4 col-md-4 m-auto text-center">
                    <h3 class="architect text-center">Job: <?php echo $drg; ?></h3>
                </div>
                <div class="col-sm-4 col-md-4 text-end pt-3">
                    <h2 class="fw-bold text-end mb-1">Client Onboarding Form</h2>
                    <h4 class="text-end mb-1">
                        <span class="fw-bold brown-two"><?php echo $enquiry_date; ?></span>
                    </h4>
                </div>
            </div>

            <div class="row">
                <div class="col-12">
                    <div class="row ">
                        <div class="col ">
                            <h4 class="fw-bold">Client Details</h4>
                        </div>
                    </div>
                    <div class="mb-1">
                        <div class="row ">
                            <div class="col-6 col-md-3">
                                <label for="firstname" class="form-label form-label-sm p-0 m-0">Clients Name</label>
                                <input type="text" class="form-control form-control-sm savable-text-field architect brown-four" name="firstname" id="firstname" tabindex="1" value="<?php echo $firstname; ?>" placeholder="First Name" autocomplete="given-name">
                            </div>
                            <div class="col-6 col-md-3">
                                <label for="lastname" class="form-label form-label-sm p-0 m-0"></label>
                                <input type="text" class="form-control form-control-sm savable-text-field architect brown-four" name="lastname" id="lastname" tabindex="2" value="<?php echo $lastname; ?>" placeholder="Last Name" autocomplete="family-name">
                            </div>
                            <div class="col-12 col-md-6">
                                <label for="joint_name" class="form-label form-label-sm p-0 m-0">T/As - Joint Names</label>
                                <input type="text" class="form-control form-control-sm savable-text-field architect brown-three" name="joint_name" id="joint_name" value="<?php echo $joint_name; ?>" tabindex="3">
                            </div>
                        </div>
                    </div>

                    <div class="mb-1">
                        <label for="postal_address" class="form-label form-label-sm p-0 m-0">Clients Postal Address</label>
                        <input type="text" class="form-control form-control-sm fw-bold savable-text-field architect brown-three map-autocomplete" id="postal_address" name="postal_address" value="<?php echo $postal_address; ?>" onFocus="geolocate(this)" tabindex="4" autocomplete="on">
                    </div>
                    <div class="mb-1">
                        <div class="row ">
                            <div class="col-md-6">
                                <label for="phoneNumber" class="form-label form-label-sm p-0 m-0">Clients Mobile</label>
                                <input type="phone" class="form-control form-control-sm savable-text-field architect brown-three" minlength="12" id="phoneNumber" name="client_mobile" value="<?php echo $client_mobile; ?>"  required onkeyup="check(); return false;" tabindex="5" autocomplete="tel">
                            </div>
                            <div class="col-md-6">
                                <label for="client_email" class="form-label form-label-sm p-0 m-0">Email address</label>
                                <input type="email" class="form-control form-control-sm savable-text-field architect brown-three" name="client_email" id="client_email" value="<?php echo $client_email; ?>" tabindex="6" autocomplete="email">
                            </div>
                        </div>
                    </div>
                </div>

				<div class="row mt-3">
					<div class="col-md-2">Item</div>
					<div class="col-md-7">Description</div>
					<div class="col">Price</div>
				</div>
                <hr>
            	<?php
            		$checkRecord = mysqli_query($con, "SELECT * FROM `progress_payments` WHERE `drg` = '{$drg}' " );
            		$rowcount = mysqli_num_rows($checkRecord);
            		$result = mysqli_query($con, "SELECT *, @curRow := @curRow + 1 AS position FROM `progress_payments` JOIN (SELECT @curRow := 0) r WHERE `drg` = '{$drg}' ");
            		if (!$result) {
            		printf("Error: %s\n", mysqli_error($con));
            		exit();
                    }
                    while ($row = mysqli_fetch_array($result)) {
                    	echo "<div class='mb-1 row justify-content-start'>";
                        echo "<label for='description' class='col-1 col-form-label'>" . $row['position'] . "</label>";
                        echo "<input type='hidden' id='progress' v-model='progress' value='" . $row['position'] . "'>";
                        echo "<div class='col-sm-7'>";
                        echo "<input type='text' class='form-control' id='description' v-model='description' value='" . $row['description'] . "' disabled>";
                        echo "</div>";
                    	echo "<div class='col-sm-2'>";
                        echo "<input type='text' class='form-control' id='paid' v-model='paid' value='" . $row['paid'] . "' disabled>";
                        echo "</div>";
                        echo "<div class='col-sm-2'>";
                        echo "<input type='currency' class='form-control' id='value' v-model='value' value='" . $row['value'] . "' disabled>";
                        echo "</div>";
                    	echo "</div>";
        			}
            	?>
				<div id="progress_payments">
				</div>
            
				<div class="row justify-content-end">
					<div class="">
						<button id="btn" class="btn btn-sm btn-block bg-brown-three brown-five col-3">Add Item</button>
					</div>
				</div>
				
            </div>
        </div>
        

		<script>
            var count= <?php echo $rowcount + 1; ?>;
            $("#btn").click(function(){

                $("#progress_payments").append(addNewRow(count));
                count++;

            });

            function addNewRow(count){
                var newrow='<div class="mb-1 row justify-content-start">'+
                    '<label for="description" class="col-1 col-form-label">'+count+'</label>'+
					'<input type="hidden" id="progress" v-model="progress" value="+count+">'+
                    '<div class="col-sm-9">'+
                    '<input type="text" class="form-control" id="description" v-model="description">'+
                    '</div>'+
                    '<div class="col-sm-2">'+
                    '<input type="currency" class="form-control" id="value" v-model="value">'+
                    '</div>'+    
                    '</div>';
                return newrow;
            }
			
			var currencyInput = document.querySelector('input[type="currency"]')
			var currency = 'AUD' // https://www.currency-iso.org/dam/downloads/lists/list_one.xml

			 // format inital value
			onBlur({target:currencyInput})

			// bind event listeners
			currencyInput.addEventListener('focus', onFocus)
			currencyInput.addEventListener('blur', onBlur)


			function localStringToNumber( s ){
			  return Number(String(s).replace(/[^0-9.,-]+/g,""))
			}

			function onFocus(e){
			  var value = e.target.value;
			  e.target.value = value ? localStringToNumber(value) : ''
			}

			function onBlur(e){
			  var value = e.target.value

			  var options = {
				  maximumFractionDigits : 2,
				  currency              : currency,
				  style                 : "currency",
				  currencyDisplay       : "symbol"
			  }
			  
			  e.target.value = (value || value === 0) 
				? localStringToNumber(value).toLocaleString(undefined, options)
				: ''
			}
        </script>


        <hr>

        <footer class="footer">
            <p class="text-center">&copy; <?php echo date('Y'); ?> - Modulos Design</p>
        </footer>

        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-HwwvtgBNo3bZJJLYd8oVXjrBZt8cqVSpeBNS5n7C8IVInixGAoxmnlMuBnhbgrkm" crossorigin="anonymous"></script>
        <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB-QceOYrDe9otynMmQ9iNF3yEZzbpsanM&libraries=places&callback=initAutocomplete" async defer></script>
        <script src="https://cdn.jsdelivr.net/npm/signature_pad@4.0.0/dist/signature_pad.umd.min.js"></script>
        <script src="js/signature.js" ></script>
        <script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
        <script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>

    </body>
</html>