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

$page_title = 'Add Manual Subscription';

$errors = [];

// Get users for dropdown
$users = [];
try {
    $stmt = db()->query("SELECT id, full_name, email FROM users WHERE status = 'active' ORDER BY full_name");
    $users = $stmt->fetchAll();
} catch (PDOException $e) {}

// 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) {}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid security token';
    } else {
        $user_id = intval($_POST['user_id'] ?? 0);
        $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 (!$user_id) $errors[] = 'Please select a user';
        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';
        
        // Auto-calculate amount if not provided
        if ($amount <= 0 && $plan_id) {
            foreach ($plans as $plan) {
                if ($plan['id'] == $plan_id) {
                    $amount = $subscription_type === 'yearly' ? $plan['yearly_price'] : $plan['monthly_price'];
                    break;
                }
            }
        }
        
        if (empty($errors)) {
            try {
                $stmt = db()->prepare("INSERT INTO user_subscriptions 
                    (user_id, plan_id, subscription_type, amount, start_date, end_date, status, payment_status, payment_id, created_at) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
                $payment_id = 'MANUAL_' . time();
                $stmt->execute([$user_id, $plan_id, $subscription_type, $amount, $start_date, $end_date, $status, $payment_status, $payment_id]);
                
                $subscription_id = db()->lastInsertId();
                
                // Add to transactions if paid
                if ($payment_status === 'paid') {
                    $transaction = db()->prepare("INSERT INTO transactions 
                        (user_id, subscription_id, amount, type, status, payment_method, payment_id, description, created_at) 
                        VALUES (?, ?, ?, 'subscription', 'completed', 'manual', ?, ?, NOW())");
                    $transaction->execute([$user_id, $subscription_id, $amount, $payment_id, $notes ?: 'Manual subscription added by admin']);
                }
                
                redirect(BASE_URL . 'admin/subscriptions.php', 'success', 'Subscription added successfully');
            } catch (PDOException $e) {
                $errors[] = 'Failed to add 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">Add Manual 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; ?>

<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-plus-circle text-primary me-2"></i>New Subscription Details</h5>
    </div>
    <div class="card-body p-4">
        <form method="POST" id="subscriptionForm">
            <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">User <span class="text-danger">*</span></label>
                    <select name="user_id" class="form-select" required>
                        <option value="">Select User</option>
                        <?php foreach ($users as $user): ?>
                        <option value="<?php echo $user['id']; ?>">
                            <?php echo $user['full_name'] . ' (' . $user['email'] . ')'; ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </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>
                        <option value="">Select Plan</option>
                        <?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 $plan['name'] . ' - ₹' . $plan['monthly_price'] . '/mo or ₹' . $plan['yearly_price'] . '/yr'; ?>
                        </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">Monthly</option>
                        <option value="yearly">Yearly</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Amount (₹)</label>
                    <input type="number" name="amount" class="form-control" id="amountInput" step="0.01" placeholder="Auto-calculated from plan">
                    <small class="text-muted">Leave empty to auto-calculate from plan</small>
                </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 date('Y-m-d'); ?>" 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" id="endDate" required>
                    <small class="text-muted">Auto-calculated based on subscription type</small>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-select">
                        <option value="active">Active</option>
                        <option value="pending">Pending</option>
                        <option value="expired">Expired</option>
                        <option value="cancelled">Cancelled</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Payment Status</label>
                    <select name="payment_status" class="form-select">
                        <option value="paid">Paid</option>
                        <option value="unpaid">Unpaid</option>
                        <option value="refunded">Refunded</option>
                    </select>
                </div>
                <div class="col-12">
                    <label class="form-label">Admin Notes</label>
                    <textarea name="notes" class="form-control" rows="2" placeholder="Optional notes about this subscription"></textarea>
                </div>
            </div>
            
            <div class="mt-4">
                <button type="submit" class="btn btn-primary btn-lg">
                    <i class="bi bi-save me-2"></i>Add Subscription
                </button>
                <a href="subscriptions.php" class="btn btn-outline-secondary ms-2">Cancel</a>
            </div>
        </form>
    </div>
</div>

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

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;
        if (!amountInput.value) {
            amountInput.value = amount;
        }
    }
    updateEndDate();
}

function updateEndDate() {
    const typeSelect = document.getElementById('typeSelect');
    const endDateInput = document.getElementById('endDate');
    const startDate = new Date();
    
    if (typeSelect.value === 'yearly') {
        startDate.setFullYear(startDate.getFullYear() + 1);
    } else {
        startDate.setMonth(startDate.getMonth() + 1);
    }
    
    endDateInput.value = startDate.toISOString().split('T')[0];
}

// Set initial end date
updateEndDate();
</script>

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