<?php
/**
 * save-qr.php — Helper endpoint to save a base64 QR image server-side
 * and return the short relative file path so it can be passed in a URL.
 *
 * POST params:
 *   b64  : the full data URI (e.g. data:image/jpeg;base64,/9j/...)
 *   ip   : the visitor IP (used as part of the filename key)
 *
 * Returns JSON: { "path": "users/imgs/qr_<hash>.<ext>" }
 */

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    exit;
}

$b64data = isset($_POST['b64']) ? trim($_POST['b64']) : '';
$ip      = isset($_POST['ip'])  ? trim($_POST['ip'])  : 'unknown';

if (empty($b64data) || strpos($b64data, 'data:image/') !== 0) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid or missing b64 parameter']);
    exit;
}

// Detect image extension from MIME type
preg_match('/data:image\/(\w+);base64,/', $b64data, $mimeMatch);
$ext = isset($mimeMatch[1]) ? strtolower($mimeMatch[1]) : 'jpg';
if ($ext === 'jpeg') $ext = 'jpg';

// Strip the data URI header and decode binary
$raw = substr($b64data, strpos($b64data, ',') + 1);
$binary = base64_decode($raw);

if ($binary === false) {
    http_response_code(400);
    echo json_encode(['error' => 'base64 decode failed']);
    exit;
}

// Ensure output directory exists
$dir = 'users/imgs/';
if (!is_dir($dir)) {
    mkdir($dir, 0755, true);
}

// Build a unique filename
$fname = $dir . 'qr_' . md5($ip . microtime()) . '.' . $ext;

if (file_put_contents($fname, $binary) === false) {
    http_response_code(500);
    echo json_encode(['error' => 'Could not write file']);
    exit;
}

echo json_encode(['path' => $fname]);
exit;
