<?php

use Mtc\Cms\Models\PageListItemData;

$cms_root_path = "../../../";
require_once $cms_root_path . "includes/compatibility_includer.php";

header('Content-Type: application/json; charset=utf-8');

// Handy function for outputting json response
function out(array $p, int $code = 200): void
{
    http_response_code($code);
    echo json_encode($p, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
    exit;
}

$id =  (int) $_POST['id'] ?? 0;
$imgSrc  = (string) $_POST['src'] ?? '';
$found = [];

// Check if there is a record for this image on the database
$page_list_item_data = null;
if ($id > 0) {
    $page_list_item_data = PageListItemData::find($id);
    if (!$page_list_item_data) {
        out(['ok' => false, 'message' => 'Image record not found in database.'], 404);
    }
}

/**
 * Delete from the filesystem
 * */
if (isset($imgSrc) && file_exists(SITE_PATH . $imgSrc)) {
    // Check if image_folders is setup for the cms_images
    if (!isset($image_folders['cms_images']) || !is_array($image_folders['cms_images'])) {
        out(['ok' => false, 'message' => 'Server misconfigured: cms_images folders not defined.'], 500);
    }

    // Get the file name and its webp counterpart
    $filename = basename($imgSrc);
    $webpFile = preg_replace('/\.\w+$/', '.webp', $filename);

    // loop to see if it exists in any other directory
    foreach ($image_folders['cms_images'] as $image_folder) {
        if (file_exists(SITE_PATH . '/' . $image_folder['path'] . '/' . $filename)) {
            $found[] = ($image_folder['path'] . '/' . $filename);
            unlink(SITE_PATH . '/' . $image_folder['path'] . '/' . $filename);
        }

        if (file_exists(SITE_PATH . '/' . $image_folder['path'] . '/' . $webpFile)) {
            $found[] = ($image_folder['path'] . '/' . $webpFile);
            unlink(SITE_PATH . '/' . $image_folder['path'] . '/' . $webpFile);
        }
    }

    // Clear database value if the record exists
    if ($page_list_item_data && $page_list_item_data->value) {
        $page_list_item_data->value = '';
        $page_list_item_data->save();
    }

    if (count($found) > 0) {
        // if files were found and deleted, return a json response with the following message.
        out([
            'ok' => true,
            'files' => $found,
            'message' => 'Deleted files: ' . implode(', ', $found) . '.'
        ]);
    }
} else {
    // If the image source was set but no file exists at that path, return an error
    out([
        'ok' => false,
        'message' => 'No files were found at provided destination.',
        404
    ]);
}
