<?php
namespace Mtc\Plugins\NHS\Classes;

/**
 * @author: Uldis Zvirbulis <uldis.zvirbulis@mtcmedia.co.uk>
 * @version: 10/17/2017
 */

use App\Src\Encryption;
use Carbon\Carbon;
use Mtc\Modules\Members\Models\Member;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';

init_request_values([
    'startnumber' => null,
    'id' => null,
    'firstname' => null,
    'lastname' => null,
    'email' => null,
    'is_pay_for_prescriptions' => null,
    'is_patient' => null,
    'gender' => null,
    'doctor_surgery' => null,
]);

$page_meta['title'] = 'Manage NHS Members';

if (filter_input(INPUT_POST, 'action') === 'update_nhs_number') {
    $nhsMember = NHSMember::query()
        ->where('member_id', '=', filter_input(INPUT_POST, 'member_id'))
        ->first();
    if (!empty($nhsMember)) {
        $nhsMember->nhs_number = filter_input(INPUT_POST, 'nhs_number');
        $nhsMember->save();
    }
    exit;
}

if ($_REQUEST['action'] === 'delete' && is_numeric($_REQUEST['delete_id'])) {
    NHSMember::query()
        ->where('id', $_REQUEST['delete_id'])
        ->delete();
}

// Lets check if we need to start at a new page.
if (is_numeric($_REQUEST['startnumber'])) {
    $startnumber = $_REQUEST['startnumber'];
} else {
    $startnumber = 0;
}

$params = [];

$append = [];

$query = Member::query()
    ->select('members.*')
    ->distinct()
    ->join('nhs_members', 'members.id', '=', 'nhs_members.member_id');

if (!empty($_REQUEST['id'])) {
    $query->where('id', $_REQUEST['id']);
}

if (!empty($_REQUEST['email'])) {
    $query->where('email_hash', Encryption::makeHash($_REQUEST['email']));
}

if (!empty($_REQUEST['firstname'])) {
    $query->where('nhs_members.firstname', Encryption::makeHash($_REQUEST['firstname']));
}

if (!empty($_REQUEST['lastname'])) {
    $query->where('nhs_members.lastname', Encryption::makeHash($_REQUEST['lastname']));
}

if (!empty($_REQUEST['doctor_surgery'])) {
    $query->join('doctor_surgeries', function ($join) {
        $join->on('doctor_surgeries.id', '=', 'nhs_members.doctor_surgery_id')
            ->where('doctor_surgeries.practice_name', 'LIKE', str_replace('*', '%', $_REQUEST['doctor_surgery']));
    });
}

if (!empty($_REQUEST['incomplete_prescriptions']) || !empty($_REQUEST['overdue'])) {
    $query->join('nhs_member_prescriptions', function ($join) {
        $join->on('nhs_members.id', '=', 'nhs_member_prescriptions.nhs_member_id');
    });
}
if (!empty($_REQUEST['incomplete_prescriptions'])) {
    // If needs to include custom dosage
    //->leftJoin('nhs_dosages', 'nhs_dosages.id', '=', 'nhs_member_prescriptions.dosage_id')
    $query->where(function ($query) {
        $query->where('nhs_member_prescriptions.quantity', '')
        ->orWhere('nhs_member_prescriptions.quantity', '0')
        ->orWhere('nhs_member_prescriptions.quantity_per_dose', '')
        ->orWhere('nhs_member_prescriptions.dosage_id', null);
        // If needs to include custom dosage
        //->orWhereNotNull('nhs_dosages.member_id');
    });
}

if (!empty($_REQUEST['overdue'])) {
    // Reorder date is Refill date minus 9 days. Show all orders that have reorder date between today and 4 weeks in the past
    $reorder_date_to = (new Carbon())->addDays(Prescription::DAYS_TO_REORDER_BEFORE_COMPLETION_DATE)->format('Y-m-d');
    $reorder_date_from = (new Carbon())->addDays(Prescription::DAYS_TO_REORDER_BEFORE_COMPLETION_DATE)->subWeeks(4)->format('Y-m-d');
    $query->whereBetween('nhs_member_prescriptions.refill_date', [$reorder_date_from, $reorder_date_to]);
}

if (isset($_REQUEST['is_pay_for_prescriptions']) && $_REQUEST['is_pay_for_prescriptions'] !== '') {
    $query->where('nhs_members.is_pay_for_prescriptions', $_REQUEST['is_pay_for_prescriptions']);
}

if (isset($_REQUEST['is_patient']) && $_REQUEST['is_patient'] !== '') {
    $query->where('nhs_members.is_patient', $_REQUEST['is_patient']);
}

if (isset($_REQUEST['gender']) && $_REQUEST['gender'] !== '') {
    $query->where('nhs_members.gender', $_REQUEST['gender']);
}

$query->orderBy('id', 'DESC');
if (filter_input(INPUT_POST, 'action') === 'export') {
    $members = $query->get();
    $rows[] = [
        'Member ID',
        'NHS Number',
        'Name',
        'Email',
        'Doctor Surgery',
        'DOB',
        'Gender',
        'Pays for prescriptions',
        'Reason why not paying',
        'Type',
    ];
    foreach ($members as $member) {
        $rows[] = [
            $member->id,
            $member->nhs_member->nhs_number,
            $member->fullname,
            $member->email,
            $member->nhs_member->doctor_surgery->practice_name,
            date_convert_db_to_dmy($member->nhs_member->dob),
            $member->nhs_member->gender,
            $member->nhs_member->is_pay_for_prescriptions ? 'Yes' : 'No',
            $member->nhs_member->pay_explanation,
            $member->nhs_member->is_patient ? 'Patient' : 'Representative',
        ];
    }
    $filename = 'nhs_members_export_' . new \Carbon\Carbon() . '.csv';

    $download_file = fopen($filename, 'w');
    foreach ($rows as $row) {
        fputcsv($download_file, $row, ',');
    }
    fclose($download_file);

    \Util::force_download($filename, file_get_contents($filename));
    unlink($filename);
    exit;
}

require_once $path . 'core/admin/templates/adminheader.html.php';

?>
    <ul class="breadcrumbs el">
        <li><a href="/admin/">Home</a> /</li>
        <li class="end">Manage NHS Members</li>
    </ul>

    <h1>Manage NHS Members</h1>

<?php

include __DIR__ . '/tabnav.php';

if (!empty($_REQUEST['errors'])) {
    $errors['failed_login'] = clean_page($_REQUEST['errors']);
}

if (!empty($errors)) {
    showerrors($errors);
}

?>

    <form action="" method="GET" class="style">
        <fieldset class="show">
            <h1>
                <a class="show el">
                    Search <i class="fa fa-caret-right"></i>
                </a>
            </h1>
            <div class="row">
                <label for="memeberid">
                    Member ID
                </label>
                <input type="text"
                       name="id"
                       id="memeberid"
                       value="<?= clean_page($_REQUEST['id']) ?>"
                />
            </div>
            <div class="row">
                <label for="firstname">
                    Firstname
                </label>
                <input type="text"
                       name="firstname"
                       id="firstname"
                       value="<?= clean_page($_REQUEST['firstname']) ?>"
                />
                <div class="defaultValue">
                    <small>
                        Use complete value for search, partial search is not available
                    </small>
                </div>
            </div>
            <div class="row">
                <label for="lastname">
                    Surname
                </label>
                <input type="text"
                       name="lastname"
                       id="lastname"
                       value="<?= clean_page($_REQUEST['lastname']) ?>"
                />
                <div class="defaultValue">
                    <small>
                        Use complete value for search, partial search is not available
                    </small>
                </div>
            </div>
            <div class="row">
                <label for="email">
                    Email
                </label>
                <input type="text"
                       name="email"
                       id="email"
                       value="<?= clean_page($_REQUEST['email']) ?>"
                />
                <div class="defaultValue">
                    <small>
                        Use complete value for search, partial search is not available
                    </small>
                </div>
            </div>
            <div class="row">
                <label for="is_pay_for_prescriptions">
                    Pays for prescriptions
                </label>
                <select name="is_pay_for_prescriptions"
                        id="is_pay_for_prescriptions"
                >
                    <option value="">
                        All
                    </option>
                    <option value="0" <?= $_REQUEST['is_pay_for_prescriptions'] === '0' ? 'selected' : ''; ?>>
                        No
                    </option>
                    <option value="1" <?= $_REQUEST['is_pay_for_prescriptions'] === '1' ? 'selected' : ''; ?>>
                        Yes
                    </option>
                </select>
            </div>
            <div class="row">
                <label for="is_patient">
                    NHS Member Type
                </label>
                <select name="is_patient"
                        id="is_patient">
                    <option value="">
                        All
                    </option>
                    <option value="1" <?= $_REQUEST['is_patient'] === '1' ? 'selected' : ''; ?>>
                        Patient
                    </option>
                    <option value="0" <?= $_REQUEST['is_patient'] === '0' ? 'selected' : ''; ?>>
                        Representative
                    </option>
                </select>
            </div>
            <div class="row">
                <label for="gender">
                    Gender
                </label>
                <select name="gender"
                        id="gender"
                >
                    <option value="">
                        All
                    </option>
                    <option value="male" <?= $_REQUEST['gender'] === 'male' ? 'selected' : ''; ?>>
                        Male
                    </option>
                    <option value="female" <?= $_REQUEST['gender'] === 'female' ? 'selected' : ''; ?>>
                        Female
                    </option>
                </select>
            </div>
            <div class="row">
                <label for="doctor_surgery">
                    Doctor Surgery
                </label>
                <input type="text"
                       name="doctor_surgery"
                       id="doctor_surgery"
                       value="<?= clean_page($_REQUEST['doctor_surgery']) ?>"
                />
            </div>
            <div class="row">
                <label for="incomplete_prescriptions">
                    Has incomplete prescriptions
                </label>
                <input type="checkbox"
                       name="incomplete_prescriptions"
                       id="incomplete_prescriptions"
                    <?= (!empty($_REQUEST['incomplete_prescriptions'])) ? 'checked' : ''; ?>
                >
            </div>
            <div class="row">
                <label for="overdue">
                    Has overdue prescriptions
                </label>
                <input type="checkbox"
                       name="overdue"
                       id="overdue"
                        <?= (!empty($_REQUEST['overdue'])) ? 'checked' : ''; ?>
                >
            </div>

            <div class="search-button">
                <input type="hidden" name="action" value="search"/>
                <input type="submit" value="Search" class="BUTTON"/>
            </div>
        </fieldset>
    </form>

<?php


// some preparation for the paginator to work
(new \Mtc\Modules\Members\Classes\ViewFixer())->resolvePaginationDependencies($twig);

$members = $query->paginate(25);

$members->appends($_GET);

$totalnumrows = $members->total();

if ($totalnumrows > 0) {
    ?>
    <table class="manage-items">
        <tr>
            <th class="center">Member ID</th>
            <th>NHS Number</th>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
        <?php
            if (empty($_REQUEST['overdue'])) {
                ?>
                <th>Doctor Surgery</th>
                <th>DOB</th>
                <th>Gender</th>
                <th>Type</th>
                <th class="center">NHS Consent</th>
                <th>Date Registered</th>
                <?php
            } else {
                ?>
                <th>Overdue prescriptions</th>
                <?php
            }
        ?>
            <th>Pays for prescriptions</th>
            <th class="center">Login as</th>
            <th class="center">Edit</th>
        </tr>
        <tbody class="tabular">
        <?php
        foreach ($members as $member) {
            /* @var $member Member */

            $member_stats = Member::getMemberStats($member->id);

            ?>
            <tr id="rorder-<?= $member->id ?>">
                <td>
                    <a href="/modules/Members/admin/manage_members.php?id=<?= $member->id ?>">
                        <?= clean_page($member->id) ?>
                    </a>
                </td>
                <td class="nhsNumberColumn" data-member_id="<?= clean_page($member->id); ?>">
                    <span class="nhsNumberText"
                          id="nhsNumberText-<?= clean_page($member->id); ?>"><?= clean_page($member->nhs_member->nhs_number); ?></span>
                                <input class="nhsNumberInput hideme" id="nhsNumberInput-<?= clean_page($member->id); ?>"
                                       value="<?= clean_page($member->nhs_member->nhs_number); ?>" data-member_id="<?= clean_page($member->id); ?>"/>
                </td>
                <td>
                    <a href="/modules/Members/admin/manage_members.php?id=<?= $member->id ?>">
                        <?= clean_page($member->fullname) ?>
                    </a>
                </td>
                <td><?= clean_page($member->email); ?></td>
                <td><?= clean_page($member->phone_prefix); ?><?= clean_page($member->contact_no); ?></td>
                <?php
                if (empty($_REQUEST['overdue'])) {
                    ?>
                    <td><?= clean_page($member->nhs_member->doctor_surgery->practice_name ?? null); ?></td>
                    <td><?= clean_page(date_convert_db_to_dmy($member->nhs_member->dob)); ?></td>
                    <td><?= clean_page($member->nhs_member->gender); ?></td>
                    <td><?= $member->nhs_member->is_patient ? 'Patient' : 'Representative'; ?></td>
                    <td class="center">
                        <a href="/plugins/NHS/admin/download_consent.php?id=<?= (int)$member->id ?>" target="_blank">
                            <i class="fa fa-download"></i>
                        </a>
                    </td>
                    <td><?= Carbon::createFromFormat('Y-m-d H:i:s', $member->nhs_member->created_at)->format('d/m/Y'); ?></td>
                    <?php
                } else {
                    ?>
                    <td>
                        <?php
                        $overdue_prescriptions = $member->nhs_member->prescriptions()
                            ->whereBetween('refill_date', [$reorder_date_from, $reorder_date_to])
                            ->get();
                            foreach($overdue_prescriptions as $overdue_prescription) {
                                echo 'Re-order date: <strong>' . Carbon::createFromFormat('Y-m-d', $overdue_prescription->refill_date)->subDays(Prescription::DAYS_TO_REORDER_BEFORE_COMPLETION_DATE)->format('d.m.Y') . '</strong> | ';
                                echo 'Prescription: ' . $overdue_prescription->name . '<br />';
                            }
                        ?>
                    </td>
                    <?php
                }
                ?>
                <td><?= $member->nhs_member->is_pay_for_prescriptions ? 'Yes' : '-'; ?></td>
                <td>
                    <a href="<?= route('admin-login-as-member', [
                        'id' => $member->id,
                        'type' => 'nhs'
                    ]); ?>"
                       target="_blank"
                    >
                        Login
                        <i class="fa fa-sign-in" aria-hidden="true"></i>
                    </a>
                </td>

                <td class="center">
                    <a href="/plugins/NHS/admin/manage_nhs_member.php?id=<?= $member->nhs_member->id ?>" class="edit">
                        <i class="fa fa-pencil"></i>
                    </a>
                </td>
            </tr>
            <?php
        }
        ?>
        </tbody>
    </table>
    <?php
} else {
    ?>
    <p>There were no NHS members found matching your search criteria</p>
    <?php
}
?>

<?= $members->render() ?>
    <form method="post" class="style">
        <h2>Export NHS Members</h2>
        <p>This will export a CSV containing NHS members from the search result</p>
        <input type="hidden" name="action" value="export"/>
        <input type="submit" value="Export"/>
    </form>

<?php

require_once $path . 'core/admin/templates/adminfooter.html.php';
