<?php

require_once __DIR__.'/../../../../main/inc/global.inc.php';

if (api_is_anonymous()) {
    echo "error anonymous";
    exit;
}

$typec = isset($_GET['typec']) ? $_GET['typec'] : '';
$lpid = isset($_GET['lpid']) ? $_GET['lpid'] : 0;
$item_id = isset($_GET['id']) ? $_GET['id'] : 0;
$id_session = isset($_GET['id_session']) ? $_GET['id_session'] : 0;
$cidReq = isset($_GET['cidReq']) ? $_GET['cidReq'] : 0;
$user_id = api_get_user_id();
$path = '';

$sql_item = "SELECT c_document.path as pathitem FROM c_lp_item
INNER JOIN c_document ON c_document.id = c_lp_item.path 
WHERE c_lp_item.id = $item_id ";

$result_item = Database::query($sql_item);
if ($rowItem = Database::fetch_array($result_item)) {
    $path = $rowItem['pathitem'];
}
$sql = " SELECT id
    FROM plugin_chamidoc_state
    WHERE user_id = $user_id
    AND lp_id = $lpid AND item_id = $item_id
    AND id_session = $id_session
    AND code LIKE '$cidReq' ";
$result = Database::query($sql);

if ($row = Database::fetch_array($result)) {
    $sqlU = " UPDATE plugin_chamidoc_state
        SET creation_date = NOW(),
        path_file = '$path' 
        WHERE id = ".$row['id'];
    Database::query($sqlU);
} else {
    $sqlInsert = " INSERT INTO plugin_chamidoc_state
        (typec,user_id, lp_id, item_id, c_id, code, creation_date, id_session, path_file)
        VALUES ('$typec',$user_id, $lpid, $item_id, 0, '$cidReq', NOW(), $id_session, '$path')";
    Database::query($sqlInsert);
}

// control 
