<?php
require_once dirname(__DIR__) . '/config.php';
require_once 'session_manager.php';

$sessionDetected = detectAndStartUserSession();

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

$input = json_decode(file_get_contents('php://input'), true);

if (!$sessionDetected || !isset($_SESSION['username']) || !isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    echo json_encode(['success' => false, 'message' => 'User not authenticated']);
    exit;
}

if (!isset($input['imagePath'])) {
    echo json_encode(['success' => false, 'message' => 'No image path provided']);
    exit;
}

$username = $_SESSION['username'];
if (strpos($input['imagePath'], $username) === false) {
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

$imagePath = PROJECT_ROOT . '/' . $input['imagePath'];

if (!file_exists($imagePath)) {
    echo json_encode(['success' => false, 'message' => 'Image file not found']);
    exit;
}

if (unlink($imagePath)) {
    echo json_encode(['success' => true, 'message' => 'Image deleted successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to delete image file']);
}
?>