<?php
session_start();
require_once '../config/database.php';
require_once '../config/security.php';

if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] != 'admin') {
    header('Location: ../index.php');
    exit();
}

$admin_id = $_SESSION['user_id'];
$conn = getDBConnection();

// Get user details
$user_query = "SELECT * FROM users WHERE id = ?";
$stmt = $conn->prepare($user_query);
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$user_result = $stmt->get_result();
$user = $user_result->fetch_assoc();
$stmt->close();

// Handle password update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_password'])) {
    requireCSRFToken();
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];

    if (password_verify($current_password, $user['password'])) {
        if ($new_password === $confirm_password) {
            if (strlen($new_password) >= 8) {
                $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                $update_query = "UPDATE users SET password = ? WHERE id = ?";
                $stmt = $conn->prepare($update_query);
                $stmt->bind_param("si", $hashed_password, $admin_id);
                $stmt->execute();
                $stmt->close();
                $success_message = "Password updated successfully!";

                // Update session
                $user_query = "SELECT * FROM users WHERE id = ?";
                $stmt = $conn->prepare($user_query);
                $stmt->bind_param("i", $admin_id);
                $stmt->execute();
                $user_result = $stmt->get_result();
                $user = $user_result->fetch_assoc();
                $stmt->close();
            } else {
                $error_message = "Password must be at least 8 characters!";
            }
        } else {
            $error_message = "New passwords do not match!";
        }
    } else {
        $error_message = "Current password is incorrect!";
    }
}

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Profile - CODELAB</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <script src="../assets/js/dark-mode.js" defer></script>
</head>
<body>
    <nav class="navbar">
        <div class="nav-container">
            <div class="nav-brand">
                <div class="nav-avatar"><?php echo strtoupper(substr($_SESSION['full_name'], 0, 1)); ?></div>
                <h2>CODELAB - Admin</h2>
            </div>
            <button class="burger-menu" onclick="toggleMenu()">
                <span></span>
                <span></span>
                <span></span>
            </button>
            <div class="nav-menu" id="nav-menu">
                <a href="dashboard.php" class="nav-link">Dashboard</a>
                <a href="users.php" class="nav-link">Users</a>
                <a href="subjects.php" class="nav-link">Subjects</a>
                <a href="profile.php" class="nav-link active">Profile</a>
                <a href="../auth/logout.php" class="nav-link logout">Logout</a>
            </div>
        </div>
    </nav>

    <div class="main-content">
        <div class="page-header">
            <h1>👤 Admin Profile</h1>
            <p>Manage your admin account settings</p>
        </div>

        <?php if (isset($success_message)): ?>
            <div class="alert alert-success" style="max-width: 800px; margin: 0 auto 20px;">
                <?php echo $success_message; ?>
            </div>
        <?php endif; ?>

        <?php if (isset($error_message)): ?>
            <div class="alert alert-error" style="max-width: 800px; margin: 0 auto 20px;">
                <?php echo $error_message; ?>
            </div>
        <?php endif; ?>

        <!-- Account Information -->
        <div class="dashboard-section" style="max-width: 800px; margin: 0 auto 30px;">
            <div class="section-header">
                <h2>📝 Account Information</h2>
            </div>
            <div style="padding: 20px;">
                <div class="form-group">
                    <label>Username</label>
                    <input type="text" value="<?php echo htmlspecialchars($user['username']); ?>" disabled style="background: #f0f0f0;">
                </div>
                <div class="form-group">
                    <label>Full Name</label>
                    <input type="text" value="<?php echo htmlspecialchars($user['full_name']); ?>" disabled style="background: #f0f0f0;">
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" value="<?php echo htmlspecialchars($user['email']); ?>" disabled style="background: #f0f0f0;">
                </div>
                <div class="form-group">
                    <label>User Type</label>
                    <input type="text" value="Administrator" disabled style="background: #f0f0f0;">
                </div>
                <div class="form-group">
                    <label>Member Since</label>
                    <input type="text" value="<?php echo date('M d, Y', strtotime($user['created_at'])); ?>" disabled style="background: #f0f0f0;">
                </div>
            </div>
        </div>

        <!-- Change Password -->
        <div class="dashboard-section" style="max-width: 800px; margin: 0 auto;">
            <div class="section-header">
                <h2>🔒 Change Password</h2>
            </div>
            <form method="POST" id="password-form">
                <?php echo csrfField(); ?>
                <div class="form-group">
                    <label>Current Password *</label>
                    <input type="password" name="current_password" required>
                    <small style="color: #666;">Enter your current password (default is: admin123)</small>
                </div>
                <div class="form-group">
                    <label>New Password *</label>
                    <input type="password" name="new_password" id="new_password" minlength="8" required>
                    <small style="color: #666;">Minimum 8 characters. Use letters, numbers, and symbols.</small>
                </div>
                <div class="form-group">
                    <label>Confirm New Password *</label>
                    <input type="password" name="confirm_password" id="confirm_password" minlength="8" required>
                </div>
                <div style="background: #fff3cd; padding: 15px; border-radius: 8px; border-left: 4px solid #ffc107; margin-bottom: 20px;">
                    <strong>⚠️ Important:</strong>
                    <ul style="margin: 10px 0 0 20px; line-height: 1.8;">
                        <li>Use a strong password (minimum 8 characters)</li>
                        <li>Include uppercase, lowercase, numbers, and symbols</li>
                        <li>Don't use common words or your username</li>
                        <li>Write it down somewhere safe!</li>
                    </ul>
                </div>
                <button type="submit" name="update_password" class="btn btn-primary">🔒 Change Password</button>
            </form>
        </div>
    </div>

    <script>
        function toggleMenu() {
            const navMenu = document.getElementById('nav-menu');
            navMenu.classList.toggle('active');
        }

        // Password match validation
        document.getElementById('password-form').addEventListener('submit', function(e) {
            const newPassword = document.getElementById('new_password').value;
            const confirmPassword = document.getElementById('confirm_password').value;

            if (newPassword !== confirmPassword) {
                e.preventDefault();
                alert('⚠️ Passwords do not match!');
                return false;
            }

            if (newPassword.length < 8) {
                e.preventDefault();
                alert('⚠️ Password must be at least 8 characters long!');
                return false;
            }
        });
    </script>
</body>
</html>
