<?php
//@session_start();
/**
 * Created by PhpStorm.
 * User: IOAN
 * Date: 11/16/2015
 * Time: 1:49 PM
 */

//echo '<pre>', var_export($_POST, true), '</pre>';

require_once(dirname(__FILE__) . "/../../adbcon.php");
ob_start();
$ret = array(
    "result" => 0,
    "error" => array(),
    "session" => isset($_POST['session']) ? $_POST['session'] : array()
);

$action = isset($_POST['action']) ? trim($_POST['action']) : "login";
$baseurl = trim($_POST['baseurl']);

if ($action=="login") {

    $log_username = isset($_POST['log_username']) ? trim($_POST['log_username']) : '';
    $log_password = isset($_POST['log_password']) ? trim($_POST['log_password']) : '';

    if (!filter_var($log_username, FILTER_VALIDATE_EMAIL)) {
        $ret['error'][] = "Please enter your email address.";
    }

    if($log_username == '') {
        $ret['error'][] = "Please enter your email address.";
    }
    if($log_password == '') {
        $ret['error'][] = "Please enter your password.";
    }

    if ($log_username != '' && $log_password != ''){
        $log_username = mysql_real_escape_string(stripslashes($log_username));
        $log_password = mysql_real_escape_string(stripslashes($log_password));
        $query = "SELECT * FROM members WHERE shipmail = '$log_username' AND password = '$log_password' and kind_ind!='3'";
        //echo "<br/>".$query;
        $result = mysql_query($query);
        $NumberOfFields = mysql_num_rows($result);
        if ($NumberOfFields > 0){
            $rline = mysql_fetch_assoc($result);
            $line = array_map('stripslashes', $rline);
            //$logged=$username;
            //session_register('logged');
            $member_id = $line["member_id"];
            $ret['session']['member_id'] = $member_id;
            $ret['session']['member_fullname'] = trim($line['shipname'] . ' ' . $line['shipsurname']);

            $_SESSION['member_id'] = $member_id;
            $_SESSION['member_fullname'] = trim($line['shipname'] . ' ' . $line['shipsurname']);

            $query = "UPDATE members SET logged=SYSDATE(), confirmed='yes' WHERE member_id='{$line['member_id']}'";
            $result = @mysql_query($query);

            $ret['result'] = 1;
            $ret['link'] = $baseurl . "/account/my_account";
            if(isset($ret['session']['requested_url'])) {
                $ret['link'] = $ret['session']['requested_url'];
            }

        }
        else{
            $ret['error'][] = "The email address and/or the password are wrong.";
        }
    }

}

if(count($ret['error']) > 0) {
    $ret['error'] = implode("<br>", $ret['error']);
}

$log = ob_get_contents();
ob_end_clean();

$ret['log'] = $log;

echo json_encode($ret);
exit();