<?php
session_start();
require_once '../Config/Database.php';
require_once '../Model/Login.php';
$login = new Login();

if(isset($_POST['auth'])){
    $username = $_POST['username'];
    $password = md5($_POST['password']);
    $success = $login->auth($username,$password);
    $login_id = $success[0]['login_id'];
    $is_first_time = $success[0]['is_first_time'];
    $employee_name = $success[0]['employee_name'];
    $employee_email = $success[0]['employee_email'];
    $employee_phone = $success[0]['employee_phone'];
    $role_id = $success[0]['role_id'];
    $role_name = $success[0]['role_name'];
    if($success){
        $_SESSION['login_id'] = $login_id;
        $_SESSION['employee_id'] = $success[0]['employee_id'];
        $_SESSION['employee_name'] = $employee_name;
        $_SESSION['employee_email'] = $employee_email;
        $_SESSION['employee_phone'] = $employee_phone;
        $_SESSION['employee_gender'] = $success[0]['employee_gender'];
        $_SESSION['employee_picture'] = $success[0]['employee_picture'];
        $_SESSION['role_id'] = $role_id;
        $_SESSION['is_first_time'] = $is_first_time;
        
        $_SESSION['role_name'] = $role_name;
        
        echo json_encode(
            array('data'=>'success',
                  'is_first_time'=>$is_first_time
            )
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}

if(isset($_POST['change_password'])){
    $old_password = md5($_POST['old_password']);
    $new_password = $_POST['new_password'];
    $confirm_new_password = $_POST['confirm_new_password'];
    if($new_password!=$confirm_new_password){
        echo json_encode(
            array("data"=>"no_match")
        );
        return;
    }
    $exists = $login->auth($_SESSION['employee_email'],$old_password);
    if(!$exists){
        echo json_encode(
            array("data"=>"wrong_old_password")
        );
        return;
    }
    $data = array(
        "password"=>md5($new_password)
    );
    $key = array(
        "login_id"=>$_SESSION['login_id']
    );
    $success = $login->update_login($key,$data);
    if($success){
        $values = array(
            "is_first_time"=>"No"
        );
        $key = array(
            "email"=>$_SESSION['employee_email']
        );
        $login->update_login($key,$values);
        $_SESSION['is_first_time'] = "No";
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}

if(isset($_POST['recovery'])){
    $username = $_POST['username'];
    $success = $login->check_username($username);
    if($success){
        $login_id = $success[0]['login_id'];
        $employee_name = $success[0]['employee_name'];
        $employee_email = $success[0]['employee_email'];
        $employee_phone = $success[0]['employee_phone'];
        $new_password = implode('',str_split(rand(1000,9999),4));
        $db_password = md5($new_password);
        $data = array(
            "password"=>$db_password,
            "passcode"=>$new_password,
            "is_first_time"=>"Yes"
        );
        $key = array(
            "login_id"=>$login_id
        );
        $success = $login->update_login($key,$data);
        //Send password via email
        $subject = "Don Publications | Password Recovery";
        $msgBody = 	"Hello $employee_name, your requested new password is $new_password. Kindly change it after login.";
        require '../mailer/PHPMailerAutoload.php';
        date_default_timezone_set('Africa/Accra');
        $mail = new PHPMailer;
        //$mail->SMTPDebug = 3;
        $mail->isSMTP();                                      // Set mailer to use SMTP
        $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
        $mail->SMTPAuth = true;                               // Enable SMTP authentication
        $mail->Username = 'millsabeiku2@gmail.com';                 // SMTP username
        $mail->Password = 'Abeiku0555733180@';                           // SMTP password
        $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
        $mail->Port = 587;
            //Set who the message is to be sent from
        $mail->setFrom('millsabeiku2@gmail.com', 'Don Publications');
        //Set an alternative reply-to address
        $mail->addReplyTo('noreply@gmail.com', 'Don Publications');
        //Set who the message is to be sent to
        $mail->addAddress($employee_email,$employee_name);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $msgBody;
        $mail->AltBody = 'This is a mail from Don Publications.';
        $mail->send();

        //Send password via phone
        try{
            $response = @file_get_contents("https://sms.arkesel.com/sms/api?action=send-sms&api_key=OnY5d2pCMk1UdEV4YjhjYXY=&to=$employee_phone&from=Don&sms=$msgBody");
             if($response===FALSE){
                $networkIssue = true;
             }
            // set_error_handler(Exception("Database Connection Failed"),0);
        }catch(Error $e){
            
        }   


        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}