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

$page_title = 'Edit Subscription Plan';
$plan_id = intval($_GET['id'] ?? 0);
$plan = null;
$errors = [];

if ($plan_id) {
    try {
        $stmt = db()->prepare("SELECT * FROM subscription_plans WHERE id = ?");
        $stmt->execute([$plan_id]);
        $plan = $stmt->fetch();
    } catch (PDOException $e) {}
}

if (!$plan) {
    redirect(BASE_URL . 'admin/plans.php', 'error', 'Plan not found');
}

// Parse existing features
$existing_features = [];
if (!empty($plan['features'])) {
    $decoded = json_decode($plan['features'], true);
    if (is_array($decoded)) {
        $existing_features = $decoded;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid security token';
    } else {
        $name = sanitize($_POST['name'] ?? '');
        $description = sanitize($_POST['description'] ?? '');
        $monthly_price = floatval($_POST['monthly_price'] ?? 0);
        $yearly_price = floatval($_POST['yearly_price'] ?? 0);
        $is_featured = isset($_POST['is_featured']) ? 1 : 0;
        $status = isset($_POST['status']) ? 1 : 0;
        
        // Process features
        $features = [];
        if (isset($_POST['features']) && is_array($_POST['features'])) {
            foreach ($_POST['features'] as $feature) {
                $feature = trim($feature);
                if (!empty($feature)) {
                    $features[] = $feature;
                }
            }
        }
        $features_json = json_encode($features);
        
        if (empty($name)) $errors[] = 'Plan name is required';
        
        if (empty($errors)) {
            try {
                $stmt = db()->prepare("UPDATE subscription_plans SET 
                    name = ?, description = ?, monthly_price = ?, yearly_price = ?, 
                    features = ?, is_featured = ?, status = ?, updated_at = NOW() WHERE id = ?");
                $stmt->execute([$name, $description, $monthly_price, $yearly_price, $features_json, $is_featured, $status, $plan_id]);
                
                $stmt = db()->prepare("SELECT * FROM subscription_plans WHERE id = ?");
                $stmt->execute([$plan_id]);
                $plan = $stmt->fetch();
                
                // Refresh features
                $existing_features = [];
                if (!empty($plan['features'])) {
                    $decoded = json_decode($plan['features'], true);
                    if (is_array($decoded)) {
                        $existing_features = $decoded;
                    }
                }
                
                $success = 'Plan updated successfully';
            } catch (PDOException $e) {
                $errors[] = 'Failed to update plan: ' . $e->getMessage();
            }
        }
    }
}

$csrf_token = generate_csrf_token();
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="fw-bold mb-0">Edit Subscription Plan</h2>
    <a href="plans.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-2"></i>Back</a>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger"><?php foreach ($errors as $error): ?><p class="mb-0"><?php echo $error; ?></p><?php endforeach; ?></div>
<?php endif; ?>
<?php if (isset($success)): ?>
    <div class="alert alert-success"><?php echo $success; ?></div>
<?php endif; ?>

<div class="card border-0 shadow-sm">
    <div class="card-body p-4">
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label">Plan Name <span class="text-danger">*</span></label>
                    <input type="text" name="name" class="form-control" value="<?php echo $plan['name']; ?>" required>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Monthly Price (₹)</label>
                    <input type="number" name="monthly_price" class="form-control" step="0.01" value="<?php echo $plan['monthly_price']; ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Yearly Price (₹)</label>
                    <input type="number" name="yearly_price" class="form-control" step="0.01" value="<?php echo $plan['yearly_price']; ?>">
                </div>
                <div class="col-12">
                    <label class="form-label">Description</label>
                    <textarea name="description" class="form-control" rows="2"><?php echo $plan['description']; ?></textarea>
                </div>
                
                <!-- Plan Features Section -->
                <div class="col-12">
                    <label class="form-label">Plan Features / Benefits</label>
                    <div id="features-container">
                        <?php 
                        $feature_count = count($existing_features);
                        if ($feature_count === 0) $feature_count = 1;
                        for ($i = 0; $i < $feature_count; $i++): 
                            $feature = $existing_features[$i] ?? '';
                        ?>
                        <div class="input-group mb-2 feature-row">
                            <span class="input-group-text"><i class="bi bi-check-circle text-success"></i></span>
                            <input type="text" name="features[]" class="form-control" value="<?php echo $feature; ?>" placeholder="Enter plan feature (e.g., WhatsApp CRM Access)">
                            <button type="button" class="btn btn-outline-danger remove-feature" onclick="this.closest('.feature-row').remove()">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                        <?php endfor; ?>
                    </div>
                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="addFeatureRow()">
                        <i class="bi bi-plus-circle me-1"></i>Add Feature
                    </button>
                    <small class="text-muted d-block mt-1">Features displayed in the plan card and comparison table</small>
                </div>
                
                <div class="col-12">
                    <div class="form-check">
                        <input type="checkbox" name="is_featured" class="form-check-input" id="featuredCheck" <?php echo $plan['is_featured'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="featuredCheck">Featured Plan</label>
                    </div>
                </div>
                <div class="col-12">
                    <div class="form-check">
                        <input type="checkbox" name="status" class="form-check-input" id="statusCheck" <?php echo $plan['status'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="statusCheck">Active</label>
                    </div>
                </div>
            </div>
            <div class="mt-4">
                <button type="submit" class="btn btn-primary"><i class="bi bi-save me-2"></i>Update Plan</button>
                <a href="plans.php" class="btn btn-outline-secondary ms-2">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
function addFeatureRow() {
    const container = document.getElementById('features-container');
    const row = document.createElement('div');
    row.className = 'input-group mb-2 feature-row';
    row.innerHTML = `
        <span class="input-group-text"><i class="bi bi-check-circle text-success"></i></span>
        <input type="text" name="features[]" class="form-control" placeholder="Enter plan feature (e.g., WhatsApp CRM Access)">
        <button type="button" class="btn btn-outline-danger remove-feature" onclick="this.closest('.feature-row').remove()">
            <i class="bi bi-trash"></i>
        </button>
    `;
    container.appendChild(row);
}
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
