<?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 FORM REQUEST
$data = json_decode(file_get_contents("php://input"));
$returnData = new CMsg(0);

if ($_SERVER["REQUEST_METHOD"] != "POST") 
{
    $returnData = new CMsg(0, 404, 'Page Not Found! REQUEST_METHOD');
    echo $returnData->jsonarray();
    return;
}

if (!isset($_SESSION["user"])) 
{
    $result = new CMsg(0, 401, "not logged in");
    echo $result->jsonarray();
    return;
}

$user = $_SESSION["user"];

if (
    !isset($data->email)
    || !isset($data->name)
    || !isset($data->phone)
    || empty(trim($data->email))
    || empty(trim($data->name))
    || empty(trim($data->phone))
) 
{

    $fields = ['fields' => ['email', 'name', 'phone']];
    $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);
$name = trim($data->name);
$phone = trim($data->phone);

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

try 
{
    $update_query =    
"
UPDATE
    `dogs`
SET
    `email` = :email,
    `name` = :name,
    `phone` = :phone
WHERE
    `qr_id` = :qr_id";

    $statement = $conn->prepare($update_query);
    $update = $statement->execute(
        array(
            'email' => $email, 
            'name' => $name, 
            'phone' => $phone, 
            'qr_id' => $user["qr_id"]
        ));

    $count = $statement->rowCount();
        
    if ($update && $count > 0) 
    {
        $returnData = new CMsg(1, 201, 'Updated');
    }
    else
    {
        $returnData = new CMsg(0, 304, 'No Update done!');
    }

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

echo $returnData->jsonarray();
?>
