<?php
/**
 * Edit Subscription
 * Update subscription details
 */

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;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = "Security token validation failed.";
    } else {
        $planType = $_POST['plan_type'];
        $amount = $_POST['amount'] ?? 0;
        $startDate = $_POST['start_date'];
        $endDate = $_POST['end_date'];
        $isActive = isset($_POST['is_active']) ? 1 : 0;
        
        // Validate dates
        $errors = [];
        if (!empty($endDate) && strtotime($endDate) < strtotime($startDate)) {
            $errors[] = "End date cannot be before start date";
        }
        
        if (empty($errors)) {
            $stmt = $pdo->prepare("UPDATE subscriptions 
                                  SET plan_type = ?, amount = ?, start_date = ?, end_date = ?, is_active = ?
                                  WHERE id = ?");
            if ($stmt->execute([$planType, $amount, $startDate, $endDate ?: null, $isActive, $subscriptionId])) {
                $success = "Subscription updated successfully!";
                // Refresh subscription data
                $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();
            } else {
                $error = "Failed to update subscription";
            }
        } else {
            $error = implode("<br>", $errors);
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit 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;
        }
    </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-edit"></i> Edit 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"><?php echo $success; ?></div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger"><?php echo $error; ?></div>
                    <?php endif; ?>
                    
                    <div class="row">
                        <div class="col-md-8">
                            <div class="form-card">
                                <form method="POST" action="">
                                    <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Doctor</label>
                                        <input type="text" class="form-control" value="<?php echo escape($subscription['full_name']); ?>" disabled>
                                        <small class="text-muted"><?php echo $subscription['email']; ?></small>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="plan_type" class="form-label">Plan Type</label>
                                            <select class="form-control" id="plan_type" name="plan_type">
                                                <option value="1month" <?php echo $subscription['plan_type'] == '1month' ? 'selected' : ''; ?>>1 Month</option>
                                                <option value="6month" <?php echo $subscription['plan_type'] == '6month' ? 'selected' : ''; ?>>6 Months</option>
                                                <option value="1year" <?php echo $subscription['plan_type'] == '1year' ? 'selected' : ''; ?>>1 Year</option>
                                                <option value="unlimited" <?php echo $subscription['plan_type'] == 'unlimited' ? 'selected' : ''; ?>>Unlimited</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="amount" class="form-label">Amount (USD)</label>
                                            <input type="number" class="form-control" id="amount" name="amount" 
                                                   step="0.01" value="<?php echo $subscription['amount']; ?>" required>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="start_date" class="form-label">Start Date</label>
                                            <input type="date" class="form-control" id="start_date" name="start_date" 
                                                   value="<?php echo $subscription['start_date']; ?>" required>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="end_date" class="form-label">End Date</label>
                                            <input type="date" class="form-control" id="end_date" name="end_date" 
                                                   value="<?php echo $subscription['end_date']; ?>">
                                            <small class="text-muted">Leave empty for unlimited plans</small>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="is_active" name="is_active" 
                                                   <?php echo $subscription['is_active'] ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="is_active">
                                                Active Subscription
                                            </label>
                                        </div>
                                    </div>
                                    
                                    <div class="mt-4">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-save"></i> Update Subscription
                                        </button>
                                        <a href="index.php" class="btn btn-secondary">Cancel</a>
                                    </div>
                                </form>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0">Subscription Info</h6>
                                </div>
                                <div class="card-body">
                                    <p><strong>Created:</strong> <?php echo date(DISPLAY_DATE_TIME_FORMAT, strtotime($subscription['created_at'])); ?></p>
                                    <p><strong>Status:</strong> 
                                        <span class="badge bg-<?php echo $subscription['is_active'] ? 'success' : 'danger'; ?>">
                                            <?php echo $subscription['is_active'] ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </p>
                                    <?php if ($subscription['end_date'] && $subscription['plan_type'] != 'unlimited'): ?>
                                        <?php $daysLeft = (strtotime($subscription['end_date']) - time()) / 86400; ?>
                                        <p><strong>Days Remaining:</strong> 
                                            <span class="badge bg-<?php echo $daysLeft > 0 ? 'success' : 'danger'; ?>">
                                                <?php echo round($daysLeft); ?> days
                                            </span>
                                        </p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>