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

$page_title = 'Edit Subscription';
$subscription_id = intval($_GET['id'] ?? 0);

if (!$subscription_id) {
    redirect(BASE_URL . 'admin/subscriptions.php', 'error', 'Invalid subscription ID');
}

// Get subscription
$subscription = null;
try {
    $stmt = db()->prepare("SELECT us.*, u.full_name, u.email, p.name as plan_name, p.monthly_price, p.yearly_price 
                          FROM user_subscriptions us 
                          JOIN users u ON us.user_id = u.id 
                          JOIN subscription_plans p ON us.plan_id = p.id 
                          WHERE us.id = ?");
    $stmt->execute([$subscription_id]);
    $subscription = $stmt->fetch();
} catch (PDOException $e) {}

if (!$subscription) {
    redirect(BASE_URL . 'admin/subscriptions.php', 'error', 'Subscription not found');
}

// Get plans for dropdown
$plans = [];
try {
    $stmt = db()->query("SELECT id, name, monthly_price, yearly_price FROM subscription_plans WHERE status = 1 ORDER BY name");
    $plans = $stmt->fetchAll();
} catch (PDOException $e) {}

$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid security token';
    } else {
        $plan_id = intval($_POST['plan_id'] ?? 0);
        $subscription_type = sanitize($_POST['subscription_type'] ?? 'monthly');
        $amount = floatval($_POST['amount'] ?? 0);
        $start_date = sanitize($_POST['start_date'] ?? '');
        $end_date = sanitize($_POST['end_date'] ?? '');
        $status = sanitize($_POST['status'] ?? 'active');
        $payment_status = sanitize($_POST['payment_status'] ?? 'paid');
        $notes = sanitize($_POST['notes'] ?? '');
        
        if (!$plan_id) $errors[] = 'Please select a plan';
        if (empty($start_date)) $errors[] = 'Start date is required';
        if (empty($end_date)) $errors[] = 'End date is required';
        
        if (empty($errors)) {
            try {
                $stmt = db()->prepare("UPDATE user_subscriptions SET 
                    plan_id = ?, subscription_type = ?, amount = ?, start_date = ?, end_date = ?, status = ?, payment_status = ?, updated_at = NOW()
                    WHERE id = ?");
                $stmt->execute([$plan_id, $subscription_type, $amount, $start_date, $end_date, $status, $payment_status, $subscription_id]);
                
                // Refresh data
                $stmt = db()->prepare("SELECT us.*, u.full_name, u.email, p.name as plan_name, p.monthly_price, p.yearly_price 
                                      FROM user_subscriptions us 
                                      JOIN users u ON us.user_id = u.id 
                                      JOIN subscription_plans p ON us.plan_id = p.id 
                                      WHERE us.id = ?");
                $stmt->execute([$subscription_id]);
                $subscription = $stmt->fetch();
                
                $success = 'Subscription updated successfully';
            } catch (PDOException $e) {
                $errors[] = 'Failed to update subscription: ' . $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</h2>
    <a href="subscriptions.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 ($success): ?>
    <div class="alert alert-success"><?php echo $success; ?></div>
<?php endif; ?>

<div class="row g-4">
    <div class="col-lg-8">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white py-3">
                <h5 class="fw-bold mb-0"><i class="bi bi-pencil text-primary me-2"></i>Edit Subscription Details</h5>
            </div>
            <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-12">
                            <label class="form-label">User</label>
                            <input type="text" class="form-control" value="<?php echo $subscription['full_name'] . ' (' . $subscription['email'] . ')'; ?>" disabled>
                            <small class="text-muted">User cannot be changed</small>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Plan <span class="text-danger">*</span></label>
                            <select name="plan_id" class="form-select" id="planSelect" required>
                                <?php foreach ($plans as $plan): ?>
                                <option value="<?php echo $plan['id']; ?>" data-monthly="<?php echo $plan['monthly_price']; ?>" data-yearly="<?php echo $plan['yearly_price']; ?>" <?php echo $subscription['plan_id'] == $plan['id'] ? 'selected' : ''; ?>>
                                    <?php echo $plan['name']; ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Subscription Type</label>
                            <select name="subscription_type" class="form-select" id="typeSelect">
                                <option value="monthly" <?php echo $subscription['subscription_type'] == 'monthly' ? 'selected' : ''; ?>>Monthly</option>
                                <option value="yearly" <?php echo $subscription['subscription_type'] == 'yearly' ? 'selected' : ''; ?>>Yearly</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Amount (₹) <span class="text-danger">*</span></label>
                            <input type="number" name="amount" class="form-control" id="amountInput" step="0.01" value="<?php echo $subscription['amount']; ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Payment ID</label>
                            <input type="text" class="form-control" value="<?php echo $subscription['payment_id']; ?>" disabled>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Start Date <span class="text-danger">*</span></label>
                            <input type="date" name="start_date" class="form-control" value="<?php echo $subscription['start_date']; ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">End Date <span class="text-danger">*</span></label>
                            <input type="date" name="end_date" class="form-control" value="<?php echo $subscription['end_date']; ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select">
                                <option value="active" <?php echo $subscription['status'] == 'active' ? 'selected' : ''; ?>>Active</option>
                                <option value="pending" <?php echo $subscription['status'] == 'pending' ? 'selected' : ''; ?>>Pending</option>
                                <option value="expired" <?php echo $subscription['status'] == 'expired' ? 'selected' : ''; ?>>Expired</option>
                                <option value="cancelled" <?php echo $subscription['status'] == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Payment Status</label>
                            <select name="payment_status" class="form-select">
                                <option value="paid" <?php echo $subscription['payment_status'] == 'paid' ? 'selected' : ''; ?>>Paid</option>
                                <option value="unpaid" <?php echo $subscription['payment_status'] == 'unpaid' ? 'selected' : ''; ?>>Unpaid</option>
                                <option value="refunded" <?php echo $subscription['payment_status'] == 'refunded' ? 'selected' : ''; ?>>Refunded</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="mt-4">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-save me-2"></i>Update Subscription
                        </button>
                        <a href="subscriptions.php" class="btn btn-outline-secondary ms-2">Cancel</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-lg-4">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white py-3">
                <h5 class="fw-bold mb-0"><i class="bi bi-info-circle text-info me-2"></i>Subscription Info</h5>
            </div>
            <div class="card-body">
                <p class="mb-2"><strong>Subscription ID:</strong> #<?php echo $subscription_id; ?></p>
                <p class="mb-2"><strong>Created:</strong> <?php echo format_date($subscription['created_at']); ?></p>
                <p class="mb-2"><strong>Last Updated:</strong> <?php echo $subscription['updated_at'] ? format_date($subscription['updated_at']) : 'Never'; ?></p>
                <hr>
                <a href="user-view.php?id=<?php echo $subscription['user_id']; ?>" class="btn btn-outline-primary w-100">
                    <i class="bi bi-person me-2"></i>View User Profile
                </a>
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('planSelect').addEventListener('change', updateAmount);
document.getElementById('typeSelect').addEventListener('change', updateAmount);

function updateAmount() {
    const planSelect = document.getElementById('planSelect');
    const typeSelect = document.getElementById('typeSelect');
    const amountInput = document.getElementById('amountInput');
    
    if (planSelect.value) {
        const option = planSelect.options[planSelect.selectedIndex];
        const amount = typeSelect.value === 'yearly' ? option.dataset.yearly : option.dataset.monthly;
        amountInput.value = amount;
    }
}
</script>

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