<link rel="stylesheet" href="https://getbootstrap.com/docs/4.3/dist/css/bootstrap.min.css">

<div style="width: 60%; margin: 0 auto; margin-top: 100px;">
    <h2>Ringba Lead Form</h2><br><br>
    <?php
    $path = 'https://errands-form.dev/digitalwim/ringba_calleridzip.php';
    if ($_SERVER['HTTP_HOST'] != 'localhost') {
        $path = 'https://digitalwim.com/forms/ringba_calleridzip.php';
    }
    if ($_POST) {

        include "MySqliDb.php";
        if ($_SERVER['HTTP_HOST'] == 'errands-form.dev') {
            // DB credentials.
            define('DB_HOST', '127.0.0.1');
            define('DB_USER', 'root');
            define('DB_PASS', 'ServBay.dev');
            define('DB_NAME', 'digitalwim22_ringba_callerzip');
        } else {
            // DB credentials.
            define('DB_HOST', 'localhost');
            define('DB_USER', 'digitalwim22_ringba_callerzip');
            define('DB_PASS', 'digitalwim22_ringba_callerzip');
            define('DB_NAME', 'digitalwim22_ringba_callerzip');
        }
        $db = new db(DB_HOST, DB_USER, DB_PASS, DB_NAME);

        //header('Content-Type: application/json; charset=utf-8');
        $POSTDATA = $_POST;
        //$POSTDATA['birthdate'] = date("Y-m-d", strtotime($POSTDATA['birthdate']));
        $phone = $POSTDATA['phone_number'];
        unset($POSTDATA['phone_number']);

        $QueryString = http_build_query($POSTDATA);
        $url = 'https://rtb.ringba.com/v1/production/3217093bac5d4a699a1d7403414d746a.json?CID=' . $phone . '&exposecallerid=yes&zipcode=' . $POSTDATA['zipcode'] . '&';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $response = curl_exec($ch);
        $error = curl_error($ch);
        $errno = curl_errno($ch);

        if (is_resource($ch)) {
            curl_close($ch);
        }

        if (0 !== $errno) {
            throw new RuntimeException($error, $errno);
        }
        //echo $response;
        $jsonRes = json_decode($response, true);

        // echo "<pre>";
        // print_r($jsonRes) . "";
        // exit;

        if (isset($jsonRes['bidId']) && $jsonRes['bidId'] != '' && !isset($jsonRes['rejectReason'])) {
            $Terms = [];
            foreach ($jsonRes['bidTerms'] as $TRM) {
                if (isset($TRM['callMinDuration'])) {
                    $callMinDuration = $TRM['callMinDuration'];
                    $Terms[] = 'Min call duration ' . $callMinDuration . ' seconds';
                } else {
                    $Terms[] = $TRM['description'];
                }
            }
            $Warnings = [];
            foreach ($jsonRes['warnings'] as $TRM) {
                $Warnings[] = $TRM['description'];
            }
    ?>
            <div class="nowrap">
                <div class="alert alert-success" role="alert">Your request Has been submitted...</div>
                <h4>Response Data: <small style="float: right"><a href="<?= $path ?>">Click here for New
                            Request</a></small></h4>
                <table class="table table-bordered ">
                    <tr>
                        <th width="140">BID ID</th>
                        <td><?= $jsonRes['bidId'] ?></td>
                        <th width="120">BID Amount</th>
                        <td><?= $jsonRes['bidAmount'] ?></td>
                    </tr>
                    <tr>
                        <th>Expire In Seconds</th>
                        <td><?= $jsonRes['expireInSeconds'] ?></td>
                        <th>Phone Number</th>
                        <td><?= $jsonRes['phoneNumberNoPlus'] ?></td>
                    </tr>
                    <tr>
                        <th>Terms</th>
                        <td colspan="3"><?= implode(". <br>", $Terms) ?></td>
                    </tr>
                    <tr>
                        <th>Warnings</th>
                        <td colspan="3"><?= implode(". <br>", $Warnings) ?></td>
                    </tr>
                </table>
            </div>
    <?php

            $SQL = "INSERT INTO `records` SET 
                    `BID_ID` = '" . $jsonRes['bidId'] . "',
                    `BID_Amount` = '" . $jsonRes['bidAmount'] . "',
                    `BID_ExpireSeconds` = '" . $jsonRes['expireInSeconds'] . "',
                    `BID_PhoneNumber` = '" . $jsonRes['phoneNumberNoPlus'] . "',
                    `BID_SipAddress` = '" . $jsonRes['sipAddress'] . "',
                    `BID_Terms` = '" . implode(". <br>", $Terms) . "',
                    `BID_Warnings` = '" . implode(". <br>", $Warnings) . "',                    
                    `phone_number` = '" . $_POST['phone_number'] . "'
                    ";
            $db->query($SQL);
        } else {
            $reason = (isset($jsonRes['rejectReason'])) ? "Reason: " . $jsonRes['rejectReason'] : '';
            $SQL = "INSERT INTO `records` SET 
                    `BID_ID` = '" . $jsonRes['bidId'] . "',
                    `BID_Amount` = '" . $jsonRes['bidAmount'] . "',
                    `BID_Warnings` = '" . $reason . "',                    
                    `phone_number` = '" . $_POST['phone_number'] . "'
                    ";
            $db->query($SQL);

            echo '<div class="alert alert-danger" role="alert">
            Your form request is NOT Accepted... <br>' . $reason . '
            <small style="float: right"><a href="' . $path . '">Click here for New Request</a></small>
            </div>';
        }
    }
    ?>

    <form action="" method="post" <?= (($_POST) ? 'style="display: none;"' : '') ?>>
        <h4>Please Fill the Form</h4>
        <div class="row">
            <?php
            $inputs = array();
            $inputs[] = array('name' => 'phone_number', 'required' => true, 'maxlength' => 10);
            $inputs[] = array('name' => 'zipcode', 'required' => true, 'maxlength' => 6);
            foreach ($inputs as $input) {
                $label = strtoupper(str_replace("_", " ", $input['name']));
                $type = 'text';
                if ($input['name'] == 'phone_number' || $input['name'] == 'zip' || $input['name'] == 'vehicle_year') {
                    $type = 'number';
                }

                switch ($input['name']) {

                    default;
                        $value = '';
                        $hide = ''; ?>
                        <div class="form-group col-md-6 <?= $hide ?>">
                            <label for="<?= ($input['name']) ?>"><?= $label ?></label>
                            <input type="<?= $type ?>" class="form-control" id="<?= ($input['name']) ?>"
                                name="<?= ($input['name']) ?>"
                                <?= ((isset($input['required']) && $input['required']) ? 'required' : '') ?>
                                <?= ((isset($input['maxlength'])) ? 'maxlength="' . $input['maxlength'] . '"' : '') ?>
                                value="<?= $value ?>" aria-describedby="<?= $label ?>Help" placeholder="Enter <?= $label ?>">
                        </div> <?php
                                break;
                        }
                    }
                                ?>
            <div class="col-md-12 text-right">
                <button type="submit" class="btn btn-primary mb-2">Confirm Submit</button>
            </div>
        </div>
    </form>
</div>