<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: POST");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

session_start();

require __DIR__.'/classes/Database.php';
require __DIR__.'/classes/lib.php';

$db_connection = new Database();
$conn = $db_connection->dbConnection();

$data = json_decode(file_get_contents("php://input"));
// $data = json_decode(
//     '{
//         "email": "a@q.q",
//         "password": "qwertzui"
//     }'
// );
$returnData = new CMsg(0);

//IF REQUEST METHOD IS NOT EQUAL TO POST
if($_SERVER["REQUEST_METHOD"] != "POST")
{
    $returnData = new CMsg(0,404,'Page Not Found! REQUEST_METHOD');
    echo $returnData->jsonarray();
    return;
}

// CHECKING EMPTY FIELDS
if(
    !isset($data->email) 
    || !isset($data->password)
    || empty(trim($data->email))
    || empty(trim($data->password))
    )
{
    $fields = ['fields' => ['email','password']];
    $returnData = new CMsg(0,422,'Please Fill in all Required Fields!',$fields);
    echo $returnData->jsonarray();
    return;
}

// IF THERE ARE NO EMPTY FIELDS THEN-
$email = trim($data->email);
$password = trim($data->password);

if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
    $returnData = new CMsg(0, 422, 'Invalid Email Address!');
    echo $returnData->jsonarray();
    return;
}


// IF PASSWORD IS LESS THAN 8 THE SHOW THE ERROR
if(strlen($password) < 8)
{
    $returnData = new CMsg(0,422,'Your password must be at least 8 characters long!');
    echo $returnData->jsonarray();
    return;
}

// THE USER IS ABLE TO PERFORM THE LOGIN ACTION

try
{
    $fetch_user_by_email = "SELECT id, qr_id, email, password FROM `dogs` WHERE `email`=:email";
    $query_stmt = $conn->prepare($fetch_user_by_email);
    $query_stmt->bindValue(':email', $email,PDO::PARAM_STR);
    $query_stmt->execute();

    // IF THE USER IS FOUNDED BY EMAIL
    if($query_stmt->rowCount())
    {
        $row = $query_stmt->fetch(PDO::FETCH_ASSOC);
        $check_password = password_verify($password, $row['password']);
//        $check_password = $password == $row['password'];

        // VERIFYING THE PASSWORD (IS CORRECT OR NOT?)
        // IF PASSWORD IS CORRECT THEN SEND THE LOGIN TOKEN
        if ($check_password)
        {
            //                    $jwt = new JwtHandler();
            $user = new CUser(  $row['id'], 
                                $row['qr_id'],    
                                $row['email']
            );
//            $_SESSION['user'] = $user;
            $_SESSION['user'] = $user->phparray();
            
            $returnData = new CMsg( 
                1, 
                200, 
                'You have successfully logged in.', 
                $fields, 
                $user);
        }
        // IF INVALID PASSWORD
        else
        {
            $returnData = new CMsg(0,422,'Invalid Password!');
        }

    // IF THE USER IS NOT FOUNDED BY EMAIL THEN SHOW THE FOLLOWING ERROR
    }
    else
    {
        $returnData = new CMsg(0,422,'Invalid Email Address! No Email found!');
    }
}
catch(PDOException $e)
{
    $returnData = new CMsg(0,500,$e->getMessage());
}

echo $returnData->jsonarray();
?>
