<?php
/**
 * Admin - Subscription Bulk Actions
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

$action = $_POST['action'] ?? '';
$ids = $_POST['ids'] ?? [];

if (empty($ids)) {
    redirect(BASE_URL . 'admin/subscriptions.php', 'error', 'No subscriptions selected');
}

if (!in_array($action, ['activate', 'suspend', 'delete'])) {
    redirect(BASE_URL . 'admin/subscriptions.php', 'error', 'Invalid action');
}

// Sanitize IDs
$ids = array_map('intval', $ids);
$id_list = implode(',', $ids);

try {
    switch ($action) {
        case 'activate':
            $stmt = db()->prepare("UPDATE user_subscriptions SET status = 'active', updated_at = NOW() WHERE id IN ($id_list)");
            $stmt->execute();
            log_activity('subscriptions_activated', "Activated subscriptions: $id_list", $_SESSION['admin_id'], 'admin');
            redirect(BASE_URL . 'admin/subscriptions.php', 'success', count($ids) . ' subscription(s) activated successfully');
            break;
            
        case 'suspend':
            $stmt = db()->prepare("UPDATE user_subscriptions SET status = 'suspended', updated_at = NOW() WHERE id IN ($id_list)");
            $stmt->execute();
            log_activity('subscriptions_suspended', "Suspended subscriptions: $id_list", $_SESSION['admin_id'], 'admin');
            redirect(BASE_URL . 'admin/subscriptions.php', 'success', count($ids) . ' subscription(s) suspended successfully');
            break;
            
        case 'delete':
            // First delete related transactions
            $stmt = db()->prepare("DELETE FROM transactions WHERE item_id IN ($id_list) AND item_type = 'subscription_plan'");
            $stmt->execute();
            
            // Then delete subscriptions
            $stmt = db()->prepare("DELETE FROM user_subscriptions WHERE id IN ($id_list)");
            $stmt->execute();
            
            log_activity('subscriptions_deleted', "Deleted subscriptions: $id_list", $_SESSION['admin_id'], 'admin');
            redirect(BASE_URL . 'admin/subscriptions.php', 'success', count($ids) . ' subscription(s) deleted successfully');
            break;
    }
} catch (PDOException $e) {
    error_log("Bulk action error: " . $e->getMessage());
    redirect(BASE_URL . 'admin/subscriptions.php', 'error', 'Action failed. Please try again.');
}
