<?php
/**
 * Add New Subscription
 * Create a new subscription for a doctor
 */

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

requireAdmin();

$pdo = getDB();
$error = '';
$success = '';

// Get active doctors without active subscription
$stmt = $pdo->query("SELECT u.id, u.full_name, u.email 
                    FROM users u 
                    WHERE u.role = 'doctor' 
                    AND u.is_active = 1
                    AND NOT EXISTS (
                        SELECT 1 FROM subscriptions s 
                        WHERE s.user_id = u.id 
                        AND s.is_active = 1 
                        AND (s.plan_type = 'unlimited' OR s.end_date >= CURDATE())
                    )
                    ORDER BY u.full_name");
$doctors = $stmt->fetchAll();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = "Security token validation failed.";
    } else {
        $doctorId = $_POST['doctor_id'];
        $planType = $_POST['plan_type'];
        $amount = $_POST['amount'] ?? 0;
        $startDate = $_POST['start_date'] ?? date('Y-m-d');
        
        // Validation
        $errors = [];
        
        if (empty($doctorId)) {
            $errors[] = "Please select a doctor";
        }
        
        if (empty($planType) || $planType == 'none') {
            $errors[] = "Please select a plan";
        }
        
        // Check if doctor already has active subscription
        if (empty($errors)) {
            $stmt = $pdo->prepare("SELECT id FROM subscriptions 
                                  WHERE user_id = ? AND is_active = 1 
                                  AND (plan_type = 'unlimited' OR end_date >= CURDATE())");
            $stmt->execute([$doctorId]);
            if ($stmt->fetch()) {
                $errors[] = "Doctor already has an active subscription";
            }
        }
        
        if (empty($errors)) {
            $planDays = [
                '1month' => 30,
                '6month' => 180,
                '1year' => 365,
                'unlimited' => null
            ];
            
            $endDate = $planDays[$planType] ? date('Y-m-d', strtotime("+{$planDays[$planType]} days", strtotime($startDate))) : null;
            
            $stmt = $pdo->prepare("INSERT INTO subscriptions (user_id, plan_type, start_date, end_date, amount, is_active) 
                                  VALUES (?, ?, ?, ?, ?, 1)");
            if ($stmt->execute([$doctorId, $planType, $startDate, $endDate, $amount])) {
                $success = "Subscription added successfully!";
                header("refresh:2;url=index.php");
            } else {
                $error = "Failed to add 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>Add 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="../rubrics/index.php">
                        <i class="fas fa-tree"></i> Rubrics
                    </a>
                    <a class="nav-link" href="../remedies/index.php">
                        <i class="fas fa-capsules"></i> Remedies
                    </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-plus"></i> Add 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">
                            <i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?>
                        </div>
                    <?php endif; ?>
                    
                    <div class="form-card">
                        <form method="POST" action="">
                            <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                            
                            <div class="mb-3">
                                <label for="doctor_id" class="form-label">Select Doctor *</label>
                                <select class="form-control" id="doctor_id" name="doctor_id" required>
                                    <option value="">-- Select Doctor --</option>
                                    <?php foreach($doctors as $doctor): ?>
                                        <option value="<?php echo $doctor['id']; ?>">
                                            <?php echo escape($doctor['full_name']); ?> (<?php echo $doctor['email']; ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <?php if(empty($doctors)): ?>
                                    <small class="text-warning">No eligible doctors found. All doctors already have active subscriptions.</small>
                                <?php endif; ?>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="plan_type" class="form-label">Subscription Plan *</label>
                                    <select class="form-control" id="plan_type" name="plan_type" required onchange="updateAmount()">
                                        <option value="none">-- Select Plan --</option>
                                        <option value="1month">1 Month - $9.99</option>
                                        <option value="6month">6 Months - $49.99</option>
                                        <option value="1year">1 Year - $89.99</option>
                                        <option value="unlimited">Unlimited - $299.99</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" 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 date('Y-m-d'); ?>">
                                </div>
                            </div>
                            
                            <div class="alert alert-info mt-3">
                                <i class="fas fa-info-circle"></i> 
                                <strong>Note:</strong> The subscription will be activated immediately. 
                                The doctor will have access based on the plan selected.
                            </div>
                            
                            <div class="mt-4">
                                <button type="submit" class="btn btn-primary" <?php echo empty($doctors) ? 'disabled' : ''; ?>>
                                    <i class="fas fa-save"></i> Add Subscription
                                </button>
                                <a href="index.php" class="btn btn-secondary">Cancel</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        function updateAmount() {
            const plan = document.getElementById('plan_type').value;
            const amountField = document.getElementById('amount');
            const amounts = {
                '1month': 9.99,
                '6month': 49.99,
                '1year': 89.99,
                'unlimited': 299.99
            };
            if (amounts[plan]) {
                amountField.value = amounts[plan];
            } else {
                amountField.value = '';
            }
        }
    </script>
</body>
</html>