<?php
/**
 * Edit Doctor
 * Update doctor profile and subscription
 */

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

requireAdmin();

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

// Get doctor details
$stmt = $pdo->prepare("SELECT u.*, 
                      s.id as subscription_id, s.plan_type, s.start_date, s.end_date, s.amount, s.is_active as sub_active
                      FROM users u 
                      LEFT JOIN subscriptions s ON u.id = s.user_id AND s.is_active = 1
                      WHERE u.id = ? AND u.role = 'doctor'");
$stmt->execute([$doctorId]);
$doctor = $stmt->fetch();

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = "Security token validation failed.";
    } else {
        $fullName = trim($_POST['full_name']);
        $email = trim($_POST['email']);
        $isActive = isset($_POST['is_active']) ? 1 : 0;
        $planType = $_POST['plan_type'] ?? null;
        $amount = $_POST['amount'] ?? 0;
        $newPassword = $_POST['new_password'] ?? '';
        
        // Validation
        $errors = [];
        
        if (!isRequired($fullName)) {
            $errors[] = "Full name is required";
        }
        
        if (!isValidEmail($email)) {
            $errors[] = "Valid email is required";
        }
        
        // Check if email exists for other user
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
        $stmt->execute([$email, $doctorId]);
        if ($stmt->fetch()) {
            $errors[] = "Email already in use by another account";
        }
        
        // Validate new password if provided
        if (!empty($newPassword)) {
            $passwordValidation = validatePasswordStrength($newPassword);
            if (!$passwordValidation['valid']) {
                $errors = array_merge($errors, $passwordValidation['errors']);
            }
        }
        
        if (empty($errors)) {
            beginTransaction();
            
            try {
                // Update user details
                $sql = "UPDATE users SET full_name = ?, email = ?, is_active = ?";
                $params = [$fullName, $email, $isActive];
                
                if (!empty($newPassword)) {
                    $passwordHash = password_hash($newPassword, PASSWORD_DEFAULT);
                    $sql .= ", password_hash = ?";
                    $params[] = $passwordHash;
                }
                
                $sql .= " WHERE id = ?";
                $params[] = $doctorId;
                
                $stmt = $pdo->prepare($sql);
                $stmt->execute($params);
                
                // Update subscription
                if ($planType && $planType != 'none') {
                    // Deactivate old subscription
                    $stmt = $pdo->prepare("UPDATE subscriptions SET is_active = 0 WHERE user_id = ?");
                    $stmt->execute([$doctorId]);
                    
                    // Create new subscription
                    $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();
                
                $success = "Doctor profile updated successfully!";
                
                // Refresh doctor data
                $stmt = $pdo->prepare("SELECT u.*, 
                                      s.id as subscription_id, s.plan_type, s.start_date, s.end_date, s.amount, s.is_active as sub_active
                                      FROM users u 
                                      LEFT JOIN subscriptions s ON u.id = s.user_id AND s.is_active = 1
                                      WHERE u.id = ?");
                $stmt->execute([$doctorId]);
                $doctor = $stmt->fetch();
                
            } catch (Exception $e) {
                rollbackTransaction();
                $error = "Failed to update: " . $e->getMessage();
            }
        } else {
            $error = implode("<br>", $errors);
        }
    }
}

// Get subscription history
$stmt = $pdo->prepare("SELECT * FROM subscriptions WHERE user_id = ? ORDER BY created_at DESC LIMIT 5");
$stmt->execute([$doctorId]);
$subscriptionHistory = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit 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;
        }
    </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-edit"></i> Edit Doctor: <?php echo escape($doctor['full_name']); ?></h4>
                        <div>
                            <a href="view.php?id=<?php echo $doctorId; ?>" class="btn btn-info btn-sm">
                                <i class="fas fa-eye"></i> View Profile
                            </a>
                            <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; ?>
                        </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="row">
                        <div class="col-md-8">
                            <div class="form-card">
                                <form method="POST" action="">
                                    <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                    
                                    <h5 class="mb-3"><i class="fas fa-user-circle"></i> Basic Information</h5>
                                    <hr>
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Username</label>
                                            <input type="text" class="form-control" value="<?php echo escape($doctor['username']); ?>" disabled>
                                            <small class="text-muted">Username cannot be changed</small>
                                        </div>
                                        <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 escape($doctor['full_name']); ?>" required>
                                        </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 $doctor['email']; ?>" required>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <div class="form-check mt-4">
                                                <input class="form-check-input" type="checkbox" id="is_active" name="is_active" 
                                                       <?php echo $doctor['is_active'] ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="is_active">
                                                    Account Active
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <h5 class="mb-3 mt-4"><i class="fas fa-credit-card"></i> Subscription</h5>
                                    <hr>
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="plan_type" class="form-label">Current Subscription Plan</label>
                                            <select class="form-control" id="plan_type" name="plan_type">
                                                <option value="none">No Active Plan</option>
                                                <option value="1month" <?php echo $doctor['plan_type'] == '1month' ? 'selected' : ''; ?>>1 Month - $9.99</option>
                                                <option value="6month" <?php echo $doctor['plan_type'] == '6month' ? 'selected' : ''; ?>>6 Months - $49.99</option>
                                                <option value="1year" <?php echo $doctor['plan_type'] == '1year' ? 'selected' : ''; ?>>1 Year - $89.99</option>
                                                <option value="unlimited" <?php echo $doctor['plan_type'] == 'unlimited' ? 'selected' : ''; ?>>Unlimited - $299.99</option>
                                            </select>
                                            <?php if ($doctor['end_date'] && $doctor['plan_type'] != 'unlimited'): ?>
                                                <small class="text-muted">Current plan expires: <?php echo date(DISPLAY_DATE_FORMAT, strtotime($doctor['end_date'])); ?></small>
                                            <?php endif; ?>
                                        </div>
                                        <div class="col-md-6 mb-3" id="amountDiv">
                                            <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 $doctor['amount']; ?>">
                                        </div>
                                    </div>
                                    
                                    <h5 class="mb-3 mt-4"><i class="fas fa-key"></i> Change Password</h5>
                                    <hr>
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="new_password" class="form-label">New Password (leave blank to keep current)</label>
                                            <input type="password" class="form-control" id="new_password" name="new_password">
                                            <small class="text-muted">Minimum 6 characters, at least one uppercase and one number</small>
                                        </div>
                                    </div>
                                    
                                    <div class="mt-4">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-save"></i> Save Changes
                                        </button>
                                        <a href="index.php" class="btn btn-secondary">Cancel</a>
                                    </div>
                                </form>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <!-- Subscription History -->
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0"><i class="fas fa-history"></i> Subscription History</h6>
                                </div>
                                <div class="card-body p-0">
                                    <div class="list-group list-group-flush">
                                        <?php foreach($subscriptionHistory as $sub): ?>
                                            <div class="list-group-item">
                                                <div class="d-flex justify-content-between">
                                                    <strong><?php echo ucfirst($sub['plan_type']); ?></strong>
                                                    <span class="badge <?php echo $sub['is_active'] ? 'bg-success' : 'bg-secondary'; ?>">
                                                        <?php echo $sub['is_active'] ? 'Active' : 'Expired'; ?>
                                                    </span>
                                                </div>
                                                <small class="text-muted">
                                                    <?php echo date(DISPLAY_DATE_FORMAT, strtotime($sub['start_date'])); ?> - 
                                                    <?php echo $sub['end_date'] ? date(DISPLAY_DATE_FORMAT, strtotime($sub['end_date'])) : 'Unlimited'; ?>
                                                </small><br>
                                                <small>Amount: <?php echo formatCurrency($sub['amount']); ?></small>
                                            </div>
                                        <?php endforeach; ?>
                                        <?php if(empty($subscriptionHistory)): ?>
                                            <div class="list-group-item text-muted text-center">
                                                No subscription history
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Quick Stats -->
                            <div class="card mt-3">
                                <div class="card-header">
                                    <h6 class="mb-0"><i class="fas fa-chart-bar"></i> Account Statistics</h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-2">
                                        <small class="text-muted">Joined:</small><br>
                                        <strong><?php echo date(DISPLAY_DATE_FORMAT, strtotime($doctor['created_at'])); ?></strong>
                                    </div>
                                    <?php if($doctor['last_login']): ?>
                                    <div class="mb-2">
                                        <small class="text-muted">Last Login:</small><br>
                                        <strong><?php echo date(DISPLAY_DATE_TIME_FORMAT, strtotime($doctor['last_login'])); ?></strong>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="../../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        // Show/hide amount based on plan selection
        document.getElementById('plan_type').addEventListener('change', function() {
            const amountDiv = document.getElementById('amountDiv');
            if (this.value !== 'none') {
                amountDiv.style.display = 'block';
                const amounts = {'1month': 9.99, '6month': 49.99, '1year': 89.99, 'unlimited': 299.99};
                if (amounts[this.value]) {
                    document.getElementById('amount').value = amounts[this.value];
                }
            } else {
                amountDiv.style.display = 'none';
            }
        });
        
        // Trigger on load
        if (document.getElementById('plan_type').value === 'none') {
            document.getElementById('amountDiv').style.display = 'none';
        }
    </script>
</body>
</html>