<?php

require '../vendor/autoload.php';

use Dotenv\Dotenv;

// Load the .env file
$dotenv = Dotenv::createImmutable(__DIR__ . "/../");
$dotenv->load();

$CLOUDINARY_NAME = $_ENV['CLOUDINARY_NAME'];
$CLOUDINARY_KEY = $_ENV['CLOUDINARY_KEY'];
$CLOUDINARY_SECRET = $_ENV['CLOUDINARY_SECRET'];

// Use the Configuration class 
use Cloudinary\Configuration\Configuration;

// Use the UploadApi class for uploading assets
use Cloudinary\Api\Upload\UploadApi;

// Use the AdminApi class for uploading assets
use Cloudinary\Api\Admin\AdminApi;

// Global config: Affects all usage of Cloudinary SDK globally
Configuration::instance([
    'cloud' => [
        'cloud_name' => $CLOUDINARY_NAME,
        'api_key'    => $CLOUDINARY_KEY,
        'api_secret' => $CLOUDINARY_SECRET
    ],
    'url' => [
        'secure' => true
    ]
]);

function fnUploadToCloudinary(
    string $sourceFilePath,
    string $saveToFolder = 'evosyspos/default',
    string $resourceType = 'auto',
    string $fileName = "",
    string $oldFileToDelete = ""
) {
    $upload = new UploadApi();
    $admin  = new AdminApi();

    if (!empty($oldFileToDelete)) {

        // 1. Extract public_id safely
        $path = parse_url($oldFileToDelete, PHP_URL_PATH);

        // Remove everything before and including /upload/
        $publicId = preg_replace('#^.*/upload/(v\d+/)?#', '', $path);

        // Remove extension
        $publicId = preg_replace('/\.[^.]+$/', '', $publicId);

        // 2. Delete existing image (MUST be image)
        try {
            $admin->asset($publicId, ['resource_type' => $resourceType]);

            $upload->destroy($publicId, [
                'resource_type' => $resourceType,
                'invalidate'    => true
            ]);
        } catch (\Exception $e) {
            // Asset does not exist — safe to continue
        }
    }

    if (empty($fileName)) {
        $fileName = uniqid();
    }

    // RESOURCE TYPES
    // Images → image
    // PDFs / docs → raw
    // Videos → video

    // 3. Upload new file
    return $upload->upload($sourceFilePath, [
        'resource_type' => $resourceType,
        'folder'        => $saveToFolder,
        'public_id'     => $fileName,
        'use_filename'  => true,
        'overwrite'     => true
    ]);
}
