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

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

requireLogin();

// Redirect admin to admin profile
if (isAdmin()) {
    header('Location: ../admin/profile.php');
    exit;
}

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

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

if (!$user) {
    header('Location: ../login.php');
    exit;
}

// Get subscription info
$subscription = getUserSubscription($userId);

// Get practice statistics
$stmt = $pdo->prepare("SELECT 
                      COUNT(*) as total_cases,
                      COUNT(DISTINCT patient_mobile) as unique_patients,
                      SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_cases,
                      SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) as closed_cases
                      FROM cases WHERE user_id = ?");
$stmt->execute([$userId]);
$stats = $stmt->fetch();

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = "Security token validation failed.";
    } else {
        $action = $_POST['action'] ?? '';
        
        if ($action == 'profile') {
            $fullName = trim($_POST['full_name']);
            $email = trim($_POST['email']);
            
            $errors = [];
            if (!isRequired($fullName)) $errors[] = "Full name is required";
            if (!isValidEmail($email)) $errors[] = "Valid email is required";
            
            // Check email uniqueness
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
            $stmt->execute([$email, $userId]);
            if ($stmt->fetch()) $errors[] = "Email already in use";
            
            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!";
                    $user['full_name'] = $fullName;
                    $user['email'] = $email;
                } else {
                    $error = "Failed to update profile";
                }
            } else {
                $error = implode("<br>", $errors);
            }
            
        } elseif ($action == 'password') {
            $currentPassword = $_POST['current_password'];
            $newPassword = $_POST['new_password'];
            $confirmPassword = $_POST['confirm_password'];
            
            if (!password_verify($currentPassword, $user['password_hash'])) {
                $error = "Current password is incorrect";
            } elseif ($newPassword != $confirmPassword) {
                $error = "New passwords do not match";
            } else {
                $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";
                    }
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My 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>
        body { background: #f0f2f5; }
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #1a472a 0%, #0d2818 100%);
            position: fixed;
            left: 0;
            top: 0;
            width: 260px;
            z-index: 100;
        }
        .sidebar .nav-link {
            color: rgba(255,255,255,0.8);
            padding: 12px 20px;
            margin: 5px 10px;
            border-radius: 8px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover { background: rgba(255,255,255,0.1); transform: translateX(5px); }
        .sidebar .nav-link.active { background: #2ecc71; color: white; }
        .sidebar .nav-link i { margin-right: 10px; width: 20px; }
        .main-content { margin-left: 260px; padding: 20px; }
        .top-navbar {
            background: white;
            border-radius: 12px;
            padding: 15px 25px;
            margin-bottom: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .profile-card {
            background: white;
            border-radius: 12px;
            padding: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            margin-bottom: 20px;
        }
        .profile-avatar {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            background: linear-gradient(135deg, #2ecc71 0%, #27ae60 100%);
            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: #2ecc71; font-weight: bold; }
        @media (max-width: 768px) {
            .sidebar { width: 70px; }
            .sidebar .nav-link span { display: none; }
            .sidebar .nav-link i { margin-right: 0; font-size: 20px; }
            .main-content { margin-left: 70px; }
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="text-center py-4">
            <h4 class="text-white mb-0">🏥 Homoeopathy</h4>
            <small class="text-white-50">Kent's Repertory</small>
        </div>
        <nav class="nav flex-column mt-3">
            <a class="nav-link" href="dashboard.php"><i class="fas fa-tachometer-alt"></i> <span>Dashboard</span></a>
            <a class="nav-link" href="cases/list.php"><i class="fas fa-folder-open"></i> <span>My Cases</span></a>
            <a class="nav-link" href="cases/new.php"><i class="fas fa-plus-circle"></i> <span>New Case</span></a>
            <a class="nav-link" href="repertory/index.php"><i class="fas fa-book"></i> <span>Repertory</span></a>
            <a class="nav-link" href="materia-medica/index.php"><i class="fas fa-capsules"></i> <span>Materia Medica</span></a>
            <a class="nav-link" href="ai/analyze.php"><i class="fas fa-robot"></i> <span>AI Analysis</span></a>
            <a class="nav-link" href="reports/index.php"><i class="fas fa-chart-line"></i> <span>Reports</span></a>
            <a class="nav-link active" href="profile.php"><i class="fas fa-user"></i> <span>My Profile</span></a>
            <hr class="bg-secondary my-3">
            <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> <span>Logout</span></a>
        </nav>
    </div>
    
    <!-- Main Content -->
    <div class="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"></i> My Profile</h4>
                <div>
                    <span class="me-3"><i class="fas fa-user-circle"></i> Dr. <?php echo escape($_SESSION['full_name']); ?></span>
                </div>
            </div>
        </div>
        
        <?php if ($message): ?>
            <div class="alert alert-success alert-dismissible fade show"><?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"><?php echo $error; ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>
        
        <div class="row">
            <div class="col-md-4">
                <div class="profile-card text-center">
                    <div class="profile-avatar"><i class="fas fa-user-md"></i></div>
                    <h4><?php echo escape($user['full_name']); ?></h4>
                    <p class="text-muted">@<?php echo $user['username']; ?></p>
                    <p><i class="fas fa-envelope"></i> <?php echo $user['email']; ?></p>
                    <p><i class="fas fa-calendar-alt"></i> Joined: <?php echo date('d-m-Y', strtotime($user['created_at'])); ?></p>
                    <hr>
                    <div class="row text-center">
                        <div class="col-6">
                            <h5><?php echo $stats['total_cases']; ?></h5>
                            <small>Total Cases</small>
                        </div>
                        <div class="col-6">
                            <h5><?php echo $stats['unique_patients']; ?></h5>
                            <small>Patients</small>
                        </div>
                    </div>
                </div>
                
                <div class="profile-card">
                    <h5><i class="fas fa-credit-card"></i> Subscription</h5>
                    <?php if ($subscription): ?>
                        <p><strong>Plan:</strong> <?php echo ucfirst($subscription['plan_type']); ?></p>
                        <p><strong>Valid Until:</strong> <?php echo $subscription['end_date'] ? date('d-m-Y', strtotime($subscription['end_date'])) : 'Lifetime'; ?></p>
                        <?php if ($subscription['plan_type'] != 'unlimited' && $subscription['days_remaining'] > 0): ?>
                            <div class="progress mb-2">
                                <div class="progress-bar bg-success" style="width: <?php echo min(100, ($subscription['days_remaining'] / 365) * 100); ?>%"></div>
                            </div>
                            <small><?php echo $subscription['days_remaining']; ?> days remaining</small>
                        <?php elseif ($subscription['plan_type'] != 'unlimited' && $subscription['days_remaining'] <= 0): ?>
                            <span class="badge bg-danger">Expired</span>
                        <?php endif; ?>
                    <?php else: ?>
                        <p class="text-muted">No active subscription</p>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="col-md-8">
                <div class="profile-card">
                    <ul class="nav nav-tabs mb-4">
                        <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#editProfile">Edit Profile</button></li>
                        <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#changePassword">Change Password</button></li>
                        <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#practiceStats">Practice Statistics</button></li>
                    </ul>
                    
                    <div class="tab-content">
                        <!-- Edit Profile Tab -->
                        <div class="tab-pane fade show active" id="editProfile">
                            <form method="POST">
                                <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                <input type="hidden" name="action" value="profile">
                                
                                <div class="mb-3">
                                    <label class="form-label">Username</label>
                                    <input type="text" class="form-control" value="<?php echo escape($user['username']); ?>" disabled>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Full Name *</label>
                                    <input type="text" class="form-control" name="full_name" value="<?php echo escape($user['full_name']); ?>" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Email Address *</label>
                                    <input type="email" class="form-control" name="email" value="<?php echo $user['email']; ?>" required>
                                </div>
                                
                                <button type="submit" class="btn btn-primary">Update Profile</button>
                            </form>
                        </div>
                        
                        <!-- Change Password Tab -->
                        <div class="tab-pane fade" id="changePassword">
                            <form method="POST">
                                <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                <input type="hidden" name="action" value="password">
                                
                                <div class="mb-3">
                                    <label class="form-label">Current Password</label>
                                    <input type="password" class="form-control" name="current_password" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label 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 class="form-label">Confirm New Password</label>
                                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                                    <span id="passwordMatch" class="small"></span>
                                </div>
                                
                                <button type="submit" class="btn btn-primary">Change Password</button>
                            </form>
                        </div>
                        
                        <!-- Practice Statistics Tab -->
                        <div class="tab-pane fade" id="practiceStats">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label>Total Cases</label>
                                        <h3><?php echo $stats['total_cases']; ?></h3>
                                    </div>
                                    <div class="mb-3">
                                        <label>Active Cases</label>
                                        <h3 class="text-success"><?php echo $stats['active_cases']; ?></h3>
                                    </div>
                                    <div class="mb-3">
                                        <label>Closed Cases</label>
                                        <h3 class="text-secondary"><?php echo $stats['closed_cases']; ?></h3>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label>Unique Patients</label>
                                        <h3><?php echo $stats['unique_patients']; ?></h3>
                                    </div>
                                    <div class="mb-3">
                                        <label>Account Created</label>
                                        <h6><?php echo date('d-m-Y', strtotime($user['created_at'])); ?></h6>
                                    </div>
                                    <?php if($user['last_login']): ?>
                                    <div class="mb-3">
                                        <label>Last Login</label>
                                        <h6><?php echo date('d-m-Y H:i', strtotime($user['last_login'])); ?></h6>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        document.getElementById('confirm_password')?.addEventListener('input', function() {
            const password = document.getElementById('new_password').value;
            const confirm = this.value;
            const span = document.getElementById('passwordMatch');
            if (password === confirm && password !== '') {
                span.innerHTML = '<i class="fas fa-check-circle text-success"></i> Passwords match';
                span.className = 'text-success';
            } else if (confirm !== '') {
                span.innerHTML = '<i class="fas fa-times-circle text-danger"></i> Passwords do not match';
                span.className = 'text-danger';
            } else {
                span.innerHTML = '';
            }
        });
    </script>
</body>
</html>