<?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 {
    // First, get all image paths from the products_req table
    $stmt = $pdo->prepare("SELECT id, product_name, product_image_url FROM {$tables['product_requests']}");
    $stmt->execute();
    $usedImages = [];
    $databaseImages = [];
    
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        if (!empty($row['product_image_url'])) {
            $databaseImages[] = [
                'id' => $row['id'],
                'name' => $row['product_name'],
                'image_url' => $row['product_image_url']
            ];
            
            if (!str_starts_with($row['product_image_url'], 'http')) {
                // Extract filename from the path (remove 'uploads/requests/' prefix if present)
                $filename = basename($row['product_image_url']);
                if (strpos($row['product_image_url'], 'uploads/requests/') === 0) {
                    $filename = basename($row['product_image_url']);
                }
                $usedImages[] = $filename;
            }
        }
    }
    
    // Get all files in the uploads/requests directory
    $uploadDir = '../uploads/requests/';
    if (!file_exists($uploadDir)) {
        echo json_encode([
            'success' => false,
            'message' => "Uploads/requests directory not found.",
            'database_images' => $databaseImages,
            'deleted_count' => 0,
            'errors' => []
        ]);
        exit;
    }

    $allFiles = scandir($uploadDir);
    $deletedCount = 0;
    $errors = [];
    $unusedFiles = [];
    
    foreach ($allFiles as $file) {
        if ($file === '.' || $file === '..') continue;
        
        // If the file is not in the used images array, it's unused
        if (!in_array($file, $usedImages)) {
            $unusedFiles[] = $file;
            $filePath = $uploadDir . $file;
            if (file_exists($filePath)) {
                if (unlink($filePath)) {
                    $deletedCount++;
                } else {
                    $errors[] = "Failed to delete: $file (Path: $filePath)";
                }
            } else {
                $errors[] = "File not found: $file (Path: $filePath)";
            }
        }
    }
    
    echo json_encode([
        'success' => true,
        'message' => "Cleanup completed. Deleted $deletedCount unused request images.",
        'database_images' => $databaseImages,
        'used_images' => $usedImages,
        'unused_files' => $unusedFiles,
        'deleted_count' => $deletedCount,
        'errors' => $errors
    ]);
    
} catch (Exception $e) {
    error_log("Request image cleanup error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred during cleanup',
        'error' => $e->getMessage()
    ]);
}
?> 