<?php
if ($_SERVER['HTTP_HOST'] != 'mcc-forms.dev') {
    $auth = 0;
    if (!isset($_SERVER['PHP_AUTH_USER'])) {
        header('WWW-Authenticate: Basic realm="Anew Health Data Records"');
        header('HTTP/1.0 401 Unauthorized');
        print "you need to login";
        exit;
    } else {
        if ($_SERVER['PHP_AUTH_USER'] == "admin" and $_SERVER['PHP_AUTH_PW'] == "mcc") {
            $auth = 1;
        } else {
            header('WWW-Authenticate: Basic realm="Anew Health Data Records"');
            header('HTTP/1.0 401 Unauthorized');
            print "you need to login";
            exit;
        }
    }

    if ($auth == 0) {
        print "you need to login";
        exit;
    }
}

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);
$SQL = "SELECT * FROM `api_logs` ";
$filter = false;
$title = "Last 1,000 Data Records";
if (isset($_GET['start']) && $_GET['start'] != '' && isset($_GET['end']) && $_GET['end'] != '') {
    $start = date("Y-m-d", strtotime($_GET['start']));
    $end = date("Y-m-d", strtotime($_GET['end']));
    $SQL .= " WHERE DATE(`system_date`) BETWEEN '$start' AND '$end' ";
    $filter = true;
    $title = "Data Records from " . date("d M, Y", strtotime($start)) . " to " . date("d M, Y", strtotime($end));
}

$SQL .= " ORDER BY `api_logs`.`uid` DESC";

if ($filter == false) $SQL .= " LIMIT 1000";
// echo $SQL; //exit;
$stmt = $db->query($SQL);
$records = $db->fetchAll($stmt);

if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="AneWhealth ' . $title . '.csv"');
    $output = fopen('php://output', 'w');
    // CSV header
    fputcsv($output, [
        'Sr. No',
        'Date/Time',
        'FirstName',
        'LastName',
        'Gender',
        'Date_of_Birth',
        'Phone',
        'MobilePhone',
        'Email',
        'Street',
        'City',
        'State',
        'PostalCode',
        'Episode_ID',
        'Primary_Insurance_Company',
        'Total_Med_Count',
        'Status'
    ]);
    $cnt = 1;
    // echo "<pre>";
    // print_r($records);
    // exit;
    foreach ($records as $record) {
        $request = json_decode($record['api_request'], true);
        $Referrals = $request['Referrals'][0];
        $result = json_decode($record['api_response'], true);
        fputcsv($output, [
            $cnt,
            date("d M, Y h:i A", strtotime($record['system_date'])),
            $Referrals['FirstName'],
            $Referrals['LastName'],
            $Referrals['Gender'],
            $Referrals['Date_of_Birth'],
            $Referrals['Phone'],
            $Referrals['MobilePhone'],
            $Referrals['Email'],
            $Referrals['Street'],
            $Referrals['City'],
            $Referrals['State'],
            $Referrals['PostalCode'],
            $Referrals['Episode_ID'],
            $Referrals['Primary_Insurance_Company'],
            $Referrals['Total_Med_Count'],
            is_array($result) ? implode(" | ", $result) : $result
        ]);
        $cnt++;
    }
    fclose($output);
    exit;
}
?>

<title>Anew Health - Data Records</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://getbootstrap.com/docs/4.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
<style>
    table td,
    table th {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .form-inline label {
        align-items: left;
        -ms-flex-pack: left;
        justify-content: left;
    }
</style>
<div class="container-fluid" style="margin: 20px auto 0; width: 95%;">
    <div class="row">
        <div class="col-12">
            <h3>Anew Health - Data Records</h3>
        </div>
        <div class="col-12">
            <div class="card">
                <div class="card-header"><strong>Filters</strong>
                    <div class="float-right">
                        <form method="get" action="" style="display:inline;">
                            <input type="hidden" name="start"
                                value="<?= isset($_GET['start']) ? htmlspecialchars($_GET['start']) : '' ?>">
                            <input type="hidden" name="end"
                                value="<?= isset($_GET['end']) ? htmlspecialchars($_GET['end']) : '' ?>">
                            <input type="hidden" name="export" value="csv">
                            <button type="submit" class="btn btn-success btn-sm">Export CSV</button>
                        </form>
                    </div>

                </div>
                <div class="card-body">
                    <form class="form-inline text-align-left" method="get" action="">
                        <div>
                            <label class="form-label">Start Date <span style="color: red;">*</span></label>
                            <input type="date" class="form-control" name="start" value="" required>
                        </div>
                        <div class="ml-2">
                            <label class="form-label">End Date <span style="color: red;">*</span></label>
                            <input type="date" class="form-control" name="end" value="" required>
                        </div>

                        <button type="submit" class="btn btn-success btn-sm mt-4 ml-2">Apply Filter</button>
                        <a href="anewhealth_records.php" class="btn btn-danger btn-sm mt-4 ml-2"
                            style="color: white;">Clear Filter</a>
                    </form>
                </div>
            </div>
        </div>
        <div class="col-12 mt-3">
            <div class="card">
                <div class="card-header"><strong><?= $title ?></strong></div>
                <div class="card-body">
                    <table id="example" class="table table-responsive" style="width: 100%; overflow-x: auto;">
                        <thead>
                            <tr>
                                <th>Sr. No</th>
                                <th>Date/Time</th>
                                <th>FirstName</th>
                                <th>LastName</th>
                                <th>Gender</th>
                                <th>Date_of_Birth</th>
                                <th>Phone</th>
                                <th>MobilePhone</th>
                                <th>Email</th>
                                <th>Street</th>
                                <th>City</th>
                                <th>State</th>
                                <th>PostalCode</th>
                                <th>Episode_ID</th>
                                <th>Primary_Insurance_Company</th>
                                <th>Total_Med_Count</th>
                                <th width="300">Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            if (count($records) > 0) {
                                $cnt = 1;
                                foreach ($records as $record) {
                                    $request = json_decode($record['api_request'], true);
                                    $Referrals = $request['Referrals'][0];
                                    $result = json_decode($record['api_response'], true);
                                    echo '
                                    <tr ' . (($record['api_response'] == '["Success! Leads are queued for creation."]') ? 'style="background-color:#d4edda; color: #155724;"' : '') . '>
                                        <td>' . $cnt . '</td>
                                        <td>' . date("d M, Y h:i A", strtotime($record['system_date'])) . '</td>
                                        <td>' . $Referrals['FirstName'] . '</td>
                                        <td>' . $Referrals['LastName'] . '</td>
                                        <td>' . $Referrals['Gender'] . '</td>
                                        <td>' . $Referrals['Date_of_Birth'] . '</td>
                                        <td>' . $Referrals['Phone'] . '</td>
                                        <td>' . $Referrals['MobilePhone'] . '</td>
                                        <td>' . $Referrals['Email'] . '</td>
                                        <td>' . $Referrals['Street'] . '</td>
                                        <td>' . $Referrals['City'] . '</td>
                                        <td>' . $Referrals['State'] . '</td>
                                        <td>' . $Referrals['PostalCode'] . '</td>
                                        <td>' . $Referrals['Episode_ID'] . '</td>
                                        <td>' . $Referrals['Primary_Insurance_Company'] . '</td>
                                        <td>' . $Referrals['Total_Med_Count'] . '</td>
                                        <td>' . implode("<br>", $result)  . '</td>
                                    </tr>';
                                    $cnt++;
                                }
                            } ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <th>Sr. No</th>
                                <th>Date/Time</th>
                                <th>FirstName</th>
                                <th>LastName</th>
                                <th>Gender</th>
                                <th>Date_of_Birth</th>
                                <th>Phone</th>
                                <th>MobilePhone</th>
                                <th>Email</th>
                                <th>Street</th>
                                <th>City</th>
                                <th>State</th>
                                <th>PostalCode</th>
                                <th>Episode_ID</th>
                                <th>Primary_Insurance_Company</th>
                                <th>Total_Med_Count</th>
                                <th>Status</th>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div style="width: 95%; margin: 50px auto 100px; text-align: center;">


</div>
<script>
    $(document).ready(function() {
        $('#example').DataTable({
            "ordering": false,
            lengthMenu: [
                [100, 250, 500, -1],
                [100, 250, 500, 'All'],
            ],
        });
    });
</script>