<?php
/**
 * Media Management AJAX Handler
 * Handles image and video deletion requests
 */

require_once __DIR__ . '/../includes/functions.php';

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

// Check if user is admin
if (!isLoggedIn() || !isAdmin()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$action = $_POST['action'] ?? '';
$id = intval($_POST['id'] ?? 0);

if (!$id) {
    echo json_encode(['success' => false, 'message' => 'Invalid ID']);
    exit;
}

switch ($action) {
    case 'delete_image':
        if (deletePackageImage($id)) {
            echo json_encode(['success' => true, 'message' => 'Image deleted successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to delete image']);
        }
        break;
        
    case 'delete_video':
        if (deletePackageVideo($id)) {
            echo json_encode(['success' => true, 'message' => 'Video deleted successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to delete video']);
        }
        break;
        
    case 'set_primary_image':
        // First, unset all primary images for this package
        $db = getDBConnection();
        
        // Get the image to find its package_id
        $stmt = $db->prepare("SELECT package_id, image FROM package_images WHERE id = ?");
        $stmt->execute([$id]);
        $image = $stmt->fetch();
        
        if ($image) {
            // Unset all primary images for this package
            $db->prepare("UPDATE package_images SET is_primary = 0 WHERE package_id = ?")->execute([$image['package_id']]);
            
            // Set this image as primary
            $db->prepare("UPDATE package_images SET is_primary = 1 WHERE id = ?")->execute([$id]);
            
            echo json_encode(['success' => true, 'message' => 'Primary image updated']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Image not found']);
        }
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
}
