<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';
require_once __DIR__ . '/../../core/Logger.php';

$db = Database::getInstance();

/**
 * ----------------------------
 * Method check
 * ----------------------------
 */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Response::error('Invalid request method', 405);
}

/**
 * ----------------------------
 * Validate input
 * ----------------------------
 */
$offerId = (int) ($_POST['id'] ?? 0);
if ($offerId <= 0) {
    Response::error('Offer ID is required', 422);
}

/**
 * ----------------------------
 * Fetch offer (for image paths)
 * ----------------------------
 */
$stmt = $db->prepare("
    SELECT desktop_image, mobile_image
    FROM offers
    WHERE id = :id AND deleted_at IS NULL
");
$stmt->execute(['id' => $offerId]);

$offer = $stmt->fetch();
if (!$offer) {
    Response::error('Offer not found', 404);
}

/**
 * ----------------------------
 * Resolve filesystem paths
 * ----------------------------
 */
function resolveFilePath(?string $url): ?string
{
    if (!$url) {
        return null;
    }

    // Remove BASE_URL from public URL
    $relativePath = str_replace(BASE_URL, '', $url);
    return BASE_PATH . $relativePath;
}

$desktopPath = resolveFilePath($offer['desktop_image']);
$mobilePath  = resolveFilePath($offer['mobile_image']);

/**
 * ----------------------------
 * Soft delete DB record
 * ----------------------------
 */
try {
    $stmt = $db->prepare("
        UPDATE offers
        SET deleted_at = NOW(),
            status = 'inactive'
        WHERE id = :id
    ");
    $stmt->execute(['id' => $offerId]);
} catch (Throwable $e) {
    Logger::error('Offer delete DB failed', ['error' => $e->getMessage()]);
    Response::error('Failed to delete offer', 500);
}

/**
 * ----------------------------
 * Image cleanup (non-fatal)
 * ----------------------------
 */
foreach ([$desktopPath, $mobilePath] as $path) {
    if ($path && file_exists($path)) {
        if (!unlink($path)) {
            Logger::error('Offer image delete failed', [
                'offer_id' => $offerId,
                'path'     => $path
            ]);
        }
    }
}

/**
 * ----------------------------
 * Response
 * ----------------------------
 */
Logger::auth('Offer deleted with images', [
    'offer_id' => $offerId,
    'by'       => $_SESSION['employee_id']
]);

Response::success('Offer deleted successfully');
