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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(BASE_URL . 'admin/plans.php', 'error', 'Invalid request');
}

if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
    redirect(BASE_URL . 'admin/plans.php', 'error', 'Invalid security token');
}

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

if (!$plan_id) {
    redirect(BASE_URL . 'admin/plans.php', 'error', 'Invalid plan ID');
}

try {
    // Check if plan exists
    $stmt = db()->prepare("SELECT name FROM subscription_plans WHERE id = ?");
    $stmt->execute([$plan_id]);
    $plan = $stmt->fetch();
    
    if (!$plan) {
        redirect(BASE_URL . 'admin/plans.php', 'error', 'Plan not found');
    }
    
    // Check if plan has active subscriptions
    $stmt = db()->prepare("SELECT COUNT(*) as count FROM user_subscriptions WHERE plan_id = ? AND status = 'active'");
    $stmt->execute([$plan_id]);
    $active_subscriptions = $stmt->fetch()['count'];
    
    if ($active_subscriptions > 0) {
        redirect(BASE_URL . 'admin/plans.php', 'error', 'Cannot delete plan with active subscriptions');
    }
    
    // Delete plan
    db()->beginTransaction();
    
    // Delete any inactive subscriptions for this plan
    $stmt = db()->prepare("DELETE FROM user_subscriptions WHERE plan_id = ?");
    $stmt->execute([$plan_id]);
    
    // Delete the plan
    $stmt = db()->prepare("DELETE FROM subscription_plans WHERE id = ?");
    $stmt->execute([$plan_id]);
    
    db()->commit();
    
    // Log activity
    log_activity('plan_deleted', "Deleted plan: {$plan['name']}", $_SESSION['admin_id'], 'admin');
    
    redirect(BASE_URL . 'admin/plans.php', 'success', 'Plan deleted successfully');
    
} catch (PDOException $e) {
    db()->rollBack();
    error_log("Delete plan error: " . $e->getMessage());
    redirect(BASE_URL . 'admin/plans.php', 'error', 'Failed to delete plan');
}
