<?php

/* * ********************************************************************
  Copyright (C) FrontAccounting, LLC.
  Released under the terms of the GNU General Public License, GPL,
  as published by the Free Software Foundation, either version 3
  of the License, or (at your option) any later version.
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
 * ********************************************************************* */
$page_security = 'SA_MMBR_SMS';
$path_to_root = '../../..';
include_once($path_to_root . "/includes/db_pager.inc");
include($path_to_root . "/includes/session.inc");
add_access_extensions();

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");
include_once($path_to_root . "/includes/data_checks.inc");

include_once($path_to_root . "/admin/db/company_db.inc");
include_once( $path_to_root . "/modules/external/includes/class.sms.inc");

page(_($help_context = "Send SMS"));

$_SESSION['sms_count'] = 0;
$_SESSION['sms_recepients'] = array();
foreach ($_POST as $key => $value) {
    if (strpos($key, 'add_to_cart') === 0) {
        add_to_cart($value);
    }
}

function add_to_cart($value, $replace = FALSE) {
    global $Ajax;
    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;
    }
    $Ajax->activate('_page_body');
}

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 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 preview_sms($row) {
    $sms = new SMS();
    $member = new Member();
    $member = get_members($row['per_ID']);
    $data = (array) $member;
    $body_txt = $sms->bindContent(get_post('sms_body'), $data);
    $count = floor((strlen($body_txt) / 160) + 1);
    $_SESSION['sms_count'] += $count;
    if (!empty($body_txt)) {
        return "<b>msg: </b>$body_txt</br/>"
                . " <b>Count: </b>$count";
    } else {
        return '';
    }
}

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);
}

//-------------------------------------------------------------------------------------------------
if (get_post('preview_sms')) {
    $Ajax->activate('_page_body');
}

function can_process() {
    $errors = 0;

    if (!empty($_SESSION['members_cart'])) {
        $tos = $_SESSION['members_cart'];

        if (count($tos) > 0) {
            foreach ($tos as $to) { //loop over values
                $member = new Member();
                $member = get_members($to);
                if (strlen($member->per_HomePhone) < 9) {
                    $errors++;
                    display_error(_("Mobile number " . $member->per_HomePhone . " is not a valid number. Please correct to continue."));
                } else {
                    $_SESSION['sms_recepients'][] = (array) $member;
                }
            }
        }
    } else {
        $errors++;
        display_error(_("Recepients must be set."));
    }

    if (empty($_POST['sms_body'])) {
        $errors++;
        display_error(_("Sms Body cannot be blunk."));
    }

    return ($errors == 0);
}

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

if (isset($_POST['submit']) && can_process()) {
    foreach ($_SESSION['sms_recepients'] as $recepient) {
        $sms = new SMS();

        $results = $sms->send($recepient['per_HomePhone'], $sms->bindContent(get_post('sms_body'), $recepient));
        foreach ($results as $res) {
            if($res->status == 'Success' || $res->status == 'PENDING'){
                display_notification(_("SMS sent to $res->number. Status: $res->status. "));
            } else {
                display_warning(_("Mobile Nomber: $res->number. Status: $res->status. "));
            }
        }
    }
}

function cart_table() {
    global $Ajax;
    $_SESSION['per_ID'] = '';
    if (db_has_members()) {
        $strict = FALSE;
        $ids = '';
        if (isset($_SESSION['members_cart'])) {
            $ids_arr = $_SESSION['members_cart'];
            if (!empty(get_post('m_id'))) {
                $ids_arr[get_post('m_id')] = get_post('m_id');
            } else if (!empty(get_post('preview_sms')) || !empty(get_post('submit'))) {
                //display_error(can_process());
                $ids_arr = $_SESSION['members_cart'];
                $strict = TRUE;
            }
            $ids = join(',', $ids_arr);
        }

        if (!empty(get_post('m_id'))) {
            $strict = TRUE;
        }
        $sql = select_members($ids, get_post('gender'), get_post('group'), get_post('m_name'), $strict);

        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);

        //display_warning(isset($_POST['preview_sms']));
        if (get_post('RefreshInquiry') || list_updated('filterType') || isset($_POST['preview_sms'])) {
            $Ajax->activate('_page_body');
            $Ajax->activate('_member_tbl_span');
        }

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

        $table = & new_db_pager('member_tbl', $sql, $cols);
        $table->width = "80%";

        // display_note(_('Press name to edit employee details.'));
        display_db_pager($table);
    } else
        display_note(_("No Members defined."), 1);
}

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


start_form();

cart_table();

div_start('details');

start_table(TABLESTYLE2);
start_row();
label_row('Recipiens: ', isset($_SESSION['members_cart']) ? count($_SESSION['members_cart']) : 0);
label_row('SMS Count: ', $_SESSION['sms_count']);
textarea_row(_("SMS BODY:"), 'sms_body', '', 50, 6);
label_row(_("Variables:"), '{per_FirstName} {per_LastName} {per_Gender}<br/>
{per_Address1} {per_BirthDay} {per_BirthMonth}<br/>
{per_BirthYear} {per_HomePhone} {per_ID}<br/>
{per_Email} {per_MembershipDate} {per_Title}');
end_row();
end_table(1);
div_end();


if (!empty(get_post('preview_sms'))) {
    submit_center('submit', _("Send SMS"), true, '', 'process');
} else {
    submit_center('preview_sms', _("Preview Send"), true, '', 'default');
}

end_form(2);

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

end_page();
?>
