<?php
// save_biometrics.php
header('Content-Type: application/json');
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$guestId = $input['guest_id'] ?? 0;
$imageData = $input['image'] ?? '';

if (empty($guestId) || empty($imageData)) {
    echo json_encode(['status' => 'error', 'message' => 'Missing data']);
    exit;
}

// Odkoduj obraz
$imageData = str_replace('data:image/png;base64,', '', $imageData);
$imageData = str_replace(' ', '+', $imageData);
$imageBytes = base64_decode($imageData);

if ($imageBytes === false) {
    echo json_encode(['status' => 'error', 'message' => 'Image decode failed']);
    exit;
}

$fileName = 'biometric_' . $guestId . '_' . time() . '.png';
$uploadDir = 'uploads/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}
$filePath = $uploadDir . $fileName;

if (file_put_contents($filePath, $imageBytes)) {
    try {
        $stmt = $pdo->prepare("UPDATE guests SET photo_path = ?, access_granted_at = NOW() WHERE id = ?");
        $stmt->execute([$filePath, $guestId]);
        echo json_encode(['status' => 'success', 'message' => 'Biometrics saved']);
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => 'Database update failed']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'File save failed']);
}
?>