<?php

$page_security = 'SA_MMBR';
$path_to_root = '../../..';

include_once($path_to_root . "/includes/db_pager.inc");
include_once($path_to_root . "/includes/session.inc");
add_access_extensions();

$js = "";
if ($SysPrefs->use_popup_windows)
    $js .= get_js_open_window(900, 500);
if (user_use_date_picker())
    $js .= get_js_date_picker();
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/modules/church/includes/church_db.inc");
include_once($path_to_root . "/modules/church/includes/church_ui.inc");

//--------------------------------------------------------------------------
$member = new Member();

function get_post_data() {
    global $member;
    $member->per_Address1 = get_post('per_Address1');
    $member->per_BirthDay = get_post('per_BirthDay');
    $member->per_BirthMonth = get_post('per_BirthMonth');
    $member->per_BirthYear = get_post('per_BirthYear');
    $member->per_CellPhone = get_post('per_CellPhone');
    $member->per_HomePhone = get_post('per_HomePhone');
    $member->per_Status = get_post('per_Status');
    $member->per_Email = get_post('per_Email');
    $member->per_FirstName = get_post('per_FirstName');
    $member->per_Gender = get_post('per_Gender');
    $member->per_LastName = get_post('per_LastName');
    $member->per_MembershipDate = get_post('per_MembershipDate');
    $member->per_MiddleName = get_post('per_MiddleName');
    $member->per_Title = get_post('per_Title');
    $member->per_Zip = get_post('per_Zip');
    $member->per_ID = get_post('per_ID');
    $member->per_Group = get_post('per_Gro');
}

foreach ($_POST as $key => $value) {
    if (strpos($key, 'mmbr_id') === 0) {
        $mmbr = get_members($value);
        if (isset($mmbr->per_ID)) {
            $_SESSION['per_ID'] = $mmbr->per_ID;
            $_POST['_tabs_sel'] = 'add';
            $Ajax->activate('_page_body');
        }
    } else if (strpos($key, 'add_to_cart') === 0) {
        add_to_cart($value);
    }
}


$cur_id = isset($_SESSION['per_ID']) ? $_SESSION['per_ID'] : '';

$upload_file = "";
$avatar_path = $path_to_root . "/modules/FrontHrm/images/avatar/";
if (isset($_FILES['pic']) && $_FILES['pic']['name'] != '') {

    $result = $_FILES['pic']['error'];
    $upload_file = 'Yes';
    $filename = $avatar_path;
    if (!file_exists($filename))
        mkdir($filename);

    $filename .= mmbr_img_name($cur_id) . ".jpg";

    if ($_FILES['pic']['error'] == UPLOAD_ERR_INI_SIZE) {

        display_error(_('The file size is over the maximum allowed.'));
        $upload_file = 'No';
    } elseif ($_FILES['pic']['error'] > 0) {

        display_error(_('Error uploading file.'));
        $upload_file = 'No';
    }
    if ((list($width, $height, $type, $attr) = getimagesize($_FILES['pic']['tmp_name'])) !== false)
        $imagetype = $type;
    else
        $imagetype = false;

    if ($imagetype != IMAGETYPE_GIF && $imagetype != IMAGETYPE_JPEG && $imagetype != IMAGETYPE_PNG) {

        display_warning(_('Only graphics files can be uploaded'));
        $upload_file = 'No';
    } elseif (!in_array(strtoupper(substr(trim($_FILES['pic']['name']), strlen($_FILES['pic']['name']) - 3)), array('JPG', 'PNG', 'GIF'))) {

        display_warning(_('Only graphics files are supported - a file extension of .jpg, .png or .gif is expected'));
        $upload_file = 'No';
    } elseif ($_FILES['pic']['size'] > ($SysPrefs->max_image_size * 1024)) {

        display_warning(_('The file size is over the maximum allowed. The maximum size allowed in KB is') . ' ' . $SysPrefs->max_image_size);
        $upload_file = 'No';
    } elseif ($_FILES['pic']['type'] == "text/plain") {

        display_warning(_('Only graphics files can be uploaded'));
        $upload_file = 'No';
    } elseif (file_exists($filename)) {

        $result = unlink($filename);
        if (!$result) {
            display_error(_('The existing image could not be removed'));
            $upload_file = 'No';
        }
    }
    if ($upload_file == 'Yes')
        $result = move_uploaded_file($_FILES['pic']['tmp_name'], $filename);

    $Ajax->activate('_page_body');
}

//--------------------------------------------------------------------------

function can_process() {
    global $member;
    if (strlen($member->per_FirstName) == 0 || $member->per_FirstName == "") {
        display_error(_("Member first name must be entered."));
        set_focus('per_FirstName');
        return false;
    }
    if (!is_year($member->per_BirthYear) && $member->per_BirthYear != '0000') {
        display_error(_("Invalid birth year."));
        set_focus('per_BirthYear');
        return false;
    }
    return true;
}

//--------------------------------------------------------------------------

function can_delete($cur_id) {


    return true;
}

function add_to_cart($value, $replace = FALSE) {
    if (!isset($_SESSION['members_cart'])) {
        $_SESSION['members_cart'] = Array();
    }
    if (isset($_SESSION['members_cart'][$value]) && !$replace) {
        unset($_SESSION['members_cart'][$value]);
    } else {
        $_SESSION['members_cart'][$value] = $value;
    }
}

function add_all_to_cart($sql) {
    global $Ajax;
    if (isset($_SESSION['add_all_to_cart'])) {
        unset($_SESSION['add_all_to_cart']);
        unset($_SESSION['members_cart']);
    } else {
        $res = db_query($sql);
        if (db_num_rows($res) != 0) {
            while ($row = db_fetch($res)) {
                add_to_cart($row['per_ID'], TRUE);
            }
        }
        $_SESSION['add_all_to_cart'] = 1;
    }
    $Ajax->activate('_page_body');
}

function is_year($int) {
    if (is_numeric($int)) {
        $input = (int) $int;
        if ($input > 1000 && $input < 2100) {
            return TRUE;
        } else {
            return FALSE;
        }
    } else {
        return FALSE;
    }
}

//--------------------------------------------------------------------------

function id_link($row) {
    return button('cur_id', $row['per_ID']);
}

function add_to_cart_link($row) {
    $cart_txt = 'Add to Cart';
    if (isset($_SESSION['members_cart'][$row['per_ID']])) {
        $cart_txt = 'Remove from Cart';
    }
    return "<button name='add_to_cart" . $row['per_ID'] . "' value='" . $row['per_ID'] . "'  class='editbutton' >$cart_txt</button>";
}

function add_all_to_cart_link() {
    $cart_txt = 'Add All to Cart';
    if (isset($_SESSION['add_all_to_cart'])) {
        $cart_txt = 'Clear Cart';
    }
    return "<td><button name='add_all_to_cart' value='1'  class='editbutton' >$cart_txt</button></td>";
}

function gender_list_cell($gender) {
    $_selector = array_selector(
            'gender', $gender, $allocs = array(
        '' => _("Select Gender"),
        'Male' => _("Male"),
        'Female' => _("Female"),
            ), array('select_submit' => true)
    );
    label_cells(_("Select Gender:"), $_selector);
}

function status_list_cell($id) {
    $_selector = array_selector(
            'per_Status', $id, $allocs = array(
        '1' => _("Active"),
        '0' => _("Inactive"),
            ), array('select_submit' => FALSE)
    );
    label_cells(_("Select Status:"), $_selector);
}

function get_name($row) {
    return "<b><button name='mmbr_id" . $row['per_ID'] . "' value='" . $row['per_ID'] . "'  class='editbutton' >" . $row['name'] . "</button></b>";
}


function employees_table() {
    global $member, $Ajax;
    $_SESSION['per_ID'] = '';
    if (db_has_members()) {

        $sql = get_members(get_post('m_id'), get_post('gender'), get_post('group'), get_post('m_name'), TRUE);
        if (get_post('add_all_to_cart')) {
            add_all_to_cart($sql);
        }
        start_table(TABLESTYLE_NOBORDER);
        start_row();
        gender_list_cell(get_post('gender'));
        group_list_cells(_('Group:'), 'group', null, _('All Groups'), true);
        text_cells(_("Member ID:"), 'm_id', get_post('m_id'));
        text_cells(_("Name:"), 'm_name', get_post('m_name'));
        submit_cells('RefreshInquiry', _("Search"), '', _('Refresh Inquiry'), 'default');
        echo add_all_to_cart_link();
        end_row();
        end_table(1);

        if (get_post('RefreshInquiry') || list_updated('filterType')) {
            $Ajax->activate('_page_body');
        }

        $cols = array(
            _('ID'),
            _('Name') => array('fun' => 'get_name'),
            _('Gender'),
            _('address'),
            _('Mobile') => array(),
            _('Email'),
            _('Group'),
            _('Add to Cart') => array('fun' => 'add_to_cart_link', 'align' => 'center')
        );

        $table = & new_db_pager('member_tbl', $sql, $cols);
        $table->width = "80%";
        $table->page_len = 25;
        // display_note(_('Press name to edit employee details.'));
        display_db_pager($table);
    } else
        display_note(_("No Members defined."), 1);
}

//--------------------------------------------------------------------------

function member_settings($cur_id) {
    global $path_to_root, $avatar_path, $Ajax;
    $member = new Member();
    if ($cur_id) {
        $member = get_members($cur_id);
    }
    start_outer_table(TABLESTYLE2);

    table_section(1);

    hidden('per_ID', $cur_id);

    file_row(_("Image File") . ":", 'pic', 'pic');
    $emp_img_link = "";
    $check_remove_image = false;
    if ($cur_id && file_exists($avatar_path . mmbr_img_name($cur_id) . ".jpg")) {
        $emp_img_link .= "<img id='emp_img' alt = '[" . $cur_id . ".jpg" .
                "]' src='" . $avatar_path . mmbr_img_name($cur_id) .
                ".jpg?nocache=" . rand() . "'" . " height='100'>";
        $check_remove_image = true;
    } else
        $emp_img_link .= "<img id='emp_img' alt = '.jpg' src='$avatar_path" . "no_image.svg' height='100'>";

    label_row("&nbsp;", $emp_img_link);
    if ($check_remove_image)
        check_row(_("Delete Image:"), 'per_IMG');

    table_section_title(_("Personal Information"));

    if ($cur_id)
        label_row(_('Member Id:'), $cur_id);

    text_row(_("Title:"), 'per_Title', $member->per_Title, 37, 50);
    text_row(_("First Name: *"), 'per_FirstName', $member->per_FirstName, 37, 50);
    text_row(_("Last Name:"), 'per_LastName', $member->per_LastName, 37, 50);
    gender_radio_row1(_('Gender:'), 'per_Gender', $member->per_Gender);
    start_row();
    label_cells(_('Birth Month & Day:'), month_list('per_BirthMonth', $member->per_BirthMonth) .
            day_list('per_BirthDay', $member->per_BirthDay));
    end_row();
    text_row(_("Birth Year :"), 'per_BirthYear', $member->per_BirthYear, 10, 50);
    date_row(_("Membership Date:"), 'per_MembershipDate', null, null, 0, 0, 1001);

    table_section(2);

    table_section_title(_("Contact Information"));

    textarea_row(_("Address:"), 'per_Address1', $member->per_Address1, 35, 5);
    text_row(_("Mobile:"), 'per_HomePhone', $member->per_HomePhone, 37, 30);
    email_row(_("e-Mail:"), 'per_Email', $member->per_Email, 37, 100);
    $member_groups_str = '';

    $gr_res = get_member_groups($cur_id);
    if (db_num_rows($gr_res) != 0) {
        while ($row = db_fetch($gr_res)) {
            $member_groups_str .= "<option value='" . $row['id'] . "' selected='selected' >" . $row['name'] . "</option>";
        }
    }
    label_row(_('Groups: '), '<select style="width: 100%;" class="groups_select" name="per_Group" multiple="multiple"><option value="">Select Groups</option>' . $member_groups_str . '</select>');
    status_list_cell($member->per_Status);

    end_outer_table(1);

    div_start('controls');

    if ($cur_id) {

        submit_center_first('addupdate', _("Update Member"), _('Update Member details'), 'default');
        submit_center_last('delete', _("Delete Member"), _('Delete employee data if have been never used'), true);
    } else
        submit_center('addupdate', _("Add New Member Details"), true, '', 'default');


    div_end();
    $select_js = "$('.groups_select').select2({
        minimumInputLength: 1,
  ajax: {
    url: '$path_to_root/modules/api/membergroups?start=0&length=1000',
    dataType: 'json',
    processResults: function (data) {
      return {
        results: data.items
      };
    }
  }
});";
    if (in_ajax()) {
        $Ajax->addScript(true, $select_js);
    } else
        add_js_source($select_js);

    $Ajax->activate('_page_body');
}

//--------------------------------------------------------------------------

if (isset($_POST['addupdate'])) {

    get_post_data();
    if (!can_process())
        return;
    write_member($member);

    if (check_value('del_image')) {
        $filename = $avatar_path . emp_img_name($cur_id) . ".jpg";
        if (file_exists($filename))
            unlink($filename);
    }
    if ($cur_id) {
        $_SESSION['per_ID'] = $cur_id;
        display_notification(_("Member details has been updated."));
    } else {
        $_SESSION['per_ID'] = '';
        $cur_id = '';
        display_notification(_("A new member has been added."));
    }

    $Ajax->activate('_page_body');
} elseif (isset($_POST['delete'])) {

    if (!can_delete($cur_id))
        return;
    delete_member($cur_id);
    display_notification(_("Member details has been deleted."));
    $Ajax->activate('_page_body');
}

//--------------------------------------------------------------------------

page(_($help_context = "Manage Members"), false, false, "", $js);

start_form(true);

tabbed_content_start(
        'tabs', array(
    'list' => array(_('Member &List'), 999),
    'add' => array(_('&Add/Edit Member'), 999)
        )
);

if (get_post('_tabs_sel') == 'list')
    employees_table();
elseif (get_post('_tabs_sel') == 'add')
    member_settings($cur_id);

br();

tabbed_content_end();

end_form();
end_page();
