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

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

//var_dump($data);

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

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

try 
{
    $stmt = $conn->prepare("SELECT * FROM `dogs` WHERE `pwtoken`=?");
    $stmt->execute([$pwtoken]); 

    if($stmt->rowCount())
    {
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $expire = new DateTime($row['pwt_time']);
        $expire->add(new DateInterval('PT' . $G_pwtoken_time_expire . 'M'));
//        var_dump($expire);
        $now = new DateTime();
//        var_dump($now);
        if($now > $expire)
        {
            $null_var = null;
            $sql = "UPDATE dogs SET pwtoken=?, pwt_time=? WHERE id=?";
            $conn->prepare($sql)->execute([$null_var, $null_var, $row['id']]);
        
            $returnData = new CMsg(
                0,
                200,
                'Passwordtoken: '. $pwtoken . ' time expired!',
                null,
                $row
            );
    
        }
        else
        {
            $returnData = new CMsg(
                1,
                200,
                'Passwordtoken: '. $pwtoken . ' valid!',
                null,
                $row
            );
        }
    }
    else
    {
        $returnData = new CMsg(
            0,
            406,
            'Passwordtoken: '. $pwtoken . ' not valid, nothing changed!'
        );

    }
} 
catch(PDOException $e)
{
    $returnData = new CMsg(0,500,$e->getMessage());
}

echo $returnData->jsonarray();
?>