<?php
/**
 * Subscription Management
 * LandSales Pro - View and manage subscription
 */
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();
requireAuth();

$userId = $_SESSION['user_id'];

// Get current subscription
$subscription = db_fetch_one("SELECT s.*, p.name as plan_name, p.price_monthly, p.price_quarterly,
    p.price_semiannual, p.price_yearly, p.max_projects, p.max_plots, p.max_agents
    FROM subscriptions s
    JOIN plans p ON s.plan_id = p.id
    WHERE s.user_id = ? AND s.status = 'active'
    ORDER BY s.expires_at DESC LIMIT 1", 'i', [$userId]);

// Get all plans
$plans = db_fetch_all("SELECT * FROM plans WHERE status = 'active' ORDER BY price_monthly");

// Get subscription history
$subscriptionHistory = db_fetch_all("SELECT s.*, p.name as plan_name
    FROM subscriptions s
    JOIN plans p ON s.plan_id = p.id
    WHERE s.user_id = ?
    ORDER BY s.created_at DESC LIMIT 10", 'i', [$userId]);

// Get payment history
$paymentHistory = db_fetch_all("SELECT sp.*, s.billing_cycle, p.name as plan_name
    FROM subscription_payments sp
    JOIN subscriptions s ON sp.subscription_id = s.id
    JOIN plans p ON s.plan_id = p.id
    WHERE s.user_id = ?
    ORDER BY sp.payment_date DESC LIMIT 10", 'i', [$userId]);

// Calculate usage
$usage = [
    'projects' => db_fetch_one("SELECT COUNT(*) as count FROM projects WHERE user_id = ?", 'i', [$userId])['count'],
    'plots' => db_fetch_one("SELECT COUNT(*) as count FROM plots WHERE user_id = ?", 'i', [$userId])['count'],
    'agents' => db_fetch_one("SELECT COUNT(*) as count FROM agents WHERE user_id = ?", 'i', [$userId])['count']
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subscription - <?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">Subscription</h1>
            <div class="header-actions">
                <a href="index.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back to Settings
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <!-- Current Subscription -->
            <div class="current-subscription">
                <?php if ($subscription): ?>
                <div class="subscription-card active">
                    <div class="subscription-header">
                        <div class="plan-info">
                            <span class="plan-badge"><?php echo htmlspecialchars($subscription['plan_name']); ?></span>
                            <h2>Your Current Plan</h2>
                        </div>
                        <div class="subscription-status">
                            <span class="status-badge status-<?php echo $subscription['status']; ?>">
                                <?php echo ucfirst($subscription['status']); ?>
                            </span>
                        </div>
                    </div>
                    <div class="subscription-body">
                        <div class="subscription-details">
                            <div class="detail-item">
                                <i class="fas fa-calendar"></i>
                                <div>
                                    <span class="detail-label">Billing Cycle</span>
                                    <span class="detail-value"><?php echo ucfirst($subscription['billing_cycle']); ?></span>
                                </div>
                            </div>
                            <div class="detail-item">
                                <i class="fas fa-clock"></i>
                                <div>
                                    <span class="detail-label">Expires On</span>
                                    <span class="detail-value"><?php echo date('F j, Y', strtotime($subscription['expires_at'])); ?></span>
                                </div>
                            </div>
                            <div class="detail-item">
                                <i class="fas fa-hourglass-half"></i>
                                <div>
                                    <span class="detail-label">Days Remaining</span>
                                    <span class="detail-value <?php echo max(0, ceil((strtotime($subscription['expires_at']) - time()) / 86400)) <= 7 ? 'text-warning' : ''; ?>">
                                        <?php echo max(0, ceil((strtotime($subscription['expires_at']) - time()) / 86400)); ?> days
                                    </span>
                                </div>
                            </div>
                        </div>

                        <div class="usage-section">
                            <h4>Current Usage</h4>
                            <div class="usage-grid">
                                <div class="usage-card">
                                    <div class="usage-icon"><i class="fas fa-building"></i></div>
                                    <div class="usage-info">
                                        <div class="usage-count"><?php echo $usage['projects']; ?> / <?php echo $subscription['max_projects'] ?: '∞'; ?></div>
                                        <div class="usage-label">Projects</div>
                                    </div>
                                    <div class="usage-bar-mini">
                                        <div class="usage-fill" style="width: <?php echo $subscription['max_projects'] ? min(100, ($usage['projects'] / $subscription['max_projects']) * 100) : 10; ?>%"></div>
                                    </div>
                                </div>
                                <div class="usage-card">
                                    <div class="usage-icon"><i class="fas fa-th"></i></div>
                                    <div class="usage-info">
                                        <div class="usage-count"><?php echo $usage['plots']; ?> / <?php echo $subscription['max_plots'] ?: '∞'; ?></div>
                                        <div class="usage-label">Plots</div>
                                    </div>
                                    <div class="usage-bar-mini">
                                        <div class="usage-fill" style="width: <?php echo $subscription['max_plots'] ? min(100, ($usage['plots'] / $subscription['max_plots']) * 100) : 10; ?>%"></div>
                                    </div>
                                </div>
                                <div class="usage-card">
                                    <div class="usage-icon"><i class="fas fa-users"></i></div>
                                    <div class="usage-info">
                                        <div class="usage-count"><?php echo $usage['agents']; ?> / <?php echo $subscription['max_agents'] ?: '∞'; ?></div>
                                        <div class="usage-label">Agents</div>
                                    </div>
                                    <div class="usage-bar-mini">
                                        <div class="usage-fill" style="width: <?php echo $subscription['max_agents'] ? min(100, ($usage['agents'] / $subscription['max_agents']) * 100) : 10; ?>%"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                <div class="subscription-card expired">
                    <div class="subscription-header">
                        <h2><i class="fas fa-exclamation-triangle"></i> No Active Subscription</h2>
                    </div>
                    <div class="subscription-body">
                        <p>Your subscription has expired or you haven't subscribed yet. Choose a plan below to continue using <?php echo APP_NAME; ?>.</p>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Renewal Notice -->
            <?php if ($subscription): ?>
            <div class="renewal-notice">
                <div class="notice-icon"><i class="fas fa-info-circle"></i></div>
                <div class="notice-content">
                    <h4>How to Renew</h4>
                    <p>To renew or upgrade your subscription, please contact us or make a payment to our account. Our admin team will activate your subscription within 24 hours of receiving payment confirmation.</p>
                    <div class="contact-info">
                        <span><i class="fas fa-phone"></i> +255 XXX XXX XXX</span>
                        <span><i class="fas fa-envelope"></i> support@landsalespro.com</span>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Available Plans -->
            <div class="plans-section">
                <h2>Available Plans</h2>
                <div class="plans-grid">
                    <?php foreach ($plans as $plan): ?>
                    <div class="plan-card <?php echo $subscription && $subscription['plan_id'] == $plan['id'] ? 'current' : ''; ?>">
                        <?php if ($plan['id'] == 2): ?><div class="popular-badge">Popular</div><?php endif; ?>
                        <div class="plan-header">
                            <h3><?php echo htmlspecialchars($plan['name']); ?></h3>
                            <div class="plan-price">
                                <span class="currency">TZS</span>
                                <span class="amount"><?php echo number_format($plan['price_monthly']); ?></span>
                                <span class="period">/month</span>
                            </div>
                        </div>
                        <div class="plan-features">
                            <div class="feature">
                                <i class="fas fa-check"></i>
                                <span><?php echo $plan['max_projects'] ?: 'Unlimited'; ?> Projects</span>
                            </div>
                            <div class="feature">
                                <i class="fas fa-check"></i>
                                <span><?php echo $plan['max_plots'] ?: 'Unlimited'; ?> Plots</span>
                            </div>
                            <div class="feature">
                                <i class="fas fa-check"></i>
                                <span><?php echo $plan['max_agents'] ?: 'Unlimited'; ?> Agents</span>
                            </div>
                            <div class="feature">
                                <i class="fas fa-check"></i>
                                <span>All Reports</span>
                            </div>
                            <div class="feature">
                                <i class="fas fa-check"></i>
                                <span>Payment Tracking</span>
                            </div>
                        </div>
                        <div class="plan-pricing">
                            <div class="pricing-option">
                                <span>Monthly</span>
                                <span>TZS <?php echo number_format($plan['price_monthly']); ?></span>
                            </div>
                            <div class="pricing-option">
                                <span>Quarterly</span>
                                <span>TZS <?php echo number_format($plan['price_quarterly']); ?></span>
                            </div>
                            <div class="pricing-option">
                                <span>Semi-Annual</span>
                                <span>TZS <?php echo number_format($plan['price_semiannual']); ?></span>
                            </div>
                            <div class="pricing-option">
                                <span>Yearly</span>
                                <span>TZS <?php echo number_format($plan['price_yearly']); ?></span>
                            </div>
                        </div>
                        <?php if ($subscription && $subscription['plan_id'] == $plan['id']): ?>
                        <button class="btn btn-outline btn-block" disabled>Current Plan</button>
                        <?php else: ?>
                        <button class="btn btn-primary btn-block" onclick="contactForPlan('<?php echo htmlspecialchars($plan['name']); ?>')">
                            <?php echo $subscription ? 'Upgrade' : 'Subscribe'; ?>
                        </button>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Payment History -->
            <?php if (!empty($paymentHistory)): ?>
            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-history"></i> Payment History</h3>
                </div>
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Plan</th>
                                <th>Period</th>
                                <th>Amount</th>
                                <th>Method</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($paymentHistory as $payment): ?>
                            <tr>
                                <td><?php echo date('M j, Y', strtotime($payment['payment_date'])); ?></td>
                                <td><?php echo htmlspecialchars($payment['plan_name']); ?></td>
                                <td><?php echo ucfirst($payment['billing_cycle']); ?></td>
                                <td>TZS <?php echo number_format($payment['amount']); ?></td>
                                <td><?php echo ucfirst($payment['payment_method'] ?? 'N/A'); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo $payment['status']; ?>">
                                        <?php echo ucfirst($payment['status']); ?>
                                    </span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php endif; ?>
        </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-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }
        .btn-block { width: 100%; justify-content: center; }
        .btn:disabled { opacity: 0.5; cursor: not-allowed; }

        .subscription-card { background: white; border-radius: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; margin-bottom: 1.5rem; }
        .subscription-card.active { border-top: 4px solid #22c55e; }
        .subscription-card.expired { border-top: 4px solid #f59e0b; }
        .subscription-header { padding: 1.5rem; display: flex; justify-content: space-between; align-items: center; background: #f8fafc; }
        .plan-badge { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 0.25rem 0.75rem; border-radius: 4px; font-size: 0.75rem; font-weight: 600; }
        .subscription-header h2 { margin: 0.5rem 0 0; font-size: 1.25rem; 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-expired { background: #fee2e2; color: #dc2626; }
        .status-confirmed { background: #dcfce7; color: #16a34a; }
        .subscription-body { padding: 1.5rem; }

        .subscription-details { display: flex; gap: 2rem; margin-bottom: 1.5rem; flex-wrap: wrap; }
        .detail-item { display: flex; gap: 0.75rem; align-items: center; }
        .detail-item i { width: 40px; height: 40px; background: #f1f5f9; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: #667eea; }
        .detail-label { display: block; font-size: 0.75rem; color: #64748b; }
        .detail-value { font-weight: 600; color: #1e293b; }
        .text-warning { color: #d97706; }

        .usage-section h4 { font-size: 0.9rem; color: #64748b; margin: 0 0 1rem; }
        .usage-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; }
        .usage-card { background: #f8fafc; border-radius: 10px; padding: 1rem; }
        .usage-icon { width: 36px; height: 36px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 8px; display: flex; align-items: center; justify-content: center; margin-bottom: 0.75rem; }
        .usage-count { font-size: 1.25rem; font-weight: 700; color: #1e293b; }
        .usage-label { font-size: 0.75rem; color: #64748b; }
        .usage-bar-mini { height: 4px; background: #e2e8f0; border-radius: 2px; margin-top: 0.5rem; overflow: hidden; }
        .usage-fill { height: 100%; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }

        .renewal-notice { background: #dbeafe; border: 1px solid #93c5fd; border-radius: 12px; padding: 1.25rem; display: flex; gap: 1rem; margin-bottom: 1.5rem; }
        .notice-icon { color: #2563eb; font-size: 1.25rem; }
        .notice-content h4 { margin: 0 0 0.5rem; color: #1e40af; }
        .notice-content p { margin: 0 0 0.75rem; color: #1e40af; font-size: 0.9rem; }
        .contact-info { display: flex; gap: 1.5rem; font-size: 0.85rem; color: #2563eb; }
        .contact-info i { margin-right: 0.25rem; }

        .plans-section { margin-bottom: 1.5rem; }
        .plans-section h2 { font-size: 1.25rem; color: #1e293b; margin-bottom: 1rem; }
        .plans-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1.5rem; }
        .plan-card { background: white; border-radius: 14px; padding: 1.5rem; box-shadow: 0 2px 8px rgba(0,0,0,0.05); position: relative; border: 2px solid transparent; transition: all 0.3s; }
        .plan-card:hover { transform: translateY(-4px); box-shadow: 0 8px 25px rgba(0,0,0,0.1); }
        .plan-card.current { border-color: #667eea; }
        .popular-badge { position: absolute; top: -10px; right: 20px; background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white; padding: 0.25rem 0.75rem; border-radius: 4px; font-size: 0.7rem; font-weight: 600; }
        .plan-header { text-align: center; padding-bottom: 1rem; border-bottom: 1px solid #f1f5f9; margin-bottom: 1rem; }
        .plan-header h3 { margin: 0 0 0.75rem; color: #1e293b; }
        .plan-price { display: flex; align-items: baseline; justify-content: center; gap: 0.25rem; }
        .plan-price .currency { font-size: 0.9rem; color: #64748b; }
        .plan-price .amount { font-size: 2rem; font-weight: 700; color: #667eea; }
        .plan-price .period { font-size: 0.85rem; color: #64748b; }

        .plan-features { margin-bottom: 1rem; }
        .feature { display: flex; align-items: center; gap: 0.5rem; padding: 0.5rem 0; font-size: 0.9rem; }
        .feature i { color: #22c55e; }

        .plan-pricing { background: #f8fafc; border-radius: 8px; padding: 0.75rem; margin-bottom: 1rem; }
        .pricing-option { display: flex; justify-content: space-between; padding: 0.35rem 0; font-size: 0.8rem; }
        .pricing-option span:first-child { color: #64748b; }
        .pricing-option span:last-child { font-weight: 500; color: #1e293b; }

        .card { background: white; border-radius: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; }
        .card-header { padding: 1rem 1.25rem; border-bottom: 1px solid #f1f5f9; background: #f8fafc; }
        .card-header h3 { margin: 0; font-size: 0.95rem; font-weight: 600; color: #1e293b; display: flex; align-items: center; gap: 0.5rem; }
        .card-header h3 i { color: #667eea; }

        .table-responsive { overflow-x: auto; }
        .data-table { width: 100%; border-collapse: collapse; }
        .data-table th, .data-table td { padding: 0.875rem 1rem; text-align: left; border-bottom: 1px solid #f1f5f9; }
        .data-table th { background: #f8fafc; font-weight: 600; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.5px; color: #64748b; }

        @media (max-width: 992px) {
            .plans-grid { grid-template-columns: 1fr; }
            .usage-grid { grid-template-columns: 1fr; }
            .subscription-details { flex-direction: column; gap: 1rem; }
        }
    </style>

    <script>
        function contactForPlan(planName) {
            alert('To subscribe to ' + planName + ' plan, please contact our sales team:\n\nPhone: +255 XXX XXX XXX\nEmail: support@landsalespro.com\n\nOur team will guide you through the payment process.');
        }
    </script>
</body>
</html>
