<?php
/**
 * Record Subscription Payment
 * LandSales Pro - Manually record subscription payments
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

initSecureSession();
requireRole(['super_admin', 'admin']);

$errors = [];
$success = false;

// Pre-select user if provided
$selectedUserId = $_GET['user_id'] ?? null;
$selectedUser = null;
$userSubscription = null;

if ($selectedUserId) {
    $selectedUser = db_fetch_one("SELECT * FROM users WHERE id = ? AND role = 'subscriber'", 'i', [$selectedUserId]);
    if ($selectedUser) {
        $userSubscription = getActiveSubscription($selectedUserId);
    }
}

// Get all subscribers for dropdown
$subscribers = db_fetch_all("SELECT u.id, u.full_name, u.email, s.id as sub_id, p.name as plan_name, s.status
    FROM users u
    LEFT JOIN subscriptions s ON u.id = s.user_id AND s.status IN ('active', 'trial', 'expired')
    LEFT JOIN plans p ON s.plan_id = p.id
    WHERE u.role = 'subscriber'
    ORDER BY u.full_name");

// Get all plans
$plans = db_fetch_all("SELECT * FROM plans WHERE is_active = 1 ORDER BY sort_order");

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userId = intval($_POST['user_id'] ?? 0);
    $planId = intval($_POST['plan_id'] ?? 0);
    $billingCycle = $_POST['billing_cycle'] ?? 'monthly';
    $amount = floatval($_POST['amount'] ?? 0);
    $paymentMethod = trim($_POST['payment_method'] ?? '');
    $referenceNumber = trim($_POST['reference_number'] ?? '');
    $paymentDate = $_POST['payment_date'] ?? date('Y-m-d');
    $notes = trim($_POST['notes'] ?? '');

    // Validation
    if (!$userId) $errors[] = "Please select a subscriber";
    if (!$planId) $errors[] = "Please select a plan";
    if ($amount <= 0) $errors[] = "Please enter a valid amount";
    if (empty($paymentMethod)) $errors[] = "Please select a payment method";

    if (empty($errors)) {
        db_begin();
        try {
            // Get or create subscription
            $subscription = db_fetch_one("SELECT * FROM subscriptions WHERE user_id = ? AND status IN ('active', 'trial', 'expired') ORDER BY expires_at DESC LIMIT 1", 'i', [$userId]);

            if ($subscription) {
                // Extend existing subscription
                $months = billingCycleMonths($billingCycle);
                $currentExpiry = strtotime($subscription['expires_at']);
                $baseDate = max($currentExpiry, time());
                $newExpiry = date('Y-m-d H:i:s', strtotime("+{$months} months", $baseDate));

                $updateSql = "UPDATE subscriptions SET
                    plan_id = ?,
                    billing_cycle = ?,
                    amount = ?,
                    status = 'active',
                    expires_at = ?,
                    updated_at = NOW()
                    WHERE id = ?";
                db_execute($updateSql, 'isdsi', [$planId, $billingCycle, $amount, $newExpiry, $subscription['id']]);
                $subscriptionId = $subscription['id'];
                $periodStart = date('Y-m-d', $baseDate);
                $periodEnd = date('Y-m-d', strtotime($newExpiry));
            } else {
                // Create new subscription
                $months = billingCycleMonths($billingCycle);
                $startsAt = date('Y-m-d H:i:s');
                $expiresAt = date('Y-m-d H:i:s', strtotime("+{$months} months"));

                $insertSql = "INSERT INTO subscriptions (user_id, plan_id, billing_cycle, amount, status, starts_at, expires_at)
                              VALUES (?, ?, ?, ?, 'active', ?, ?)";
                db_execute($insertSql, 'iisdss', [$userId, $planId, $billingCycle, $amount, $startsAt, $expiresAt]);
                $subscriptionId = db_last_id();
                $periodStart = date('Y-m-d');
                $periodEnd = date('Y-m-d', strtotime($expiresAt));
            }

            // Generate receipt number
            $receiptNumber = 'RCP-' . date('Ymd') . '-' . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);

            // Record payment
            $paymentSql = "INSERT INTO subscription_payments
                (subscription_id, user_id, amount, payment_method, reference_number, receipt_number,
                 payment_date, period_start, period_end, status, notes, recorded_by)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'confirmed', ?, ?)";

            db_execute($paymentSql, 'iidssssssi', [
                $subscriptionId,
                $userId,
                $amount,
                $paymentMethod,
                $referenceNumber,
                $receiptNumber,
                $paymentDate,
                $periodStart,
                $periodEnd,
                $notes,
                $_SESSION['user_id']
            ]);

            // Log activity
            logActivity('subscription_payment', "Recorded payment of TZS " . number_format($amount) . " for user ID {$userId}");

            db_commit();
            $success = true;
            setFlashMessage('success', 'Payment recorded successfully. Receipt: ' . $receiptNumber);

            // Redirect to prevent resubmission
            header('Location: payments.php?success=1');
            exit;

        } catch (Exception $e) {
            db_rollback();
            $errors[] = "An error occurred: " . $e->getMessage();
        }
    }
}

// Get plan prices for JavaScript
$planPrices = [];
foreach ($plans as $plan) {
    $planPrices[$plan['id']] = [
        'monthly' => $plan['price_monthly'],
        'quarterly' => $plan['price_quarterly'],
        'semi_annual' => $plan['price_semi_annual'],
        'yearly' => $plan['price_yearly']
    ];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Record Payment - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Record Payment</h1>
            <div class="header-actions">
                <a href="payments.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back to Payments
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <div class="form-container">
                <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <ul>
                        <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>

                <form method="POST" class="payment-form">
                    <div class="form-card">
                        <div class="card-header">
                            <i class="fas fa-user"></i>
                            <h3>Subscriber Details</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="user_id">Select Subscriber *</label>
                                <select name="user_id" id="user_id" class="form-control" required onchange="loadUserSubscription(this.value)">
                                    <option value="">-- Select Subscriber --</option>
                                    <?php foreach ($subscribers as $sub): ?>
                                    <option value="<?php echo $sub['id']; ?>"
                                            data-sub-id="<?php echo $sub['sub_id'] ?? ''; ?>"
                                            data-plan="<?php echo htmlspecialchars($sub['plan_name'] ?? ''); ?>"
                                            data-status="<?php echo $sub['status'] ?? ''; ?>"
                                            <?php echo ($selectedUserId == $sub['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($sub['full_name']); ?> (<?php echo htmlspecialchars($sub['email']); ?>)
                                        <?php if ($sub['plan_name']): ?> - <?php echo $sub['plan_name']; ?><?php endif; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div id="currentSubscription" class="subscription-info" style="display: <?php echo $userSubscription ? 'block' : 'none'; ?>">
                                <div class="info-label">Current Subscription</div>
                                <div class="info-content" id="subscriptionDetails">
                                    <?php if ($userSubscription): ?>
                                    <span class="plan-name"><?php echo $userSubscription['plan_name']; ?></span>
                                    <span class="status-badge status-<?php echo $userSubscription['status']; ?>"><?php echo ucfirst($userSubscription['status']); ?></span>
                                    <span class="expiry">Expires: <?php echo date('M j, Y', strtotime($userSubscription['expires_at'])); ?></span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-card">
                        <div class="card-header">
                            <i class="fas fa-tags"></i>
                            <h3>Plan & Billing</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="plan_id">Plan *</label>
                                    <select name="plan_id" id="plan_id" class="form-control" required onchange="updateAmount()">
                                        <option value="">-- Select Plan --</option>
                                        <?php foreach ($plans as $plan): ?>
                                        <option value="<?php echo $plan['id']; ?>"
                                                <?php echo ($userSubscription && $userSubscription['plan_id'] == $plan['id']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($plan['name']); ?> - TZS <?php echo number_format($plan['price_monthly']); ?>/mo
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="billing_cycle">Billing Cycle *</label>
                                    <select name="billing_cycle" id="billing_cycle" class="form-control" required onchange="updateAmount()">
                                        <option value="monthly">Monthly</option>
                                        <option value="quarterly">Quarterly (3 months) - ~7% off</option>
                                        <option value="semi_annual">Semi-Annual (6 months) - ~10% off</option>
                                        <option value="yearly">Yearly - ~17% off</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="amount">Amount (TZS) *</label>
                                <div class="amount-input">
                                    <span class="currency">TZS</span>
                                    <input type="number" name="amount" id="amount" class="form-control" required min="0" step="1000">
                                </div>
                                <small class="form-text">Suggested amount based on plan and billing cycle</small>
                            </div>
                        </div>
                    </div>

                    <div class="form-card">
                        <div class="card-header">
                            <i class="fas fa-money-bill-wave"></i>
                            <h3>Payment Details</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="payment_method">Payment Method *</label>
                                    <select name="payment_method" id="payment_method" class="form-control" required>
                                        <option value="">-- Select Method --</option>
                                        <option value="mpesa">M-Pesa</option>
                                        <option value="tigopesa">Tigo Pesa</option>
                                        <option value="airtel">Airtel Money</option>
                                        <option value="bank_transfer">Bank Transfer</option>
                                        <option value="cash">Cash</option>
                                        <option value="other">Other</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="reference_number">Reference/Transaction Number</label>
                                    <input type="text" name="reference_number" id="reference_number" class="form-control" placeholder="e.g., MPESA123456">
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="payment_date">Payment Date *</label>
                                <input type="date" name="payment_date" id="payment_date" class="form-control" required value="<?php echo date('Y-m-d'); ?>">
                            </div>

                            <div class="form-group">
                                <label for="notes">Notes</label>
                                <textarea name="notes" id="notes" class="form-control" rows="3" placeholder="Optional notes about this payment..."></textarea>
                            </div>
                        </div>
                    </div>

                    <div class="form-actions">
                        <a href="payments.php" class="btn btn-outline">Cancel</a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-check"></i> Record Payment
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <style>
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            margin: 0;
            background: #f1f5f9;
        }

        .header-actions {
            display: flex;
            gap: 0.75rem;
        }

        .btn {
            padding: 0.625rem 1.25rem;
            border-radius: 8px;
            font-weight: 500;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            font-size: 0.875rem;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        .btn-outline {
            border: 1px solid #e2e8f0;
            background: white;
            color: #64748b;
        }

        .btn-outline:hover {
            border-color: #667eea;
            color: #667eea;
        }

        .form-container {
            max-width: 800px;
        }

        .alert {
            padding: 1rem 1.5rem;
            border-radius: 10px;
            margin-bottom: 1.5rem;
            display: flex;
            gap: 0.75rem;
        }

        .alert-danger {
            background: #fef2f2;
            border: 1px solid #fecaca;
            color: #991b1b;
        }

        .alert ul {
            margin: 0;
            padding-left: 1rem;
        }

        .form-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            margin-bottom: 1.5rem;
            overflow: hidden;
        }

        .card-header {
            padding: 1rem 1.5rem;
            background: #f8fafc;
            border-bottom: 1px solid #f1f5f9;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .card-header i {
            color: #667eea;
            font-size: 1rem;
        }

        .card-header h3 {
            margin: 0;
            font-size: 1rem;
            font-weight: 600;
            color: #1e293b;
        }

        .card-body {
            padding: 1.5rem;
        }

        .form-row {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
        }

        .form-group {
            margin-bottom: 1.25rem;
        }

        .form-group:last-child {
            margin-bottom: 0;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: #374151;
            font-size: 0.875rem;
        }

        .form-control {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 0.9rem;
            transition: all 0.2s;
            background: white;
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        select.form-control {
            cursor: pointer;
        }

        textarea.form-control {
            resize: vertical;
            min-height: 80px;
        }

        .form-text {
            font-size: 0.8rem;
            color: #94a3b8;
            margin-top: 0.25rem;
        }

        .amount-input {
            position: relative;
        }

        .amount-input .currency {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #64748b;
            font-weight: 500;
        }

        .amount-input input {
            padding-left: 3rem;
        }

        .subscription-info {
            background: #f8fafc;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 1rem;
        }

        .info-label {
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            color: #64748b;
            margin-bottom: 0.5rem;
        }

        .info-content {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            flex-wrap: wrap;
        }

        .plan-name {
            font-weight: 600;
            color: #1e293b;
        }

        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .status-active { background: #dcfce7; color: #16a34a; }
        .status-trial { background: #dbeafe; color: #2563eb; }
        .status-expired { background: #fee2e2; color: #dc2626; }

        .expiry {
            color: #64748b;
            font-size: 0.875rem;
        }

        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 1rem;
            padding-top: 0.5rem;
        }

        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
            }

            .form-actions {
                flex-direction: column-reverse;
            }

            .form-actions .btn {
                width: 100%;
                justify-content: center;
            }
        }
    </style>

    <script>
        const planPrices = <?php echo json_encode($planPrices); ?>;

        function updateAmount() {
            const planId = document.getElementById('plan_id').value;
            const billingCycle = document.getElementById('billing_cycle').value;

            if (planId && planPrices[planId]) {
                const price = planPrices[planId][billingCycle] || planPrices[planId]['monthly'];
                document.getElementById('amount').value = price;
            }
        }

        function loadUserSubscription(userId) {
            const select = document.getElementById('user_id');
            const option = select.options[select.selectedIndex];
            const subscriptionDiv = document.getElementById('currentSubscription');
            const detailsDiv = document.getElementById('subscriptionDetails');

            if (option.dataset.subId) {
                const plan = option.dataset.plan;
                const status = option.dataset.status;
                detailsDiv.innerHTML = `
                    <span class="plan-name">${plan}</span>
                    <span class="status-badge status-${status}">${status.charAt(0).toUpperCase() + status.slice(1)}</span>
                `;
                subscriptionDiv.style.display = 'block';
            } else {
                subscriptionDiv.style.display = 'none';
            }
        }

        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            updateAmount();
        });
    </script>
</body>
</html>
