<?php

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

// ================= CONFIG =================
$baseDir = __DIR__ . "/uploads/";
$baseUrl = "https://poskita.ajhotelsystem.com/api/uploads/";

// ================= AMBIL STORE ID =================
$storeId = isset($_POST['store_id']) ? $_POST['store_id'] : null;

if (!$storeId) {
    echo json_encode([
        "success" => false,
        "message" => "store_id wajib"
    ]);
    exit;
}

// 🔥 sanitasi (WAJIB BIAR AMAN)
$storeId = preg_replace('/[^a-zA-Z0-9_-]/', '', $storeId);

// ================= VALIDASI FILE =================
if (!isset($_FILES['photo'])) {
    echo json_encode([
        "success" => false,
        "message" => "File tidak ditemukan"
    ]);
    exit;
}

$file = $_FILES['photo'];

// ================= VALIDASI DASAR =================
$maxFileSize = 2 * 1024 * 1024; // 2MB

if ($file['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(["success" => false, "message" => "Upload gagal"]);
    exit;
}

if ($file['size'] > $maxFileSize) {
    echo json_encode(["success" => false, "message" => "File terlalu besar"]);
    exit;
}

// ================= CEK GAMBAR VALID =================
$info = getimagesize($file['tmp_name']);
if ($info === false) {
    echo json_encode([
        "success" => false,
        "message" => "File bukan gambar valid"
    ]);
    exit;
}

// ================= EXTENSION =================
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$allowed = ['jpg','jpeg','png','webp'];

if (!in_array($ext, $allowed)) {
    echo json_encode([
        "success" => false,
        "message" => "Format tidak diizinkan"
    ]);
    exit;
}

// ================= BUAT FOLDER PER STORE =================
$storeFolder = $baseDir . "store_" . $storeId . "/";

if (!is_dir($storeFolder)) {
    mkdir($storeFolder, 0755, true);
}

// ================= RENAME FILE =================
$filename = bin2hex(random_bytes(16)) . "." . $ext;

$targetPath = $storeFolder . $filename;

// ================= SIMPAN =================
if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
    echo json_encode([
        "success" => false,
        "message" => "Gagal simpan file"
    ]);
    exit;
}

// ================= RESPONSE =================
echo json_encode([
    "success" => true,
    "url" => $baseUrl . "store_" . $storeId . "/" . $filename
]);