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

if (!isset($_SESSION['admin_id'])) {
    header("Location: ../index.php");
    exit;
}

$adminId = $_SESSION['admin_id'];
$stmt = $pdo->prepare("SELECT * FROM admins WHERE id = ?");
$stmt->execute([$adminId]);
$admin = $stmt->fetch();
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Profile | NROI Portal</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../assets/css/loader.css">
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/dashboard.css">
    <link rel="icon" type="image/png" href="../assets/images/nroi_logo.png">
    <style>
        .profile-container {
            max-width: 800px;
            margin: 0 auto;
            background: #fff;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.05);
        }

        .profile-header {
            display: flex;
            align-items: center;
            gap: 25px;
            padding-bottom: 30px;
            border-bottom: 1px solid #f1f5f9;
            margin-bottom: 35px;
        }

        .large-avatar {
            width: 100px;
            height: 100px;
            background: var(--primary-color);
            color: #fff;
            border-radius: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2.5rem;
            font-weight: 800;
            box-shadow: 0 10px 20px rgba(37, 99, 235, 0.2);
        }

        .profile-info h1 {
            margin: 0;
            font-size: 1.8rem;
            color: #1e293b;
        }

        .profile-info p {
            margin: 5px 0 0;
            color: #64748b;
            font-weight: 500;
        }

        .info-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
        }

        .info-item {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .info-label {
            font-size: 0.85rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #94a3b8;
            font-weight: 700;
        }

        .info-value {
            font-size: 1.1rem;
            color: #334155;
            font-weight: 600;
            padding: 12px 18px;
            background: #f8fafc;
            border-radius: 12px;
            border: 1px solid #f1f5f9;
        }
    </style>
</head>

<body class="dashboard-body">
    <?php include '../includes/loader.php'; ?>

    <aside class="sidebar">
        <div class="sidebar-brand-area">
            <div class="sidebar-role-badge">ADMIN</div>
        </div>
        <ul class="sidebar-menu">
            <li class="sidebar-item">
                <a href="dashboard.php" class="sidebar-link">
                    <i class="fas fa-th-large"></i> Overview
                </a>
            </li>
            <li class="sidebar-item">
                <a href="../api/users.php" class="sidebar-link">
                    <i class="fas fa-user-friends"></i> Accounts
                </a>
            </li>
            <li class="sidebar-item">
                <a href="management.php" class="sidebar-link">
                    <i class="fas fa-cog"></i> Management
                </a>
            </li>
            <li class="sidebar-item">
                <a href="../api/matches.php" class="sidebar-link">
                    <i class="fas fa-trophy"></i> Matches
                </a>
            </li>
            <li class="sidebar-item">
                <a href="../api/request.php" class="sidebar-link">
                    <i class="fas fa-inbox"></i> For Approval
                </a>
            </li>
            <li class="sidebar-item">
                <a href="../api/points_card.php" class="sidebar-link">
                    <i class="fas fa-id-card"></i> Points Card
                </a>
            </li>
            <li class="sidebar-item">
                <a href="system_logs.php" class="sidebar-link">
                    <i class="fas fa-list-alt"></i> System Log
                </a>
            </li>
        </ul>

        <div class="sidebar-profile">
            <div class="sidebar-user-card" id="profileToggle">
                <div class="user-avatar" style="width: 35px; height: 35px; min-width: 35px;">AD</div>
                <div class="sidebar-user-info">
                    <div class="sidebar-user-name">Administrator</div>
                    <div class="sidebar-user-role">System Admin</div>
                </div>
                <i class="fas fa-chevron-up" style="font-size: 0.7rem; color: #94a3b8;"></i>

                <div class="profile-dropdown" id="profileDropdown"
                    style="bottom: 100%; top: auto; right: 10px; left: 10px; width: auto; margin-bottom: 10px;">
                    <a href="profile.php" class="dropdown-item"><i class="far fa-user-circle"></i> My Profile</a>
                    <div style="height: 1px; background: rgba(0,0,0,0.05); margin: 5px 0;"></div>
                    <a href="../logout.php" class="dropdown-item logout"><i class="fas fa-sign-out-alt"></i> Logout</a>
                </div>
            </div>
        </div>
    </aside>

    <div class="main-layout">
        <main class="content-wrapper">
            <header class="welcome-header">
                <div class="header-brand-box">
                    <img src="../assets/images/nroi_logo.png" alt="NROI Logo" class="header-logo">
                    <div class="header-text">
                        <h2>NATIONAL RANGE OFFICERS INSTITUTE</h2>
                        <p>ADMINISTRATOR PROFILE</p>
                    </div>
                </div>
            </header>

            <div class="profile-container animated-fade-in">
                <div class="profile-header">
                    <div class="large-avatar">
                        <?php echo strtoupper(substr($admin['first_name'] ?? 'A', 0, 1)); ?>
                    </div>
                    <div class="profile-info">
                        <h1>
                            <?php echo htmlspecialchars(capitalizeWords(($admin['first_name'] ?? 'System') . ' ' . ($admin['last_name'] ?? 'Admin'))); ?>
                        </h1>
                        <p><i class="fas fa-shield-alt" style="color:var(--primary-color)"></i> System Administrator</p>
                    </div>
                </div>

                <div class="info-grid">
                    <div class="info-item">
                        <span class="info-label">First Name</span>
                        <div class="info-value">
                            <?php echo htmlspecialchars(capitalizeWords($admin['first_name'] ?? 'System')); ?>
                        </div>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Last Name</span>
                        <div class="info-value">
                            <?php echo htmlspecialchars(capitalizeWords($admin['last_name'] ?? 'Administrator')); ?>
                        </div>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Email Address</span>
                        <div class="info-value">
                            <?php echo htmlspecialchars($admin['email'] ?? 'admin@nroi.ccbis.com'); ?>
                        </div>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Phone Number</span>
                        <div class="info-value">
                            <?php echo htmlspecialchars($admin['phone_number'] ?? 'N/A'); ?>
                        </div>
                    </div>
                    <div class="info-item" style="grid-column: span 2;">
                        <span class="info-label">Username</span>
                        <div class="info-value" style="background: #eff6ff; color: #1d4ed8; border-color: #dbeafe;">
                            <?php echo htmlspecialchars($admin['username']); ?>
                        </div>
                    </div>
                </div>

            </div>

            <div style="margin-top: 35px; padding-top: 25px; border-top: 1.5px solid #f1f5f9;">
                <h2
                    style="font-size: 1.1rem; color: #1e293b; margin-bottom: 20px; display: flex; align-items: center; gap: 10px;">
                    <i class="fas fa-shield-alt" style="color:#ef4444"></i> Security & Password
                </h2>

                <div id="changePassStep1"
                    style="background: #f8fafc; padding: 20px; border-radius: 16px; border: 1px solid #f1f5f9;">
                    <p style="margin: 0 0 15px 0; font-size: 0.9rem; color: #64748b;">To change your password, please
                        confirm your current password first.</p>
                    <div style="display: flex; gap: 15px; align-items: flex-end;">
                        <div style="flex: 1;">
                            <label class="info-label"
                                style="font-size: 0.7rem; margin-bottom: 5px; display: block;">Current Password</label>
                            <input type="password" id="current_password" class="form-input" style="width: 100%;"
                                placeholder="********">
                        </div>
                        <button class="btn-primary" style="margin: 0; padding: 10px 20px; width: auto;"
                            id="requestOtpBtn">
                            REQUEST OTP
                        </button>
                    </div>
                </div>

                <div id="changePassStep2"
                    style="display: none; background: #f8fafc; padding: 20px; border-radius: 16px; border: 1px solid #f1f5f9;">
                    <div
                        style="background: #eff6ff; border: 1px solid #dbeafe; padding: 12px 15px; border-radius: 12px; margin-bottom: 20px;">
                        <p style="margin: 0; color: #1e40af; font-size: 0.85rem;"><i class="fas fa-info-circle"></i>
                            Check your email: <strong id="obscuredEmail"></strong>. Code expires in 10 minutes.</p>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                        <div>
                            <label class="info-label"
                                style="font-size: 0.7rem; margin-bottom: 5px; display: block;">6-Digit OTP</label>
                            <input type="text" id="otp_code" class="form-input"
                                style="width: 100%; text-align: center; letter-spacing: 5px; font-weight: 800;"
                                placeholder="000000" maxlength="6">
                        </div>
                        <div>
                            <label class="info-label" style="font-size: 0.7rem; margin-bottom: 5px; display: block;">New
                                Password</label>
                            <input type="password" id="new_password" class="form-input" style="width: 100%;"
                                placeholder="********">
                        </div>
                    </div>

                    <div style="margin-top: 20px; display: flex; justify-content: flex-end; gap: 10px;">
                        <button class="btn-primary"
                            style="background: transparent; color: #64748b; border: 1px solid #e2e8f0; width: auto; padding: 10px 20px;"
                            id="cancelChangeBtn">
                            Cancel
                        </button>
                        <button class="btn-primary" style="width: auto; padding: 10px 20px;" id="updatePasswordBtn">
                            Update Password
                        </button>
                    </div>
                </div>
            </div>

            <div style="margin-top: 40px; text-align: right;">
                <button class="btn-primary" onclick="openEditModal()" style="width: auto; padding: 12px 30px;">
                    <i class="fas fa-edit"></i> Edit Details
                </button>
            </div>
    </div>
    </main>
    </div>

    <!-- Edit Modal -->
    <div id="editModal" class="modal"
        style="display:none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); backdrop-filter: blur(4px);">
        <div class="modal-content"
            style="background: #fff; margin: 5% auto; padding: 30px; border-radius: 20px; width: 500px; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
                <h2 style="margin:0; color:#1e293b;"><i class="fas fa-user-edit" style="color:var(--primary-color)"></i>
                    Edit Admin Details</h2>
                <span onclick="closeEditModal()" style="cursor:pointer; font-size: 24px; color:#94a3b8;">&times;</span>
            </div>

            <form id="editAdminForm">
                <div class="form-group" style="margin-bottom: 15px;">
                    <label class="form-label">Username</label>
                    <input type="text" name="username" class="form-input"
                        value="<?php echo htmlspecialchars($admin['username']); ?>" required>
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                    <div class="form-group">
                        <label class="form-label">First Name</label>
                        <input type="text" name="first_name" class="form-input"
                            value="<?php echo htmlspecialchars(capitalizeWords($admin['first_name'])); ?>" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Last Name</label>
                        <input type="text" name="last_name" class="form-input"
                            value="<?php echo htmlspecialchars(capitalizeWords($admin['last_name'])); ?>" required>
                    </div>
                </div>
                <div class="form-group" style="margin-bottom: 20px;">
                    <label class="form-label">Email Address (Read Only)</label>
                    <div style="display: flex; gap: 10px;">
                        <input type="email" name="email" class="form-input"
                            value="<?php echo htmlspecialchars($admin['email']); ?>" readonly
                            style="background: #f8fafc; cursor: not-allowed; flex: 1;">
                        <button type="button" id="requestEmailChangeBtn"
                            style="background: #2563eb; color: white; border: none; padding: 0 15px; border-radius: 10px; font-size: 0.75rem; font-weight: 600; cursor: pointer;">
                            CHANGE
                        </button>
                    </div>
                    <p style="font-size: 0.7rem; color: #64748b; margin-top: 5px;">A verification link will be sent to
                        your current email.</p>
                </div>
                <div class="form-group" style="margin-bottom: 25px;">
                    <label class="form-label">Phone Number</label>
                    <input type="text" name="phone_number" class="form-input"
                        value="<?php echo htmlspecialchars($admin['phone_number']); ?>">
                </div>

                <button type="submit" class="btn-primary" id="saveButton">Save Changes</button>
            </form>
        </div>
    </div>

    <script src="../assets/js/loader.js"></script>
    <script>
        const profileToggle = document.getElementById('profileToggle');
        const profileDropdown = document.getElementById('profileDropdown');
        if (profileToggle) {
            profileToggle.addEventListener('click', (e) => {
                e.stopPropagation();
                profileDropdown.classList.toggle('active');
            });
        }
        document.addEventListener('click', () => profileDropdown?.classList.remove('active'));

        function openEditModal() {
            document.getElementById('editModal').style.display = 'block';
        }

        function closeEditModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        document.getElementById('editAdminForm').addEventListener('submit', function (e) {
            e.preventDefault();
            const saveBtn = document.getElementById('saveButton');
            saveBtn.disabled = true;
            saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';

            const formData = new FormData(this);
            fetch('../api/update_admin_profile.php', {
                method: 'POST',
                body: formData
            })
                .then(r => r.json())
                .then(res => {
                    if (res.success) {
                        alert(res.message);
                        location.reload();
                    } else {
                        alert(res.message);
                        saveBtn.disabled = false;
                        saveBtn.innerHTML = 'Save Changes';
                    }
                })
                .catch(() => {
                    alert('Update failed. Connection error.');
                    saveBtn.disabled = false;
                    saveBtn.innerHTML = 'Save Changes';
                });
        });

        // Change Password Logic
        let currentIdentity = "";

        document.getElementById('requestOtpBtn')?.addEventListener('click', function () {
            const currentPass = document.getElementById('current_password').value;
            if (!currentPass) {
                alert('Please enter your current password.');
                return;
            }

            this.disabled = true;
            this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';

            fetch('../api/change_password_request.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    user_id: "<?php echo $adminId; ?>",
                    user_type: "admin",
                    current_password: currentPass
                })
            })
                .then(r => r.json())
                .then(res => {
                    if (res.success) {
                        currentIdentity = res.identity;
                        document.getElementById('obscuredEmail').innerText = res.email_obscured;
                        document.getElementById('changePassStep1').style.display = 'none';
                        document.getElementById('changePassStep2').style.display = 'block';
                    } else {
                        alert(res.message);
                        this.disabled = false;
                        this.innerHTML = 'REQUEST OTP';
                    }
                })
                .catch(() => {
                    alert('Request failed. Connection error.');
                    this.disabled = false;
                    this.innerHTML = 'REQUEST OTP';
                });
        });

        document.getElementById('cancelChangeBtn')?.addEventListener('click', function () {
            document.getElementById('changePassStep2').style.display = 'none';
            document.getElementById('changePassStep1').style.display = 'block';
            document.getElementById('current_password').value = '';
            const btn = document.getElementById('requestOtpBtn');
            if (btn) {
                btn.disabled = false;
                btn.innerHTML = 'REQUEST OTP';
            }
        });

        // Email Change Request
        const requestEmailChangeBtn = document.getElementById('requestEmailChangeBtn');
        if (requestEmailChangeBtn) {
            requestEmailChangeBtn.addEventListener('click', async () => {
                if (!confirm('Send a verification link to your current email address to begin the email change process?')) return;

                requestEmailChangeBtn.disabled = true;
                requestEmailChangeBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';

                try {
                    const response = await fetch('../api/request_email_change.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            user_id: "<?php echo $adminId; ?>",
                            user_type: 'admin'
                        })
                    });
                    const res = await response.json();

                    if (res.success) {
                        alert(res.message);
                        closeEditModal();
                    } else {
                        alert(res.message || 'Failed to request email change.');
                    }
                } catch (e) {
                    alert('An error occurred. Please try again.');
                } finally {
                    requestEmailChangeBtn.disabled = false;
                    requestEmailChangeBtn.innerHTML = 'CHANGE';
                }
            });
        }

        document.getElementById('updatePasswordBtn')?.addEventListener('click', function () {
            const otpCode = document.getElementById('otp_code').value;
            const newPass = document.getElementById('new_password').value;

            if (!otpCode || otpCode.length < 6) {
                alert('Please enter the 6-digit OTP.');
                return;
            }
            if (!newPass || newPass.length < 6) {
                alert('New password must be at least 6 characters long.');
                return;
            }

            this.disabled = true;
            this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';

            fetch('../api/reset_password.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    nroi_id: currentIdentity,
                    otp: otpCode,
                    new_password: newPass
                })
            })
                .then(r => r.json())
                .then(res => {
                    if (res.success) {
                        alert('Password updated successfully. For security, please log in again.');
                        window.location.href = '../logout.php';
                    } else {
                        alert(res.message);
                        this.disabled = false;
                        this.innerHTML = 'Update Password';
                    }
                })
                .catch(() => {
                    alert('Update failed. Connection error.');
                    this.disabled = false;
                    this.innerHTML = 'Update Password';
                });
        });
    </script>
    <script src="../assets/js/dashboard-transitions.js"></script>
</body>

</html>