<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Not authorized']);
    exit;
}

require_once '../config/database.php';

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

try {
    // Get all image paths from the database
    $stmt = $pdo->prepare("SELECT 
        ProductImage, 
        AlternativeImage1, 
        AlternativeImage2, 
        AlternativeImage3 
        FROM {$tables['products']}");
    $stmt->execute();
    $usedImages = [];
    
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        foreach ($row as $image) {
            if (!empty($image)) {
                $usedImages[] = $image;
            }
        }
    }
    
    // Get all files in the uploads/products directory
    $uploadDir = '../uploads/products/';
    $allFiles = scandir($uploadDir);
    $deletedCount = 0;
    $errors = [];
    
    foreach ($allFiles as $file) {
        if ($file === '.' || $file === '..') continue;
        
        // If the file is not in the used images array, delete it
        if (!in_array($file, $usedImages)) {
            $filePath = $uploadDir . $file;
            if (unlink($filePath)) {
                $deletedCount++;
            } else {
                $errors[] = "Failed to delete: $file";
            }
        }
    }
    
    echo json_encode([
        'success' => true,
        'message' => "Cleanup completed. Deleted $deletedCount unused images.",
        'deleted_count' => $deletedCount,
        'errors' => $errors
    ]);
    
} catch (Exception $e) {
    error_log("Image cleanup error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred during cleanup',
        'error' => $e->getMessage()
    ]);
}
?> 