<?php
if (isset($_POST['download_csv'])) {
    download_csv('members.csv', 'import_members_csv.csv');
}
/* * ********************************************
  Author: kenn
  Author: Tom Moulton - added Export of many types and import of the same
  Name: Import of CSV formatted members
  Free software under GNU GPL
 * ********************************************* */
set_time_limit(0);
$page_security = 'SA_MMBR';
$path_to_root = '../../..';

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

include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/data_checks.inc");

include_once($path_to_root . "/inventory/includes/inventory_db.inc");
include_once($path_to_root . "/inventory/includes/db/items_codes_db.inc");
include_once($path_to_root . "/dimensions/includes/dimensions_db.inc");
include_once($path_to_root . "/modules/church/includes/church_db.inc");

function download_csv($filename, $saveasname = '') {
    if (empty($filename) || !file_exists($filename)) {
        return false;
    }
    if ($saveasname == '')
        $saveasname = basename($filename);
    header('Content-type: text/x-csv');
    header('Content-Disposition: attachment; filename="' . $saveasname . '"');
    readfile($filename);
    exit;
}

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

page("Import of CSV formatted Members");

if (isset($_POST['import'])) {
    if (isset($_FILES['imp']) && $_FILES['imp']['name'] != '') {
        $filename = $_FILES['imp']['tmp_name'];
        $sep = $_POST['sep'];

        $fp = @fopen($filename, "r");
        if (!$fp)
            die("can not open file $filename");

        $lines = 0;
        $test = TRUE;
        $csv_lines[] = array();
        // type, item_code, stock_id, description, category, units, qty, mb_flag, currency, price
        while ($data = fgetcsv($fp, 4096, $sep)) {
            if ($lines++ == 0)
                continue;
            $member = new Member();
            list($member->per_Title, $member->per_FirstName, $member->per_LastName, $member->per_Gender, $member->per_BirthMonth, $member->per_BirthDay, $member->per_BirthYear, $member->per_MembershipDate, $member->per_Address1, $member->per_HomePhone, $member->per_Email, $member->per_Group, $member->per_Status) = $data;

            if (strlen($member->per_FirstName) == 0 || $member->per_FirstName == "") {
                display_error(_("Member first name must be entered On line " . $lines));
                $test = false;
            }
            if (!is_year($member->per_BirthYear) && $member->per_BirthYear != '0000' && $member->per_BirthYear != '') {
                display_error(_("Invalid birth year On line " . $lines));
                $test = false;
            }
            $csv_lines[] = $data;
        }

        if ($test) {
            $lines = 0;
            foreach ($csv_lines as $data) {
                if ($lines++ == 0)
                    continue;
                $member = new Member();
                list($member->per_Title, $member->per_FirstName, $member->per_LastName, $member->per_Gender, $member->per_BirthMonth, $member->per_BirthDay, $member->per_BirthYear, $member->per_MembershipDate, $member->per_Address1, $member->per_HomePhone, $member->per_Email, $member_Group, $member->per_Status) = $data;
                foreach(explode(',', $member_Group) as $grp){
                    $member->per_Group[] = get_group_id($grp);
                }
                if (!write_member($member)) {
                    $test = FALSE;
                }
            }
        }
        @fclose($fp);

        if ($test) {
            display_notification('Members have been imported successfully');
        }
    } else
        display_error("No CSV file selected");
}  


start_form(true);

start_table(TABLESTYLE2, "width=40%");
if (!isset($_POST['sep']))
    $_POST['sep'] = ",";
text_row("Field separator:", 'sep', $_POST['sep'], 2, 1);
label_row("CSV Import File:", "<input type='file' id='imp' name='imp'>");

end_table(1);

submit_center_first('import', "Import CSV File");

submit_center_last('download_csv', "Export Sample CSV File");

end_form();

end_page();
