<?php
/**
 * Add New Doctor
 * Create a new doctor account with subscription
 */

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

requireAdmin();

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Validate CSRF token
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = "Security token validation failed.";
    } else {
        $fullName = trim($_POST['full_name']);
        $username = trim($_POST['username']);
        $email = trim($_POST['email']);
        $password = $_POST['password'];
        $confirmPassword = $_POST['confirm_password'];
        $planType = $_POST['plan_type'] ?? null;
        $amount = $_POST['amount'] ?? 0;
        
        // Validation
        $errors = [];
        
        if (!isRequired($fullName)) {
            $errors[] = "Full name is required";
        }
        
        if (!isRequired($username)) {
            $errors[] = "Username is required";
        } elseif (!isAlphanumeric($username, true)) {
            $errors[] = "Username can only contain letters and numbers";
        } elseif (!isLengthBetween($username, 3, 50)) {
            $errors[] = "Username must be between 3 and 50 characters";
        }
        
        if (!isValidEmail($email)) {
            $errors[] = "Valid email is required";
        }
        
        if (!isRequired($password)) {
            $errors[] = "Password is required";
        } else {
            $passwordValidation = validatePasswordStrength($password);
            if (!$passwordValidation['valid']) {
                $errors = array_merge($errors, $passwordValidation['errors']);
            }
        }
        
        if ($password != $confirmPassword) {
            $errors[] = "Passwords do not match";
        }
        
        // Check if username exists
        if (empty($errors)) {
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
            $stmt->execute([$username]);
            if ($stmt->fetch()) {
                $errors[] = "Username already exists";
            }
        }
        
        // Check if email exists
        if (empty($errors)) {
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$email]);
            if ($stmt->fetch()) {
                $errors[] = "Email already registered";
            }
        }
        
        if (empty($errors)) {
            // Begin transaction
            beginTransaction();
            
            try {
                // Create doctor account
                $passwordHash = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("INSERT INTO users (username, email, full_name, password_hash, role, is_active) 
                                      VALUES (?, ?, ?, ?, 'doctor', 1)");
                $stmt->execute([$username, $email, $fullName, $passwordHash]);
                $doctorId = $pdo->lastInsertId();
                
                // Add subscription if selected
                if ($planType && $planType != 'none') {
                    $startDate = date('Y-m-d');
                    $endDate = null;
                    
                    $planDays = [
                        '1month' => 30,
                        '6month' => 180,
                        '1year' => 365,
                        'unlimited' => null
                    ];
                    
                    if ($planDays[$planType]) {
                        $endDate = date('Y-m-d', strtotime("+{$planDays[$planType]} days"));
                    }
                    
                    $stmt = $pdo->prepare("INSERT INTO subscriptions (user_id, plan_type, start_date, end_date, amount, is_active) 
                                          VALUES (?, ?, ?, ?, ?, 1)");
                    $stmt->execute([$doctorId, $planType, $startDate, $endDate, $amount]);
                }
                
                commitTransaction();
                
                // Send welcome email (optional)
                // sendWelcomeEmail($email, $fullName, $username, $password);
                
                $success = "Doctor account created successfully!";
                
                // Redirect after 2 seconds
                header("refresh:2;url=index.php");
                
            } catch (Exception $e) {
                rollbackTransaction();
                $error = "Failed to create doctor: " . $e->getMessage();
            }
        } 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 New Doctor - 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;
        }
        .password-strength {
            height: 4px;
            margin-top: 5px;
            transition: all 0.3s;
        }
    </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 active" href="index.php">
                        <i class="fas fa-user-md"></i> Doctors
                    </a>
                    <a class="nav-link" href="../subscriptions/index.php">
                        <i class="fas fa-credit-card"></i> Subscriptions
                    </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="../reports/index.php">
                        <i class="fas fa-chart-line"></i> Reports
                    </a>
                    <a class="nav-link" href="../settings/index.php">
                        <i class="fas fa-cog"></i> Settings
                    </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-user-plus"></i> Add New Doctor</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 doctor 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="" id="doctorForm">
                            <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                            
                            <h5 class="mb-3"><i class="fas fa-user-circle"></i> Account Information</h5>
                            <hr>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="full_name" class="form-label">Full Name *</label>
                                    <input type="text" class="form-control" id="full_name" name="full_name" 
                                           value="<?php echo $_POST['full_name'] ?? ''; ?>" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="username" class="form-label">Username *</label>
                                    <input type="text" class="form-control" id="username" name="username" 
                                           value="<?php echo $_POST['username'] ?? ''; ?>" required>
                                    <small class="text-muted">Used for login (letters and numbers only)</small>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="email" class="form-label">Email Address *</label>
                                    <input type="email" class="form-control" id="email" name="email" 
                                           value="<?php echo $_POST['email'] ?? ''; ?>" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="plan_type" class="form-label">Initial Subscription Plan</label>
                                    <select class="form-control" id="plan_type" name="plan_type">
                                        <option value="none">No Subscription (Select later)</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>
                            
                            <div class="row" id="amountRow" style="display: none;">
                                <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 $_POST['amount'] ?? ''; ?>">
                                </div>
                            </div>
                            
                            <h5 class="mb-3 mt-4"><i class="fas fa-key"></i> Password</h5>
                            <hr>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="password" class="form-label">Password *</label>
                                    <input type="password" class="form-control" id="password" name="password" required>
                                    <div class="password-strength" id="passwordStrength"></div>
                                    <small class="text-muted">Minimum 6 characters, at least one uppercase and one number</small>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="confirm_password" class="form-label">Confirm Password *</label>
                                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                                    <small id="passwordMatch" class="text-muted"></small>
                                </div>
                            </div>
                            
                            <div class="alert alert-info mt-3">
                                <i class="fas fa-info-circle"></i> 
                                <strong>Doctor Credentials:</strong> The doctor will receive an email with login instructions.
                                Default login URL: <?php echo APP_URL; ?>/login.php
                            </div>
                            
                            <div class="mt-4">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> Create Doctor Account
                                </button>
                                <a href="index.php" class="btn btn-secondary">Cancel</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // Plan selection change
        document.getElementById('plan_type').addEventListener('change', function() {
            const amountRow = document.getElementById('amountRow');
            const selectedPlan = this.value;
            
            if (selectedPlan !== 'none') {
                amountRow.style.display = 'flex';
                // Auto-fill amount based on plan
                const amounts = {
                    '1month': 9.99,
                    '6month': 49.99,
                    '1year': 89.99,
                    'unlimited': 299.99
                };
                if (amounts[selectedPlan]) {
                    document.getElementById('amount').value = amounts[selectedPlan];
                }
            } else {
                amountRow.style.display = 'none';
            }
        });
        
        // Password strength indicator
        document.getElementById('password').addEventListener('input', function() {
            const password = this.value;
            let strength = 0;
            let color = '#dc3545';
            let width = '20%';
            
            if (password.length >= 6) strength++;
            if (password.match(/[A-Z]/)) strength++;
            if (password.match(/[a-z]/)) strength++;
            if (password.match(/[0-9]/)) strength++;
            
            switch(strength) {
                case 1: color = '#dc3545'; width = '25%'; break;
                case 2: color = '#ffc107'; width = '50%'; break;
                case 3: color = '#17a2b8'; width = '75%'; break;
                case 4: color = '#28a745'; width = '100%'; break;
                default: color = '#dc3545'; width = '20%';
            }
            
            const strengthDiv = document.getElementById('passwordStrength');
            strengthDiv.style.background = color;
            strengthDiv.style.width = width;
            strengthDiv.style.height = '4px';
            strengthDiv.style.marginTop = '5px';
            strengthDiv.style.borderRadius = '2px';
        });
        
        // Password match validation
        document.getElementById('confirm_password').addEventListener('input', function() {
            const password = document.getElementById('password').value;
            const confirm = this.value;
            const matchSpan = document.getElementById('passwordMatch');
            
            if (password === confirm && password !== '') {
                matchSpan.innerHTML = '<i class="fas fa-check-circle text-success"></i> Passwords match';
                matchSpan.className = 'text-success';
            } else if (confirm !== '') {
                matchSpan.innerHTML = '<i class="fas fa-times-circle text-danger"></i> Passwords do not match';
                matchSpan.className = 'text-danger';
            } else {
                matchSpan.innerHTML = '';
            }
        });
        
        // Trigger plan change on load
        if (document.getElementById('plan_type').value !== 'none') {
            document.getElementById('amountRow').style.display = 'flex';
        }
    </script>
</body>
</html>