<?php

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Log;

/**
 * Local image storage helpers.
 *
 * Uploaded files are saved under public/uploads/{folderPath}/ on the server,
 * which is served directly by Laravel's public document root. Function names
 * keep the "R2" suffix only because they are referenced from many controllers;
 * the implementation is fully local — no Cloudflare R2 connection required.
 */

function uploadImageR2(UploadedFile $file, string $folderPath, ?string $fileName = null): string
{
    if (!$file->isValid()) {
        throw new InvalidArgumentException("Invalid file provided for upload.");
    }
    if (empty($folderPath)) {
        throw new InvalidArgumentException("Invalid folder path provided.");
    }

    try {
        $destination = public_path("uploads/{$folderPath}");
        if (!is_dir($destination)) {
            if (!mkdir($destination, 0777, true) && !is_dir($destination)) {
                throw new Exception("Failed to create directory: {$destination}");
            }
        }

        $fileName = $fileName ?? uniqid() . '.' . $file->getClientOriginalExtension();
        $file->move($destination, $fileName);

        return $fileName;
    } catch (Exception $e) {
        throw new Exception("File upload failed due to: {$e->getMessage()}");
    }
}

function deleteOldFileR2(string $folderPath, ?string $oldFileName): void
{
    if (!$oldFileName) {
        return;
    }
    // Accept folder paths with or without a leading "speed-net/" prefix
    // for backward compatibility with older controllers.
    $folderPath = preg_replace('#^speed-net/#', '', $folderPath);
    $filePath = public_path("uploads/{$folderPath}/{$oldFileName}");
    if (is_file($filePath) && !@unlink($filePath)) {
        throw new Exception("Failed to delete the old file: {$oldFileName}");
    }
}

function ensureDirectoryExists(string $folderPath): void
{
    $destination = public_path("uploads/{$folderPath}");
    if (!is_dir($destination)) {
        if (!mkdir($destination, 0777, true) && !is_dir($destination)) {
            throw new Exception("Failed to create directory: {$destination}");
        }
    }
}

function storeFile(UploadedFile $file, string $folderPath): string
{
    $destination = public_path("uploads/{$folderPath}");
    if (!is_dir($destination)) {
        mkdir($destination, 0777, true);
    }
    $fileName = uniqid() . '_.' . trim($file->getClientOriginalExtension());
    $file->move($destination, $fileName);
    return $fileName;
}

function getObjUrl($path, $name)
{
    if (empty($name)) {
        return null;
    }
    return asset("uploads/{$path}/{$name}");
}

function deleteImage(string $folderPath, string $fileName): bool
{
    if (empty($folderPath) || empty($fileName)) {
        throw new InvalidArgumentException("Invalid folder path or file name provided.");
    }

    $filePath = public_path("uploads/{$folderPath}/{$fileName}");

    try {
        if (is_file($filePath)) {
            if (!@unlink($filePath)) {
                throw new Exception("Failed to delete the file: {$fileName}");
            }
            return true;
        }
        Log::info("File not found: {$filePath}");
        return false;
    } catch (Exception $e) {
        Log::error("File deletion failed: {$e->getMessage()}");
        throw new Exception("File deletion failed due to: {$e->getMessage()}");
    }
}
