<?php
/**
 * Renew Subscription
 * Extend an existing subscription
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';
require_once '../../includes/validation.php';

requireAdmin();

$pdo = getDB();
$subscriptionId = (int)($_GET['id'] ?? 0);
$error = '';
$success = '';

// Get subscription details
$stmt = $pdo->prepare("SELECT s.*, u.full_name, u.email 
                      FROM subscriptions s
                      JOIN users u ON s.user_id = u.id
                      WHERE s.id = ?");
$stmt->execute([$subscriptionId]);
$subscription = $stmt->fetch();

if (!$subscription) {
    header('Location: index.php?error=Subscription not found');
    exit;
}

// Calculate renewal options
$currentEndDate = $subscription['end_date'] ? strtotime($subscription['end_date']) : time();
$today = time();

// If already expired, start from today
if ($currentEndDate < $today) {
    $currentEndDate = $today;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = "Security token validation failed.";
    } else {
        $renewalType = $_POST['renewal_type'];
        $amount = $_POST['amount'] ?? 0;
        
        $planDays = [
            '1month' => 30,
            '6month' => 180,
            '1year' => 365,
            'unlimited' => null
        ];
        
        if ($renewalType == 'unlimited') {
            $newEndDate = null;
        } else {
            $newEndDate = date('Y-m-d', strtotime("+{$planDays[$renewalType]} days", $currentEndDate));
        }
        
        // Deactivate old subscription
        $stmt = $pdo->prepare("UPDATE subscriptions SET is_active = 0 WHERE id = ?");
        $stmt->execute([$subscriptionId]);
        
        // Create new subscription (renewal)
        $stmt = $pdo->prepare("INSERT INTO subscriptions (user_id, plan_type, start_date, end_date, amount, is_active) 
                              VALUES (?, ?, ?, ?, ?, 1)");
        $stmt->execute([
            $subscription['user_id'],
            $renewalType,
            date('Y-m-d', $currentEndDate),
            $newEndDate,
            $amount
        ]);
        
        $success = "Subscription renewed successfully!";
        header("refresh:2;url=index.php");
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Renew Subscription - Admin Panel</title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background: #2c3e50;
        }
        .sidebar .nav-link {
            color: #ecf0f1;
            padding: 12px 20px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover {
            background: #34495e;
            padding-left: 25px;
        }
        .sidebar .nav-link.active {
            background: #3498db;
        }
        .sidebar .nav-link i {
            margin-right: 10px;
            width: 20px;
        }
        .main-content {
            background: #f8f9fa;
            min-height: 100vh;
        }
        .top-navbar {
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 15px 20px;
        }
        .form-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            padding: 30px;
        }
        .plan-card {
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 15px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .plan-card:hover {
            border-color: #3498db;
            transform: translateY(-2px);
        }
        .plan-card.selected {
            border-color: #28a745;
            background: #f0fff4;
        }
        .plan-price {
            font-size: 24px;
            font-weight: bold;
            color: #2c3e50;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-2 p-0 sidebar">
                <div class="text-center py-4">
                    <h4 class="text-white">🏥 Admin Panel</h4>
                    <small class="text-muted"><?php echo APP_VERSION; ?></small>
                </div>
                <nav class="nav flex-column">
                    <a class="nav-link" href="../dashboard.php">
                        <i class="fas fa-tachometer-alt"></i> Dashboard
                    </a>
                    <a class="nav-link" href="../doctors/index.php">
                        <i class="fas fa-user-md"></i> Doctors
                    </a>
                    <a class="nav-link active" href="index.php">
                        <i class="fas fa-credit-card"></i> Subscriptions
                    </a>
                    <a class="nav-link" href="plans.php">
                        <i class="fas fa-tags"></i> Plans
                    </a>
                    <a class="nav-link" href="reports.php">
                        <i class="fas fa-chart-line"></i> Reports
                    </a>
                    <a class="nav-link" href="../profile.php">
                        <i class="fas fa-user"></i> My Profile
                    </a>
                    <hr class="bg-secondary">
                    <a class="nav-link" href="../../logout.php">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </nav>
            </div>
            
            <!-- Main Content -->
            <div class="col-md-10 main-content">
                <div class="top-navbar">
                    <div class="d-flex justify-content-between align-items-center">
                        <h4 class="mb-0"><i class="fas fa-sync-alt"></i> Renew Subscription</h4>
                        <div>
                            <a href="index.php" class="btn btn-secondary btn-sm">
                                <i class="fas fa-arrow-left"></i> Back to List
                            </a>
                        </div>
                    </div>
                </div>
                
                <div class="p-4">
                    <?php if ($success): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle"></i> <?php echo $success; ?>
                            <br><small>Redirecting to subscription list...</small>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger"><?php echo $error; ?></div>
                    <?php endif; ?>
                    
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-card">
                                <div class="alert alert-info">
                                    <strong>Doctor:</strong> <?php echo escape($subscription['full_name']); ?><br>
                                    <strong>Current Plan:</strong> <?php echo ucfirst($subscription['plan_type']); ?><br>
                                    <strong>Current End Date:</strong> 
                                    <?php echo $subscription['end_date'] ? date(DISPLAY_DATE_FORMAT, strtotime($subscription['end_date'])) : 'Lifetime'; ?>
                                    <?php if ($subscription['end_date'] && strtotime($subscription['end_date']) < time()): ?>
                                        <span class="badge bg-danger">Expired</span>
                                    <?php endif; ?>
                                </div>
                                
                                <form method="POST" action="" id="renewForm">
                                    <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                    <input type="hidden" name="renewal_type" id="renewal_type" value="">
                                    <input type="hidden" name="amount" id="amount" value="">
                                    
                                    <h5 class="mb-3">Select Renewal Plan</h5>
                                    
                                    <div class="row">
                                        <div class="col-md-3">
                                            <div class="plan-card" data-plan="1month" data-amount="9.99">
                                                <h5>1 Month</h5>
                                                <div class="plan-price">$9.99</div>
                                                <small class="text-muted">30 days extension</small>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="plan-card" data-plan="6month" data-amount="49.99">
                                                <h5>6 Months</h5>
                                                <div class="plan-price">$49.99</div>
                                                <small class="text-muted">180 days extension</small>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="plan-card" data-plan="1year" data-amount="89.99">
                                                <h5>1 Year</h5>
                                                <div class="plan-price">$89.99</div>
                                                <small class="text-muted">365 days extension</small>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="plan-card" data-plan="unlimited" data-amount="299.99">
                                                <h5>Unlimited</h5>
                                                <div class="plan-price">$299.99</div>
                                                <small class="text-muted">Lifetime access</small>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mt-4">
                                        <button type="submit" class="btn btn-success" id="submitBtn" disabled>
                                            <i class="fas fa-sync-alt"></i> Renew Subscription
                                        </button>
                                        <a href="index.php" class="btn btn-secondary">Cancel</a>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        let selectedPlan = null;
        
        document.querySelectorAll('.plan-card').forEach(card => {
            card.addEventListener('click', function() {
                // Remove selected class from all cards
                document.querySelectorAll('.plan-card').forEach(c => c.classList.remove('selected'));
                
                // Add selected class to clicked card
                this.classList.add('selected');
                
                // Set hidden fields
                const plan = this.dataset.plan;
                const amount = this.dataset.amount;
                document.getElementById('renewal_type').value = plan;
                document.getElementById('amount').value = amount;
                
                // Enable submit button
                document.getElementById('submitBtn').disabled = false;
            });
        });
    </script>
</body>
</html>