<?php
// error_reporting(E_ALL);
// ini_set("display_errors", 1);



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();

//var_dump($_POST);

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

if(
    !isset($_POST['password1']) 
    || !isset($_POST['id']) 
    || empty(trim($_POST['password1']))
    || empty(trim($_POST['id']))
    )
{
    $fields = ['fields' => ['password','passwordToken','id']];
    $returnData = new CMsg(0,422,'Please Fill in all Required Fields!',$fields);
    echo $returnData->jsonarray();
    return;
}


$password = $_POST['password1'];
$id = $_POST['id'];
if (strlen($password) < 8)
{
    $returnData = new CMsg(0, 422, 'Your password must be at least 8 characters long!');
    echo $returnData->jsonarray();
    return;
} 

$pwcrypt = password_hash($password, PASSWORD_DEFAULT);
$null_var = null;
try
{
    $sql = "UPDATE dogs SET password=?, pwtoken=?, pwt_time=? WHERE id=?";
    $conn->prepare($sql)->execute([$pwcrypt, $null_var, $null_var, $id]);
    $returnData = new CMsg(1, 200, 'Password reset successfully!');
}
catch(PDOException $e)
{
    $returnData = new CMsg(0, 500, $e->getMessage() );
}

echo $returnData->jsonarray();
?>