<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Anew Health Form</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div class="container mt-4">
        <h2 class="mb-3">Anew Health Form</h2>
        <?php
        if ($_POST) {
            include "MySqliDb.php";
            if ($_SERVER['HTTP_HOST'] == 'mcc-forms.dev') {
                // DB credentials.
                define('DB_HOST', '127.0.0.1');
                define('DB_USER', 'root');
                define('DB_PASS', 'ServBay.dev');
                define('DB_NAME', 'masterco_anewhealth');
            } else {
                // DB credentials.
                define('DB_HOST', 'localhost');
                define('DB_USER', 'gharmila_anewhealth');
                define('DB_PASS', 'gharmila_anewhealth');
                define('DB_NAME', 'gharmila_anewhealth');
            }
            $db = new db(DB_HOST, DB_USER, DB_PASS, DB_NAME);


            $stmt = $db->query("SELECT COUNT(`phone`) as cnt FROM `api_logs` WHERE `phone` = " . $_POST['Phone'] . ";");
            $record = $db->fetchAll($stmt);
            $found = $record[0]['cnt'];
            // print_r($record);
            // exit;

            if ($found == 0) {
                $curl = curl_init();
                $request = json_encode([
                    "Referral_Source_System"   => $_POST['Referral_Source_System'] ?? '',
                    "LeadSource"               => $_POST['LeadSource'] ?? '',
                    "RecordTypeId"             => $_POST['RecordTypeId'] ?? '',
                    "Referral_Source_Details"  => $_POST['Referral_Source_Details'] ?? '',
                    "List_Affiliate_Name"      => $_POST['List_Affiliate_Name'] ?? '',
                    "Web_Referrer_Company"     => $_POST['Web_Referrer_Company'] ?? '',
                    "Referrals" => [[
                        "FirstName"                 => $_POST['FirstName'] ?? '',
                        "LastName"                  => $_POST['LastName'] ?? '',
                        "Gender"                    => $_POST['Gender'] ?? '',
                        "Date_of_Birth"             => $_POST['Date_of_Birth'] ?? '',
                        "Status"                    => $_POST['Status'] ?? '',
                        "Phone"                     => $_POST['Phone'] ?? '',
                        "MobilePhone"               => $_POST['MobilePhone'] ?? '',
                        "Email"                     => $_POST['Email'] ?? '',
                        "Street"                    => $_POST['Street'] ?? '',
                        "City"                      => $_POST['City'] ?? '',
                        "State"                     => $_POST['State'] ?? '',
                        "PostalCode"                => $_POST['PostalCode'] ?? '',
                        "Episode_ID"                => $_POST['Episode_ID'] ?? '',
                        "Scheduling_Status"         => $_POST['Scheduling_Status'] ?? '',
                        "Primary_Insurance_Company" => $_POST['Primary_Insurance_Company'] ?? '',
                        "Total_Med_Count"           => $_POST['Total_Med_Count'] ?? '',
                        "Batch_Status"              => $_POST['Batch_Status'] ?? ''
                    ]]
                ]);

                curl_setopt_array($curl, array(
                    CURLOPT_URL => 'https://exactcarepharmacy.my.salesforce-sites.com/lead/services/apexrest/v1/LeadApi/',
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => '',
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 0,
                    CURLOPT_FOLLOWLOCATION => true,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => 'POST',
                    CURLOPT_POSTFIELDS => $request,

                    CURLOPT_HTTPHEADER => array(
                        'Content-Type: application/json',
                        'Cookie: BrowserId=6wfhlo87EfCC5FGSdQxaYg; CookieConsentPolicy=0:1; LSKey-c$CookieConsentPolicy=0:1'
                    ),
                ));

                $response = curl_exec($curl);
                if (curl_errno($curl)) {
                    // Show error message
                    echo 'cURL Error: ' . curl_error($curl);
                } else {
                    // Success
                    $result = json_decode($response, true);
                }
                // print_r($result);

                curl_close($curl);

                $SQL = "INSERT INTO `api_logs` (`api_request`, `api_response`,`firstname`, `lastname`,`phone`) VALUES ('" . $request . "', '" . $response . "','" . $_POST['FirstName'] . "', '" . $_POST['LastName']  . "','" . $_POST['Phone']  . "');";

                // $SQL = "INSERT INTO `api_logs` (`api_request`, `api_response`, `firstname`, `lastname`, `phone`)
                // SELECT * FROM (
                //     SELECT '" . $request . "', '" . $response . "', '" . $_POST['FirstName'] . "', '" . $_POST['LastName'] . "', '" . $_POST['Phone'] . "'
                // ) AS tmp
                // WHERE NOT EXISTS (
                //     SELECT 1 FROM `api_logs` WHERE `phone` = '" . $_POST['Phone'] . "'
                // ) LIMIT 1;";

                $db->query($SQL);

                if (count($result) == 1 && $result[0] == "Success! Leads are queued for creation.") {
                    echo '<div class="alert alert-success">Form submitted successfully!</div>';
                } else {
                    echo '<div class="alert alert-danger">Error submitting form: ' . implode(", ", $result) . '</div>';
                }
            } else {
                echo '<div class="alert alert-danger">Already Processed...</div>';
            }

            echo '
            <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
            <script>
                $(document).ready(function() {
                    setTimeout(function() {
                        //location.reload();
                    }, 2000); // 2 seconds
                });
            </script> ';
        }



        ?>
        <form method="post" action="">
            <input type="hidden" class="form-control" name="Referral_Source_System" value="W2L PROXY">
            <input type="hidden" class="form-control" name="LeadSource" value="Phone">
            <input type="hidden" class="form-control" name="RecordTypeId" value="012390000006DX3AAM">
            <input type="hidden" class="form-control" name="Referral_Source_Details" value="Warm Transfer">
            <input type="hidden" class="form-control" name="Web_Referrer_Company" value="001Pi00005enAmuIAE">
            <input type="hidden" class="form-control" name="Status" value="Awaiting Scheduling">
            <input type="hidden" class="form-control" name="Scheduling_Status" value="Awaiting 1st Patient Contact">
            <input type="hidden" class="form-control" name="Batch_Status" value="Unreleased">
            <input type="hidden" class="form-control" name="Episode_ID"
                value="<?= strtoupper(substr(md5(time()), rand(1, 6), 6)) ?>">
            <input type="hidden" class="form-control" name="List_Affiliate_Name" value="XYZ">

            <!-- Referral Section -->
            <div class="border rounded p-3 mb-3">

                <div class="row mb-3">
                    <div class="col-md-4">
                        <label class="form-label">First Name <span style="color: red;">*</span></label>
                        <input type="text" class="form-control" name="FirstName"
                            value="<?= isset($_POST['FirstName']) ? htmlspecialchars($_POST['FirstName']) : '' ?>"
                            required>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Last Name <span style="color: red;">*</span></label>
                        <input type="text" class="form-control" name="LastName"
                            value="<?= isset($_POST['LastName']) ? htmlspecialchars($_POST['LastName']) : '' ?>"
                            required>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Gender</label>
                        <input type="text" class="form-control" name="Gender"
                            value="<?= isset($_POST['Gender']) ? htmlspecialchars($_POST['Gender']) : '' ?>">
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Date of Birth <span style="color: red;">*</span></label>
                        <input type="date" class="form-control" name="Date_of_Birth"
                            value="<?= isset($_POST['Date_of_Birth']) ? htmlspecialchars($_POST['Date_of_Birth']) : '' ?>"
                            required>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Phone <span style="color: red;">*</span></label>
                        <input type="text" class="form-control" name="Phone"
                            value="<?= isset($_POST['Phone']) ? htmlspecialchars($_POST['Phone']) : '' ?>" required
                            pattern="\d{10}" maxlength="10" title="Please enter a 10-digit phone number (numbers only)">
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Mobile Phone</label>
                        <input type="text" class="form-control" name="MobilePhone"
                            value="<?= isset($_POST['MobilePhone']) ? htmlspecialchars($_POST['MobilePhone']) : '' ?>">
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" name="Email"
                            value="<?= isset($_POST['Email']) ? htmlspecialchars($_POST['Email']) : '' ?>">
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Street <span style="color: red;">*</span></label>
                        <input type="text" class="form-control" name="Street"
                            value="<?= isset($_POST['Street']) ? htmlspecialchars($_POST['Street']) : '' ?>" required>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">City <span style="color: red;">*</span></label>
                        <input type="text" class="form-control" name="City"
                            value="<?= isset($_POST['City']) ? htmlspecialchars($_POST['City']) : '' ?>" required>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">State <span style="color: red;">*</span></label>
                        <input type="text" class="form-control" name="State"
                            value="<?= isset($_POST['State']) ? htmlspecialchars($_POST['State']) : '' ?>" required>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Zip Code <span style="color: red;">*</span></label>
                        <input type="text" class="form-control" name="PostalCode"
                            value="<?= isset($_POST['PostalCode']) ? htmlspecialchars($_POST['PostalCode']) : '' ?>"
                            required>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Primary Insurance Company</label>
                        <input type="text" class="form-control" name="Primary_Insurance_Company"
                            value="<?= isset($_POST['Primary_Insurance_Company']) ? htmlspecialchars($_POST['Primary_Insurance_Company']) : '' ?>">
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Total Med Count</label>
                        <input type="number" class="form-control" name="Total_Med_Count"
                            value="<?= isset($_POST['Total_Med_Count']) ? htmlspecialchars($_POST['Total_Med_Count']) : '' ?>">
                    </div>
                </div>

            </div>

            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>
</body>

</html>