<?php

use App\MemberInfo;
use Carbon\Carbon;
use Mtc\Core\Permissions;
use Mtc\Modules\Members\Models\Member;
use Mtc\Modules\Members\Models\MembersAddress;


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

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

init_request_values([
    'id' => null,
    'firstname' => null,
    'lastname' => null,
    'email' => null,
    'contact_no' => null,
    'date_of_birth' => null,
    'startnumber' => null,
]);

if ($_REQUEST['action']=='delete' && is_numeric($_REQUEST['delete_id'])) {

    MembersAddress::query()
        ->where('member_id', $_REQUEST['delete_id'])
        ->delete();

    Member::query()
        ->where('id', $_REQUEST['delete_id'])
        ->delete();
}

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

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

<h1>Manage Members</h1>

<?php

include 'tabnav.php';

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

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

?>

<form action="manage_members.php" 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>
        <div class="row">
            <label for="lastname">Surname</label>
            <input type="text" name="lastname" id="lastname" value="<?= clean_page($_REQUEST['lastname']) ?>" />
        </div>
        <div class="row">
            <label for="email">Email</label>
            <input type="text" name="email" id="email" value="<?= clean_page($_REQUEST['email']) ?>" />
        </div>
        <div class="row">
            <label for="contact_no">Phone Number</label>
            <input type="text" name="contact_no" id="contact_no" value="<?= clean_page($_REQUEST['contact_no']) ?>" />
        </div>
        <div class="row">
            <label for="date_of_birth">Date of Birth</label>
            <input type="text"
                   name="date_of_birth"
                   placeholder="dd/mm/yyyy e.g. 06/07/1990"
                   id="date_of_birth"
                   value="<?= clean_page($_REQUEST['date_of_birth']) ?>" />
        </div>

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

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

/*
 * Lets start building the query.
 */

$params = [];

$append = [];

$query = Member::query();

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

if (!empty($_REQUEST['email'])) {
    $query->where('email', 'LIKE', '%' . trim($_REQUEST['email']) . '%');
}

if (!empty($_REQUEST['firstname'])) {
    $query->whereHas('addressBilling', function ($query) {
        $query->where('firstname', 'LIKE', '%' . str_replace('*', '%', trim($_REQUEST['firstname'])) . '%');
    });
}

if (!empty($_REQUEST['lastname'])) {
    $query->whereHas('addressBilling', function ($query) {
        $query->where('lastname', 'LIKE', '%' . str_replace('*', '%', trim($_REQUEST['lastname'])) . '%');
    });
}

if (!empty($_REQUEST['contact_no'])) {
    $query->whereRaw("REPLACE(`contact_no`, ' ', '') LIKE ?", ['%' . str_replace('*', '%', trim($_REQUEST['contact_no'])) . '%']);
}

if (!empty($_REQUEST['date_of_birth'])) {
    try {
        $date_of_birth = Carbon::createFromFormat('d/m/Y', $_REQUEST['date_of_birth']);
        $query->where('dob', $date_of_birth);
    } catch (\Exception $exception) {

    }
}

$query->orderBy('id', 'DESC');

// 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>ID</th>
            <th>Site of origin</th>
            <th>Name</th>
            <th>Email</th>
            <th>Phone Number</th>
            <th>Created</th>
            <th>Last login</th>
            <?php
            if (Permissions::can(Permissions::LOGIN_AS_PATIENT)) {
            ?>
                <th class="center">Login as</th>
            <?php
            }
            ?>
            <th class="center">Edit</th>
            <th class="center">Delete</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="manage_member.php?id=<?= $member->id ?>">
                        <?= clean_page($member->id) ?>
                    </a>
                </td>
                <td>
                    <?= MemberInfo::getSiteOfOrigin($member) ?>
                </td>
                <td>
                    <a href="manage_member.php?id=<?= $member->id ?>">
                        <?= clean_page($member->fullname) ?>
                    </a>
                </td>
                <td><?= clean_page($member->email) ?></td>
                <td><?= clean_page($member->contact_no) ?></td>
                <td><?= clean_page($member->created_at) ?></td>
                <td><?= clean_page($member_stats['last_login']) ?></td>

                <?php
                if (Permissions::can(Permissions::LOGIN_AS_PATIENT)) {
                ?>
                    <td>
                        <a href="<?= route('admin-login-as-member', ['id' => $member->id], false) ?>"
                        target="_blank">Login
                        <i class="fa fa-sign-in" aria-hidden="true"></i>
                        </a>
                    </td>
                <?php
                }
                ?>

                <td class="center">
                    <a href="manage_member.php?id=<?= $member->id ?>" class="edit">
                        <i class="fa fa-pencil"></i>
                    </a>
                </td>
                <td class="center">
                    <a href="manage_members.php?action=delete&delete_id=<?= $member->id ?>"
                        class="alert picto error"
                        title="Are you sure you want to delete this member?"
                    >
                        <i class="fa fa-times-circle"></i>
                    </a>
                </td>
            </tr>
        <?php
        }
        ?>
        </tbody>
    </table>
<?php
} else {
?>
    <p>There were no members found matching your search criteria</p>
<?php
}
?>

    <?= $members->render() ?>

    <form action="<?= route('admin-patients-export', [], false) ?>" method="post" class="style">
        <fieldset class="show">
            <h1><a class="show el">Export Members <i class="fa fa-caret-down"></i></a></h1>
            <div class="row">Click export below to export the above members as a CSV</div>
        </fieldset>
        <div class="row">
            <input type="hidden" name="id" value="<?= $_REQUEST['id'];?>"/>
            <input type="hidden" name="firstname" value="<?= $_REQUEST['firstname'];?>"/>
            <input type="hidden" name="lastname" value="<?= $_REQUEST['lastname'];?>"/>
            <input type="hidden" name="email" value="<?= $_REQUEST['email'];?>"/>
            <input type="submit" value="Export"/>
        </div>

    </form>
    <?php

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