<?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->qr_width_cm)
    || !isset($data->qr_height_cm)
    || !isset($data->qr_fontsize)
    || !isset($data->qr_visible_items)
    || !isset($data->qr_item_sequence)
    || empty(trim($data->qr_width_cm))
    || empty(trim($data->qr_height_cm))
    || empty(trim($data->qr_fontsize))
    || empty(trim($data->qr_visible_items))
    || empty(trim($data->qr_item_sequence))
) 
{

    $fields = ['fields' => ['qr_width_cm', 'qr_height_cm', 'qr_fontsize', 'qr_visible_items', 'qr_item_sequence']];
    $returnData = new CMsg(0, 422, 'Please Fill in all Required Fields!', $fields);
    echo $returnData->jsonarray();
    return;
}

// IF THERE ARE NO EMPTY FIELDS THEN-
$qr_width_cm = trim($data->qr_width_cm);
$qr_height_cm = trim($data->qr_height_cm);
$qr_fontsize = trim($data->qr_fontsize);
$qr_visible_items = trim($data->qr_visible_items);
$qr_item_sequence = trim($data->qr_item_sequence);

try 
{
    $update_query =    
"
UPDATE
    `dogs`
SET
    `qr_width_cm` = :qr_width_cm,                          
    `qr_height_cm` = :qr_height_cm,
    `qr_fontsize` = :qr_fontsize,
    `qr_visible_items` = :qr_visible_items,
    `qr_item_sequence` = :qr_item_sequence
WHERE
    `qr_id` = :qr_id";

    $statement = $conn->prepare($update_query);
    $update = $statement->execute(
        array(
            'qr_width_cm' => $qr_width_cm, 
            'qr_height_cm' => $qr_height_cm, 
            'qr_fontsize' => $qr_fontsize, 
            'qr_visible_items' => $qr_visible_items, 
            'qr_item_sequence' => $qr_item_sequence, 
            '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();
?>
