<?php

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

// ================= CONFIG =================
$baseDir = __DIR__ . "/uploads/";

// ================= INPUT =================
$url = $_POST['url'] ?? null;
$storeId = $_POST['store_id'] ?? null;

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

// ================= AMBIL PATH FILE =================
// contoh url:
// https://domain.com/api/uploads/store_1/abc.jpg

$parsed = parse_url($url);
$path = $parsed['path'] ?? '';

// ambil setelah /uploads/
$relativePath = strstr($path, "/uploads/");

if (!$relativePath) {
    echo json_encode([
        "success" => false,
        "message" => "Path tidak valid"
    ]);
    exit;
}

// path full di server
$filePath = __DIR__ . $relativePath;

// ================= VALIDASI STORE =================
if (strpos($filePath, "store_" . $storeId) === false) {
    echo json_encode([
        "success" => false,
        "message" => "Akses ditolak"
    ]);
    exit;
}

// ================= DELETE =================
if (file_exists($filePath)) {
    unlink($filePath);

    echo json_encode([
        "success" => true,
        "message" => "File dihapus"
    ]);
} else {
    echo json_encode([
        "success" => false,
        "message" => "File tidak ditemukan"
    ]);
}