<?php
$restaurantId = basename($_GET['rid'] ?? '');
$filename     = basename($_GET['filename'] ?? '');
$uploadDir    = __DIR__ . "/images/$restaurantId/";
$logFile      = __DIR__ . "/upload-log.txt";

function log_msg($msg) {
  global $logFile;
  file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] $msg\n", FILE_APPEND);
}

if (!preg_match('/^[a-zA-Z0-9_-]+$/', $restaurantId) || !$filename) {
  http_response_code(400);
  log_msg("Invalid input: $restaurantId / $filename");
  echo "Invalid input.";
  exit;
}
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
  http_response_code(400);
  log_msg("Upload error.");
  echo "Upload error.";
  exit;
}
if (!file_exists($uploadDir)) {
  mkdir($uploadDir, 0777, true);
}
$tmpPath = $_FILES['file']['tmp_name'];
$targetPath = $uploadDir . $filename;

function resizeImage($src, $dest, $maxDim = 600) {
  [$w, $h, $type] = getimagesize($src);
  $ratio = $w / $h;
  if ($w > $h) {
    $newW = $maxDim;
    $newH = $maxDim / $ratio;
  } else {
    $newH = $maxDim;
    $newW = $maxDim * $ratio;
  }
  switch ($type) {
    case IMAGETYPE_JPEG: $srcImg = imagecreatefromjpeg($src); break;
    case IMAGETYPE_PNG:  $srcImg = imagecreatefrompng($src); break;
    case IMAGETYPE_WEBP: $srcImg = imagecreatefromwebp($src); break;
    default: return false;
  }
  $dstImg = imagecreatetruecolor($newW, $newH);
  imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $newW, $newH, $w, $h);
  switch ($type) {
    case IMAGETYPE_JPEG: imagejpeg($dstImg, $dest, 85); break;
    case IMAGETYPE_PNG:  imagepng($dstImg, $dest); break;
    case IMAGETYPE_WEBP: imagewebp($dstImg, $dest, 85); break;
  }
  imagedestroy($srcImg); imagedestroy($dstImg);
  return true;
}

if (!resizeImage($tmpPath, $targetPath)) {
  move_uploaded_file($tmpPath, $targetPath);
}
log_msg("Uploaded: $filename");
echo "OK";
?>