<?php
declare(strict_types = 1);

/**
 * Capture d'image des vidéos.
 *
 * @license https://www.gnu.org/licenses/gpl-3.0.html
 * @link https://www.igalerie.org/
 */
require_once(__DIR__ . '/includes/prepend.php');

$data = json_decode(file_get_contents('php://input'), TRUE);
if ($data)
{
	$_POST = $data;
}
$_POST = array_map('strval', $_POST);

// Vérification du format des paramètres.
if (!isset($_POST['data'])
 || !Utility::checkPost('hash', '`^[a-f0-9]{32}$`')
 || !Utility::checkPost('duration', '`^\d{1,5}$`')
 || !Utility::checkPost('height', '`^\d{1,4}$`')
 || !Utility::checkPost('id', '`^p?\d{1,12}$`')
 || !Utility::checkPost('key', '`^[a-f0-9]{32}$`')
 || !Utility::checkPost('width', '`^\d{1,4}$`'))
{
	die(App::httpResponse(400));
}

// Vérification de la clé de sécurité.
if (!Security::fileKeyVerify([$_POST['id']], $_POST['key']))
{
	die(App::httpResponse(403));
}

// Création du fichier.
$capture = GALLERY_ROOT . '/cache/captures/' . $_POST['id'] . '-' . $_POST['hash'] . '.jpg';
File::putContents($capture, base64_decode((string) $_POST['data']));

// Mise à jour de la base de données.
if (DB::connect())
{
	if ($_POST['id'][0] == 'p')
	{
		$table = "items_pending";
		$prefix = "pending";
		$id = substr($_POST['id'], 1);
	}
	else
	{
		$table = "items";
		$prefix = "item";
		$id = $_POST['id'];
	}
	$sql = "UPDATE {{$table}}
			   SET {$prefix}_height = :height,
				   {$prefix}_width = :width,
				   {$prefix}_duration = :duration
			 WHERE {$prefix}_id = :id";
	DB::execute($sql,
	[
		'duration' => $_POST['duration'],
		'height' => $_POST['height'],
		'id' => $id,
		'width' => $_POST['width']
	]);
}

die(json_encode(['success' => 1]));
?>