<?php
// remove_image.php - Deletes a media file and its database record

// --- Show all errors for easier debugging ---
ini_set('display_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');

// --- 1. INCLUDE DATABASE CONNECTION ---
require_once 'db_connect.php'; 

// --- 2. VALIDATE INPUT FROM APP ---
if (!isset($_POST['image_url']) || empty($_POST['image_url'])) {
    die(json_encode(['status' => 'error', 'message' => 'Image URL is missing.']));
}
$imageUrl = $_POST['image_url'];

// --- 3. DELETE THE PHYSICAL FILE FROM THE SERVER ---
$fileDeletedOnServer = false;

$urlPath = parse_url($imageUrl, PHP_URL_PATH);
$serverFilePath = $_SERVER['DOCUMENT_ROOT'] . $urlPath;
$serverFilePath = realpath($serverFilePath); 

if ($serverFilePath && file_exists($serverFilePath)) {
    if (strpos($serverFilePath, 'uploads') !== false) {
        if (unlink($serverFilePath)) {
            $fileDeletedOnServer = true;
        } else {
            die(json_encode(['status' => 'error', 'message' => 'File System Error: Could not delete the image file. Please check server folder permissions.']));
        }
    } else {
        die(json_encode(['status' => 'error', 'message' => 'Security Error: File path is outside the allowed directory.']));
    }
} else {
    $fileDeletedOnServer = true;
}


// --- 4. DELETE THE RECORD FROM THE DATABASE ---
if ($fileDeletedOnServer) {
    try {
        $sql = "DELETE FROM media WHERE image_url = ?";
        $stmt = $pdo->prepare($sql);

        if ($stmt->execute([$imageUrl])) {
            if ($stmt->rowCount() > 0) {
                echo json_encode(['status' => 'success', 'message' => 'Image deleted successfully.']);
            } else {
                echo json_encode(['status' => 'success', 'message' => 'File deleted, but no corresponding database record was found.']);
            }
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $e->getMessage()]);
    }
}
?>