<?php

use Carbon\Carbon;
use Mtc\Core\Models\Country;
use Mtc\Modules\Members\Classes\MemberManager;
use Mtc\Modules\Members\Models\Member;
use Mtc\Modules\Members\Models\MembersAddress;
use Mtc\Plugins\NewsletterSignup\Classes\Newsletter;



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


//get the ID of the member to edit - no ID means user wants to add new member
    if (isset($_REQUEST['id'])) {
        $member_id = abs((int) $_REQUEST['id']);
    } else {
        $member_id = 0;
    }

$page_meta['title'] = 'Edit Member Details';
$section = 'members';
$display_form = true;

if ($member_id > 0) {
    $add_edit = 'Update';
} else {
    $add_edit = 'Add';
}

//will load member if ID given
$member = Member::findOrNew($member_id);
$address_billing = $member->addressBilling ?: new MembersAddress();
$address_shipping = $member->addressShipping ?: new MembersAddress();

//rule to show or collapse certain parts of the form
$class_show = '';

if ($_REQUEST['action'] === 'update') {
    $post = $_POST;
    $post['medications'] = json_encode(explode(',', $post['medications']));
    $post['conditions'] = json_encode(explode(',', $post['conditions']));
    $post['allergies'] = json_encode(explode(',', $post['allergies']));

    $member_manager = new MemberManager();
    if (!$member_manager->save($post, $member)) {
        $errors = $member_manager->getErrors();
        //set this to keep user input when errors occur
        $member->fill($post);
        $address_billing->fill($member_manager->cleanInputAddress($post, 'billing_'));
        $address_shipping->fill($member_manager->cleanInputAddress($post, 'shipping_'));

    } else { //redirect user to clear post and avoid adding another when refreshing accidentally
        if (!empty($post['newsletter'])) {
            Newsletter::signUp($post['email'], [
                'first_name' => $post['billing_firstname'],
                'last_name' => $post['billing_lastname'],
                'skip_double_opt_in' => true,
            ]);
        } else {
            Newsletter::unsubscribe($post['email']);
        }
        header('Location: ?success=' . strtolower($add_edit) . '&id=' . $member->id);
        exit;
    }
}

$titles = Member::$titles;

require_once $path . 'core/admin/templates/adminheader.html.php';
?>
<script type="text/javascript" src="../js/mtc_members.js"></script>

<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li><a href="/modules/Members/admin/manage_members.php">Manage Members</a> /</li>
    <li class="end"><?= $add_edit ?> Member Details</li>
</ul>

<h1><?= $add_edit ?> Member</h1>

<?php

include 'tabnav.php';

if ($display_form) {

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

    //success message based on whether user updated or added member
    if (empty($errors) && isset($_REQUEST['success'])) {
        $message = 'Member successfully ';
        if ($_REQUEST['success'] == 'add') {
            $message .= 'added';
        } elseif ($_REQUEST['success'] == 'update') {
            $message .= 'updated';
        }

        echo showmsg($message, "success", $path);
    }
    ?>

    <form action="manage_member.php" method="POST" class="style">
        <fieldset class="show">
            <h1><a class="show el">Details <i class="fa fa-caret-right"></i></a></h1>
            <div class="row">
                <label for="email">Email</label>
                <input type="text" name="email" id="email" value="<?= clean_page($member->email);?>">
            </div>

            <div class="row">
                <label for="gender">Gender</label>
                <select name="gender" id="gender">
                    <option value="">Not defined</option>
                    <?php
                    foreach (Member::$genders as $gender) {
                        $selected = ($member->gender === $gender) ? ' selected' : null;
                        echo '<option value="'.$gender.'" '.$selected.'>'.$gender.'</option>';
                    }
                    ?>
                </select>
            </div>
            <div class="row">
                <label for="billing_firstname">Firstname</label>
                <input type="text" name="billing_firstname" id="billing_firstname" value="<?= clean_page($address_billing['firstname']);?>">
            </div>
            <div class="row">
                <label for="billing_lastname">Lastname</label>
                <input type="text" name="billing_lastname" id="billing_lastname" value="<?= clean_page($address_billing['lastname']);?>">
            </div>
            <div class="row">
                <label for="contact_no">Contact Number</label>
                <input type="text" name="contact_no" id="contact_no" value="<?= clean_page($member->contact_no);?>">
            </div>

            <div class="row">
                <label for="id_verified">Account verified (phone/email)</label>
                <input type="checkbox"
                       name="account_verified"
                       id="account_verified"
                       <?= !empty($member->account_verified) ? 'checked' : ''; ?> />
            </div>

            <div class="row">
                <label for="passed_id_check">ID Check Service passed (LexisNexis)</label>
                <input type="checkbox"
                       name="passed_id_check"
                       id="passed_id_check"
                        <?= !empty($member->passed_id_check) ? 'checked' : ''; ?> />
            </div>

            <div class="row">
                <label for="dob_date">DOB</label>
                <input type="number"
                       min="1"
                       max="31"
                       name="dob_date"
                       id="dob_date"
                       value="<?= !empty($member->dob) ? Carbon::parse($member->dob)->format('d') : ''; ?>"
                       class="short"
                >
                <input type="number"
                       min="1"
                       max="12"
                       name="dob_month"
                       id="dob_month"
                       value="<?= !empty($member->dob) ? Carbon::parse($member->dob)->format('m') : ''; ?>"
                       class="short"
                >
                <input type="number"
                       min="1900"
                       max="<?=date('Y');?>"
                       name="dob_year"
                       id="dob_year"
                       value="<?= !empty($member->dob) ? Carbon::parse($member->dob)->format('Y') : ''; ?>"
                       class="short"
                >
            </div>

            <div class="row">
                <label for="height">
                    Height (cm)
                </label>
                <input type="number"
                       name="height"
                       id="height"
                       value="<?= clean_page($member->height);?>" class="short"
                >
            </div>

            <div class="row">
                <label for="medications">Allergies</label>
                <input type="hidden" id="allergies" name="allergies"
                       class="js_allergies_tagit"
                       value="<?= $member->getAllergiesString() ?>" />
            </div>
            <div class="row">
                <label for="medications">Medications</label>
                <input type="hidden" id="medications" name="medications"
                       class="js_medications_tagit"
                       value="<?= $member->getMedicationsString() ?>" />
            </div>
            <div class="row">
                <label for="conditions">Medical Conditions</label>
                <input type="hidden" id="conditions" name="conditions"
                       class="js_medical_conditions_tagit"
                       autocomplete="off"
                       value="<?= $member->getConditionsString() ?>" />
            </div>

                <script src="/core/admin/js/libs/tagit/js/tag-it.min.js"></script>
                <link rel="stylesheet" href="/core/admin/js/libs/tagit/css/jquery.tagit.css">

                <script>
                    var all_medications = <?= json_encode(\Mtc\Shop\Medication::query()->pluck('name')->toArray()); ?>;
                    var all_medical_conditions = <?= json_encode(\Mtc\Shop\MedicalCondition::query()->pluck('name')->toArray()); ?>;
                </script>

            <div class="row">
                <label for="newsletter">
                    Subscribed to newsletter
                </label>
                <input type="checkbox"
                       name="newsletter"
                       id="newsletter"<?= Newsletter::checkIfExists($member->email) ? ' checked' : '' ?>
                />
            </div>

        </fieldset>
        <?php
        if (SAGEPAY_TOKEN && !empty($member->sagepay_token)) {
        ?>
            <fieldset>
                <h1><a class="show el">Credit Card Details <i class="fa fa-caret-right"></i></a></h1>

                <div class="row">
                    <label >Card Type: </label> <input type="text" readonly="" value="<?=clean_page($member->sagepay_card); ?>" />
                </div>
                <div class="row">
                    <label >Last 4 digits: </label> <input type="text" readonly="" value="<?=clean_page($member->sagepay_last4); ?>" />
                </div>
            </fieldset>
        <?php
        }
        ?>
            <fieldset>
                <?php
                //only show change option when updating member
                if ($member->id) {

                    ?>
                    <h1><a class="show el">Change Password <i class="fa fa-caret-right"></i></a></h1>

                    <div class="row">
                        <label for="resetpw">Change Password</label>
                        <input type="checkbox" name="resetpw" id="resetpw" value="1" />
                    </div>
                    <?php
                }

                ?>

                <div class="row">
                    <label for="password">Password</label>
                    <td><input type="password" name="password" value="" />
                </div>

                <div class="row">
                    <label for="password2">Confirm Password</label>
                    <td><input type="password" name="password2" value="" />
                </div>
            </fieldset>

            <fieldset class="<?= $class_show ?>">

                <h1><a class="show el">Billing Address <i class="fa fa-caret-right"></i></a></h1>

                <div class="row">
                    <label for="address1">Address 1</label>
                    <input type="text" name="billing_address1" id="address1" value="<?= clean_page($address_billing['address1']) ?>">
                </div>

                <div class="row">
                    <label for="address2">Address 2</label>
                    <input type="text" name="billing_address2" id="address2" value="<?= clean_page($address_billing['address2']) ?>">
                </div>

                <div class="row">
                    <label for="city">City</label>
                    <input type="text" name="billing_city" id="city" value="<?= clean_page($address_billing['city']) ?>">
                </div>
                <div class="row">
                    <label for="country">Country</label>
                    <select name="billing_country" id="country">
                        <?php

                        if (empty($address_billing['country'])) {
                            $address_billing['country']='GB';
                        }

                        foreach (Country::getFullCountryList() as $country_id => $country_name) {
                            if ($address_billing['country'] == $country_id) {
                                ?>
                                <option value="<?= $country_id ?>" selected><?= $country_name ?></option>
                                <?php
                            } else {
                                ?>
                                <option value="<?= $country_id ?>"><?= $country_name ?></option>
                                <?php
                            }
                        }
                        ?>
                    </select>
                </div>
                <div class="row">
                    <div id="state_row">
                    </div>
                </div>
                <div class="row">
                    <label for="postcode">Postcode</label>
                    <input type="text" name="billing_postcode" id="postcode" value="<?= clean_page($address_billing['postcode']) ?>" />
                </div>
            </fieldset>

            <fieldset class="<?= $class_show ?>">

                <h1><a class="show el">Shipping Address <i class="fa fa-caret-right"></i></a></h1>

                <div class="row">
                    <label for="address1">Address 1</label>
                    <input type="text" name="shipping_address1" id="address1" value="<?= clean_page($address_shipping['address1']) ?>">
                </div>

                <div class="row">
                    <label for="address2">Address 2</label>
                    <input type="text" name="shipping_address2" id="address2" value="<?= clean_page($address_shipping['address2']) ?>">
                </div>

                <div class="row">
                    <label for="city">City</label>
                    <input type="text" name="shipping_city" id="city" value="<?= clean_page($address_shipping['city']) ?>">
                </div>
                <div class="row">
                    <label for="country">Country</label>
                    <select name="shipping_country" id="country">
                        <?php

                        if (empty($address_shipping['country'])) {
                            $address_shipping['country']='GB';
                        }

                        foreach (Country::getFullCountryList() as $country_id => $country_name) {
                            if ($address_shipping['country'] == $country_id) {
                                ?>
                                <option value="<?= $country_id ?>" selected><?= $country_name ?></option>
                                <?php
                            } else {
                                ?>
                                <option value="<?= $country_id ?>"><?= $country_name ?></option>
                                <?php
                            }
                        }
                        ?>
                    </select>
                </div>
                <div class="row">
                    <div id="state_row">
                    </div>
                </div>
                <div class="row">
                    <label for="postcode">Postcode</label>
                    <input type="text" name="shipping_postcode" id="postcode" value="<?= clean_page($address_shipping['postcode']) ?>" />
                </div>
            </fieldset>

        <input type="hidden" name="id" id="member_id" value="<?= $member->id ?>" />
        <input type="hidden" name="action" value="update" />
        <input type="hidden" name="from_admin_area" value="1" />
        <input type="submit" value="Save" />

    </form>
<?php
}

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