<?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']) ? (int)$_GET['drg'] : 0;

$payment_no = isset($_GET['pn']) ? $_GET['pn'] : '';


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>Payment Request Form</title>
        <link rel="shortcut icon" href="images/blueprint.ico" type="image/x-icon">
        <link href="css/bootstrap.css" rel="stylesheet">
        <link href="css/blueprint.css" rel="stylesheet">
        <link href="css/print.css" rel="stylesheet" media="print">

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

        <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></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>

            <script type="text/javascript" src="https://sandbox.web.squarecdn.com/v1/square.js" ></script>
            <script>
                const appId = '{sandbox-sq0idb-ZUSNynWbeVYrFo3hjZFIQg}';
                const locationId = '{LYQ568H0H05Q2}';

                async function initializeCard(payments) {
                    const card = await payments.card();
                    await card.attach('#card-container');

                    return card;
                }

                async function createPayment(token, verificationToken) {
                    const body = JSON.stringify({
                        locationId,
                        sourceId: token,
                        verificationToken,
                        idempotencyKey: window.crypto.randomUUID(),
                    });

                    const paymentResponse = await fetch('/payment', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body,
                    });

                    if (paymentResponse.ok) {
                        return paymentResponse.json();
                    }

                    const errorBody = await paymentResponse.text();
                    throw new Error(errorBody);
                }

                async function tokenize(paymentMethod) {
                    const tokenResult = await paymentMethod.tokenize();
                    if (tokenResult.status === 'OK') {
                        return tokenResult.token;
                    } else {
                        let errorMessage = `Tokenization failed with status: ${tokenResult.status}`;
                        if (tokenResult.errors) {
                            errorMessage += ` and errors: ${JSON.stringify(
                                tokenResult.errors,
                            )}`;
                        }

                        throw new Error(errorMessage);
                    }
                }

                // Required in SCA Mandated Regions: Learn more at https://developer.squareup.com/docs/sca-overview
                async function verifyBuyer(payments, token) {
                    const verificationDetails = {
                        amount: '100.00',
                        billingContact: {
                            givenName: '<?php echo $firstname; ?>',
                            familyName: '<?php echo $lastname; ?>',
                            email: '<?php echo $client_email; ?>',
                            phone: '<?php echo $client_mobile; ?>',
                            addressLines: ['<?php echo $postal_address_street; ?>'],
                            city: '<?php echo $postal_address_town; ?>',
                            state: '<?php echo $postal_address_state; ?>',
                            countryCode: 'AU',
                        },
                        currencyCode: 'AUD',
                        intent: 'CHARGE',
                    };

                    const verificationResults = await payments.verifyBuyer(
                        token,
                        verificationDetails,
                    );
                    return verificationResults.token;
                }

                // status is either SUCCESS or FAILURE;
                function displayPaymentResults(status) {
                    const statusContainer = document.getElementById(
                        'payment-status-container',
                    );
                    if (status === 'SUCCESS') {
                        statusContainer.classList.remove('is-failure');
                        statusContainer.classList.add('is-success');
                    } else {
                        statusContainer.classList.remove('is-success');
                        statusContainer.classList.add('is-failure');
                    }

                    statusContainer.style.visibility = 'visible';
                }

                document.addEventListener('DOMContentLoaded', async function () {
                    if (!window.Square) {
                        throw new Error('Square.js failed to load properly');
                    }

                    let payments;
                    try {
                        payments = window.Square.payments(appId, locationId);
                    } catch {
                        const statusContainer = document.getElementById(
                        'payment-status-container',
                        );
                    statusContainer.className = 'missing-credentials';
                    statusContainer.style.visibility = 'visible';
                    return;
                }

                                          let card;
                                          try {
                                          card = await initializeCard(payments);
                } catch (e) {
                    console.error('Initializing Card failed', e);
                    return;
                }

                async function handlePaymentMethodSubmission(event, card) {
                    event.preventDefault();

                    try {
                        // disable the submit button as we await tokenization and make a payment request.
                        cardButton.disabled = true;
                        const token = await tokenize(card);
                        const verificationToken = await verifyBuyer(payments, token);
                        const paymentResults = await createPayment(
                            token,
                            verificationToken,
                        );
                        displayPaymentResults('SUCCESS');

                        console.debug('Payment Success', paymentResults);
                    } catch (e) {
                        cardButton.disabled = false;
                        displayPaymentResults('FAILURE');
                        console.error(e.message);
                    }
                }

                const cardButton = document.getElementById('card-button');
                cardButton.addEventListener('click', async function (event) {
                    await handlePaymentMethodSubmission(event, card);
                });
                });
            </script>

            <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 architect brown-four" name="firstname" id="firstname" tabindex="1" value="<?php echo $firstname; ?>" readonly>
                            </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 architect brown-four" name="lastname" id="lastname" tabindex="2" value="<?php echo $lastname; ?>" readonly>
                            </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 architect brown-three" name="joint_name" id="joint_name" value="<?php echo $joint_name; ?>" readonly>
                            </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 architect brown-three map-autocomplete" id="postal_address" name="postal_address" value="<?php echo $postal_address; ?>" readonly>
                    </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 architect brown-three" minlength="12" id="phoneNumber" name="client_mobile" value="<?php echo $client_mobile; ?>"  readonly>
                            </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 architect brown-three" name="client_email" id="client_email" value="<?php echo $client_email; ?>" readonly>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <hr>
        
        	<div class="row mt-3">
                <div class="col-md-1">Item</div>
                <div class="col-md-5">Description</div>
            	<div class="col-md-2">Date Paid</div>
                <div class="col">Total</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)) {
                $pos  = (int)$row['position'];
                $desc = htmlspecialchars($row['description'], ENT_QUOTES, 'UTF-8');
                $paid = htmlspecialchars($row['paid'], ENT_QUOTES, 'UTF-8');
                $val  = htmlspecialchars($row['value'], ENT_QUOTES, 'UTF-8');
                echo "<div class='mb-1 row justify-content-start'>";
                echo "<label for='description' class='col-1 col-form-label'>" . $pos . "</label>";
                echo "<input type='hidden' id='progress' v-model='progress' value='" . $pos . "'>";
                echo "<div class='col-sm-5'>";
                echo "<input type='text' class='form-control form-control-sm' id='description' v-model='description' value='" . $desc . "' disabled>";
                echo "</div>";
                echo "<div class='col-sm-2'>";
                echo "<input type='text' class='form-control form-control-sm' id='paid' v-model='paid' value='" . $paid . "' disabled>";
                echo "</div>";
                echo "<div class='col-sm-2'>";
                echo "<input type='currency' class='form-control form-control-sm' id='value' v-model='value' value='" . $val . "' disabled>";
                echo "</div>";
                echo "<div class='col-sm-2'>";
                echo "<button class='btn btn-sm bg-brown-three brown-five' id='card-button' type='button' data-value='" . $val . "'>Pay $" . $val . "</button>";
                echo "</div>";
                echo "</div>";
            }
            ?>

            <hr>
        
        	<div class="row">
                <form id="payment-form">
                    <div id="card-container"></div>
                    <button class="btn btn-sm bg-brown-three brown-five" id="card-button" type="button">Pay $100.00</button>
                </form>
                <div id="payment-status-container"></div>	
            </div>

            <script type="text/javascript" src="https://sandbox.web.squarecdn.com/v1/square.js" ></script>
            <script>
                const appId = '{sandbox-sq0idb-ZUSNynWbeVYrFo3hjZFIQg}';
                const locationId = '{LYQ568H0H05Q2}';

                async function initializeCard(payments) {
                    const card = await payments.card();
                    await card.attach('#card-container');

                    return card;
                }

                async function createPayment(token, verificationToken) {
                    const body = JSON.stringify({
                        locationId,
                        sourceId: token,
                        verificationToken,
                        idempotencyKey: window.crypto.randomUUID(),
                    });

                    const paymentResponse = await fetch('/payment', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body,
                    });

                    if (paymentResponse.ok) {
                        return paymentResponse.json();
                    }

                    const errorBody = await paymentResponse.text();
                    throw new Error(errorBody);
                }

                async function tokenize(paymentMethod) {
                    const tokenResult = await paymentMethod.tokenize();
                    if (tokenResult.status === 'OK') {
                        return tokenResult.token;
                    } else {
                        let errorMessage = `Tokenization failed with status: ${tokenResult.status}`;
                        if (tokenResult.errors) {
                            errorMessage += ` and errors: ${JSON.stringify(
                                tokenResult.errors,
                            )}`;
                        }

                        throw new Error(errorMessage);
                    }
                }

                const amount = event.currentTarget.getAttribute('data-value');
                // Required in SCA Mandated Regions: Learn more at https://developer.squareup.com/docs/sca-overview
                async function verifyBuyer(payments, token) {
                    const verificationDetails = {
                        amount: amount,
                        billingContact: {
                            givenName: '<?php echo $firstname; ?>',
                            familyName: '<?php echo $lastname; ?>',
                            email: '<?php echo $client_email; ?>',
                            phone: '<?php echo $client_mobile; ?>',
                            addressLines: ['<?php echo $postal_address_street; ?>'],
                            city: '<?php echo $postal_address_town; ?>',
                            state: '<?php echo $postal_address_state; ?>',
                            countryCode: 'AU',
                        },
                        currencyCode: 'AUD',
                        intent: 'CHARGE',
                    };

                    const verificationResults = await payments.verifyBuyer(
                        token,
                        verificationDetails,
                    );
                    return verificationResults.token;
                }

                // status is either SUCCESS or FAILURE;
                function displayPaymentResults(status) {
                    const statusContainer = document.getElementById(
                        'payment-status-container',
                    );
                    if (status === 'SUCCESS') {
                        statusContainer.classList.remove('is-failure');
                        statusContainer.classList.add('is-success');
                    	// 
                    	// Add date payment success to data base
                    	// 
                    } else {
                        statusContainer.classList.remove('is-success');
                        statusContainer.classList.add('is-failure');
                    }

                    statusContainer.style.visibility = 'visible';
                }

                document.addEventListener('DOMContentLoaded', async function () {
                    if (!window.Square) {
                        throw new Error('Square.js failed to load properly');
                    }

                    let payments;
                    try {
                        payments = window.Square.payments(appId, locationId);
                    } catch {
                        const statusContainer = document.getElementById(
                        'payment-status-container',
                        );
                    statusContainer.className = 'missing-credentials';
                    statusContainer.style.visibility = 'visible';
                    return;
                }

                                          let card;
                                          try {
                                          card = await initializeCard(payments);
                } catch (e) {
                    console.error('Initializing Card failed', e);
                    return;
                }

                async function handlePaymentMethodSubmission(event, card) {
                    event.preventDefault();

                    try {
                        // disable the submit button as we await tokenization and make a payment request.
                        cardButton.disabled = true;
                        const token = await tokenize(card);
                        const verificationToken = await verifyBuyer(payments, token);
                        const paymentResults = await createPayment(
                            token,
                            verificationToken,
                        );
                        displayPaymentResults('SUCCESS');

                        console.debug('Payment Success', paymentResults);
                    } catch (e) {
                        cardButton.disabled = false;
                        displayPaymentResults('FAILURE');
                        console.error(e.message);
                    }
                }

                const cardButton = document.getElementById('card-button');
                cardButton.addEventListener('click', async function (event) {
                    await handlePaymentMethodSubmission(event, card);
                });
                });
            </script>

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

        </div>

        <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>