<?php
/**
 * AJAX endpoint for deleting item images
 */

require_once '../app/Core/init.php';

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// Validate CSRF token
if (!Security::validateToken($_POST['csrf_token'] ?? '')) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Invalid security token']);
    exit;
}

// Require vendor authentication
Auth::requireVendor();

// Check if required data is present
if (!isset($_POST['image_id']) || !isset($_POST['image_path'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required data']);
    exit;
}

$image_id = (int)$_POST['image_id'];
$image_path = Security::clean($_POST['image_path']);

try {
    // Initialize models
    $item = new Item();
    $upload = new Upload();
    
    // Get vendor details for ownership verification
    $vendor_id = Auth::id();
    $vendor = new Vendor();
    $vendor_data = $vendor->getByUserId($vendor_id);
    
    if (!$vendor_data) {
        throw new Exception('Vendor profile not found');
    }
    
    // Verify image ownership
    $db = Database::getInstance();
    $sql = "SELECT ii.*, i.vendor_id 
            FROM item_images ii 
            JOIN items i ON ii.item_id = i.id 
            WHERE ii.id = ? AND i.vendor_id = ?";
    $image_data = $db->fetch($sql, [$image_id, $vendor_data['id']]);
    
    if (!$image_data) {
        throw new Exception('Image not found or access denied');
    }
    
    // Delete from database
    $delete_sql = "DELETE FROM item_images WHERE id = ?";
    $delete_result = $db->execute($delete_sql, [$image_id]);
    
    if (!$delete_result) {
        throw new Exception('Failed to delete image from database');
    }
    
    // Delete file from server
    $file_deleted = false;
    if (!empty($image_path)) {
        $file_deleted = $upload->deleteFile('items/' . $image_path);
        
        // If file doesn't exist, still consider it a success
        if (!$file_deleted && !file_exists('../uploads/items/' . $image_path)) {
            $file_deleted = true;
        }
    } else {
        $file_deleted = true;
    }
    
    if ($delete_result && $file_deleted) {
        echo json_encode([
            'success' => true, 
            'message' => 'Image deleted successfully'
        ]);
    } else {
        // Log the issue but still return success since DB record was deleted
        error_log("Image file deletion failed for: " . $image_path);
        echo json_encode([
            'success' => true, 
            'message' => 'Image deleted (file may still exist on server)'
        ]);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'message' => $e->getMessage()
    ]);
}