<?php
/**
 * Admin Profile Page
 * Update admin profile information and password
 */

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

// Check if user is logged in and is admin
requireAdmin();

$pdo = getDB();
$userId = $_SESSION['user_id'];
$message = '';
$error = '';

// Get current admin data
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$userId]);
$admin = $stmt->fetch();

if (!$admin) {
    die("Admin not found");
}

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Generate CSRF token for security
    if (!isset($_POST['csrf_token']) || !verifyCsrfToken($_POST['csrf_token'])) {
        $error = "Security token validation failed. Please try again.";
    } else {
        $action = $_POST['action'] ?? '';
        
        if ($action == 'profile') {
            // Update profile information
            $fullName = trim($_POST['full_name']);
            $email = trim($_POST['email']);
            
            $errors = [];
            
            // Validate inputs
            if (!isRequired($fullName)) {
                $errors[] = "Full name is required";
            }
            
            if (!isValidEmail($email)) {
                $errors[] = "Valid email is required";
            }
            
            // Check if email already exists for other user
            if (empty($errors)) {
                $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
                $stmt->execute([$email, $userId]);
                if ($stmt->fetch()) {
                    $errors[] = "Email already in use by another account";
                }
            }
            
            if (empty($errors)) {
                $stmt = $pdo->prepare("UPDATE users SET full_name = ?, email = ? WHERE id = ?");
                if ($stmt->execute([$fullName, $email, $userId])) {
                    $_SESSION['full_name'] = $fullName;
                    $_SESSION['email'] = $email;
                    $message = "Profile updated successfully!";
                    // Refresh admin data
                    $admin['full_name'] = $fullName;
                    $admin['email'] = $email;
                } else {
                    $error = "Failed to update profile";
                }
            } else {
                $error = implode("<br>", $errors);
            }
            
        } elseif ($action == 'password') {
            // Update password
            $currentPassword = $_POST['current_password'];
            $newPassword = $_POST['new_password'];
            $confirmPassword = $_POST['confirm_password'];
            
            // Verify current password
            if (!password_verify($currentPassword, $admin['password_hash'])) {
                $error = "Current password is incorrect";
            } elseif ($newPassword != $confirmPassword) {
                $error = "New passwords do not match";
            } else {
                // Validate password strength
                $passwordValidation = validatePasswordStrength($newPassword);
                if (!$passwordValidation['valid']) {
                    $error = implode("<br>", $passwordValidation['errors']);
                } else {
                    $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
                    $stmt = $pdo->prepare("UPDATE users SET password_hash = ? WHERE id = ?");
                    if ($stmt->execute([$newHash, $userId])) {
                        $message = "Password changed successfully!";
                    } else {
                        $error = "Failed to change password";
                    }
                }
            }
        } elseif ($action == 'notification') {
            // Update notification settings (can be expanded)
            $emailNotifications = isset($_POST['email_notifications']) ? 1 : 0;
            // Store in settings table or user meta (simplified for now)
            $_SESSION['email_notifications'] = $emailNotifications;
            $message = "Notification settings updated!";
        }
    }
}

// Get admin statistics
$stmt = $pdo->prepare("SELECT 
                      (SELECT COUNT(*) FROM users WHERE role = 'doctor') as total_doctors,
                      (SELECT COUNT(*) FROM cases) as total_cases,
                      (SELECT COUNT(*) FROM subscriptions WHERE is_active = 1) as active_subs,
                      (SELECT COUNT(*) FROM rubrics) as total_rubrics");
$stmt->execute();
$stats = $stmt->fetch();

// Get login history (last 5 logins - simplified)
// In production, you would have a login_logs table
$loginHistory = [
    ['time' => date('Y-m-d H:i:s'), 'ip' => $_SERVER['REMOTE_ADDR'], 'device' => getDevice() . ' - ' . getBrowser()]
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Profile - <?php echo APP_NAME; ?></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;
        }
        .profile-avatar {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            background: #3498db;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
        }
        .profile-avatar i {
            font-size: 60px;
            color: white;
        }
        .nav-tabs .nav-link {
            color: #2c3e50;
        }
        .nav-tabs .nav-link.active {
            color: #3498db;
            font-weight: bold;
        }
    </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" 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 active" 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">My Profile</h4>
                        <div>
                            <span class="me-3">
                                <i class="fas fa-user-circle"></i> 
                                <?php echo escape($_SESSION['full_name']); ?>
                            </span>
                            <span class="badge bg-primary">Admin</span>
                        </div>
                    </div>
                </div>
                
                <div class="p-4">
                    <?php if ($message): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="fas fa-check-circle"></i> <?php echo $message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <div class="row">
                        <!-- Profile Sidebar -->
                        <div class="col-md-3">
                            <div class="card">
                                <div class="card-body text-center">
                                    <div class="profile-avatar">
                                        <i class="fas fa-user-shield"></i>
                                    </div>
                                    <h5 class="mt-2"><?php echo escape($admin['full_name']); ?></h5>
                                    <p class="text-muted">@<?php echo $admin['username']; ?></p>
                                    <p>
                                        <span class="badge bg-primary">Administrator</span>
                                    </p>
                                    <hr>
                                    <div class="text-start small">
                                        <p><i class="fas fa-calendar-alt"></i> Joined: <?php echo date(DISPLAY_DATE_FORMAT, strtotime($admin['created_at'])); ?></p>
                                        <p><i class="fas fa-envelope"></i> <?php echo $admin['email']; ?></p>
                                        <p><i class="fas fa-shield-alt"></i> Role: Super Admin</p>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Quick Stats -->
                            <div class="card mt-3">
                                <div class="card-header">
                                    <h6 class="mb-0">System at a Glance</h6>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>Total Doctors:</span>
                                        <strong><?php echo $stats['total_doctors']; ?></strong>
                                    </div>
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>Total Cases:</span>
                                        <strong><?php echo $stats['total_cases']; ?></strong>
                                    </div>
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>Active Subscriptions:</span>
                                        <strong><?php echo $stats['active_subs']; ?></strong>
                                    </div>
                                    <div class="d-flex justify-content-between">
                                        <span>Total Rubrics:</span>
                                        <strong><?php echo $stats['total_rubrics']; ?></strong>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Profile Tabs -->
                        <div class="col-md-9">
                            <div class="card">
                                <div class="card-header">
                                    <ul class="nav nav-tabs card-header-tabs" id="profileTabs" role="tablist">
                                        <li class="nav-item" role="presentation">
                                            <button class="nav-link active" id="profile-tab" data-bs-toggle="tab" 
                                                    data-bs-target="#profile" type="button" role="tab">
                                                <i class="fas fa-user-edit"></i> Edit Profile
                                            </button>
                                        </li>
                                        <li class="nav-item" role="presentation">
                                            <button class="nav-link" id="password-tab" data-bs-toggle="tab" 
                                                    data-bs-target="#password" type="button" role="tab">
                                                <i class="fas fa-key"></i> Change Password
                                            </button>
                                        </li>
                                        <li class="nav-item" role="presentation">
                                            <button class="nav-link" id="security-tab" data-bs-toggle="tab" 
                                                    data-bs-target="#security" type="button" role="tab">
                                                <i class="fas fa-shield-alt"></i> Security
                                            </button>
                                        </li>
                                        <li class="nav-item" role="presentation">
                                            <button class="nav-link" id="activity-tab" data-bs-toggle="tab" 
                                                    data-bs-target="#activity" type="button" role="tab">
                                                <i class="fas fa-history"></i> Activity
                                            </button>
                                        </li>
                                    </ul>
                                </div>
                                <div class="card-body">
                                    <div class="tab-content">
                                        <!-- Edit Profile Tab -->
                                        <div class="tab-pane fade show active" id="profile" role="tabpanel">
                                            <form method="POST" action="">
                                                <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                                <input type="hidden" name="action" value="profile">
                                                
                                                <div class="mb-3">
                                                    <label for="username" class="form-label">Username</label>
                                                    <input type="text" class="form-control" id="username" 
                                                           value="<?php echo escape($admin['username']); ?>" disabled>
                                                    <small class="text-muted">Username cannot be changed</small>
                                                </div>
                                                
                                                <div class="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($admin['full_name']); ?>" required>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label for="email" class="form-label">Email Address *</label>
                                                    <input type="email" class="form-control" id="email" 
                                                           name="email" value="<?php echo $admin['email']; ?>" required>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label class="form-label">Role</label>
                                                    <input type="text" class="form-control" value="Administrator" disabled>
                                                </div>
                                                
                                                <hr>
                                                
                                                <button type="submit" class="btn btn-primary">
                                                    <i class="fas fa-save"></i> Update Profile
                                                </button>
                                            </form>
                                        </div>
                                        
                                        <!-- Change Password Tab -->
                                        <div class="tab-pane fade" id="password" role="tabpanel">
                                            <form method="POST" action="">
                                                <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                                <input type="hidden" name="action" value="password">
                                                
                                                <div class="mb-3">
                                                    <label for="current_password" class="form-label">Current Password *</label>
                                                    <input type="password" class="form-control" id="current_password" 
                                                           name="current_password" required>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label for="new_password" class="form-label">New Password *</label>
                                                    <input type="password" class="form-control" id="new_password" 
                                                           name="new_password" required>
                                                    <small class="text-muted">
                                                        Minimum 6 characters, at least one uppercase letter and one number
                                                    </small>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label for="confirm_password" class="form-label">Confirm New Password *</label>
                                                    <input type="password" class="form-control" id="confirm_password" 
                                                           name="confirm_password" required>
                                                </div>
                                                
                                                <div class="alert alert-info">
                                                    <i class="fas fa-info-circle"></i> 
                                                    Password strength requirements:
                                                    <ul class="mb-0 mt-2">
                                                        <li>Minimum 6 characters</li>
                                                        <li>At least one uppercase letter (A-Z)</li>
                                                        <li>At least one lowercase letter (a-z)</li>
                                                        <li>At least one number (0-9)</li>
                                                    </ul>
                                                </div>
                                                
                                                <button type="submit" class="btn btn-warning">
                                                    <i class="fas fa-key"></i> Change Password
                                                </button>
                                            </form>
                                        </div>
                                        
                                        <!-- Security Tab -->
                                        <div class="tab-pane fade" id="security" role="tabpanel">
                                            <form method="POST" action="">
                                                <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                                <input type="hidden" name="action" value="notification">
                                                
                                                <div class="mb-3">
                                                    <div class="form-check form-switch">
                                                        <input class="form-check-input" type="checkbox" id="email_notifications" 
                                                               name="email_notifications" <?php echo isset($_SESSION['email_notifications']) && $_SESSION['email_notifications'] ? 'checked' : ''; ?>>
                                                        <label class="form-check-label" for="email_notifications">
                                                            Receive email notifications
                                                        </label>
                                                    </div>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <div class="form-check form-switch">
                                                        <input class="form-check-input" type="checkbox" id="login_alerts" name="login_alerts" checked>
                                                        <label class="form-check-label" for="login_alerts">
                                                            Alert me on new login from unknown device
                                                        </label>
                                                    </div>
                                                </div>
                                                
                                                <hr>
                                                
                                                <div class="mb-3">
                                                    <label class="form-label">Session Management</label>
                                                    <button type="button" class="btn btn-danger btn-sm" onclick="logoutAllDevices()">
                                                        <i class="fas fa-sign-out-alt"></i> Logout from all devices
                                                    </button>
                                                </div>
                                                
                                                <button type="submit" class="btn btn-primary">
                                                    <i class="fas fa-save"></i> Save Settings
                                                </button>
                                            </form>
                                        </div>
                                        
                                        <!-- Activity Tab -->
                                        <div class="tab-pane fade" id="activity" role="tabpanel">
                                            <h6>Recent Login Activity</h6>
                                            <div class="table-responsive">
                                                <table class="table table-sm">
                                                    <thead>
                                                        <tr><th>Time</th><th>IP Address</th><th>Device/Browser</th></tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach($loginHistory as $login): ?>
                                                        <tr>
                                                            <td><?php echo $login['time']; ?></td>
                                                            <td><?php echo $login['ip']; ?></td>
                                                            <td><?php echo $login['device']; ?></td>
                                                        </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                            
                                            <hr>
                                            
                                            <div class="alert alert-warning">
                                                <i class="fas fa-exclamation-triangle"></i> 
                                                <strong>Security Tip:</strong> Regularly review your login activity. 
                                                If you see any suspicious activity, change your password immediately.
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        function logoutAllDevices() {
            if (confirm('This will log you out from all devices. Are you sure?')) {
                // Implement logout all devices functionality
                window.location.href = 'logout-all.php';
            }
        }
        
        // Password strength indicator (optional enhancement)
        document.getElementById('new_password')?.addEventListener('input', function() {
            const password = this.value;
            let strength = 0;
            
            if (password.length >= 6) strength++;
            if (password.match(/[A-Z]/)) strength++;
            if (password.match(/[a-z]/)) strength++;
            if (password.match(/[0-9]/)) strength++;
            
            const strengthText = ['Very Weak', 'Weak', 'Fair', 'Good', 'Strong'];
            const strengthColor = ['danger', 'warning', 'info', 'primary', 'success'];
            
            // You can add a strength indicator element
        });
    </script>
</body>
</html>