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

$allowedRoles = ['AC', 'AAC', 'NROI', 'PPSA'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], $allowedRoles)) {
    header("Location: ../index.php");
    exit;
}

$userId = $_SESSION['user_id'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch();

if (!$user) {
    die("User not found.");
}

$isSpecialRole = in_array(strtoupper($user['role'] ?? ''), ['PPSA', 'NROI']);
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Officer 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: 950px;
            margin: 0 auto;
            background: #fff;
            border-radius: 32px;
            padding: 50px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.05);
            border: 1px solid rgba(0, 0, 0, 0.03);
        }

        .profile-header {
            display: flex;
            align-items: center;
            gap: 40px;
            padding-bottom: 45px;
            border-bottom: 1.5px solid #f8fafc;
            margin-bottom: 45px;
        }

        .profile-photo-container {
            width: 180px;
            height: 180px;
            border-radius: 40px;
            overflow: hidden;
            background: #f1f5f9;
            border: 6px solid #fff;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.08);
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
        }

        .profile-photo-container img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .profile-photo-container i {
            font-size: 4rem;
            color: #cbd5e1;
        }

        .header-info h1 {
            margin: 0;
            font-size: 2.8rem;
            color: #0f172a;
            font-weight: 800;
            letter-spacing: -1px;
        }

        .header-info .badge-container {
            display: flex;
            gap: 12px;
            margin-top: 15px;
        }

        .role-badge-large {
            padding: 8px 20px;
            background: #eff6ff;
            color: #2563eb;
            border-radius: 12px;
            font-size: 0.9rem;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            box-shadow: 0 4px 12px rgba(37, 99, 235, 0.1);
        }

        .area-badge-large {
            padding: 8px 20px;
            background: #f0fdf4;
            color: #16a34a;
            border-radius: 12px;
            font-size: 0.9rem;
            font-weight: 800;
            display: flex;
            align-items: center;
            gap: 8px;
            box-shadow: 0 4px 12px rgba(22, 163, 74, 0.1);
        }

        .section-title {
            font-size: 1.1rem;
            font-weight: 900;
            color: #1e293b;
            margin: 50px 0 25px;
            display: flex;
            align-items: center;
            gap: 12px;
            text-transform: uppercase;
            letter-spacing: 1.5px;
        }

        .section-title i {
            color: #2563eb;
            font-size: 1.2rem;
            background: #eff6ff;
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 10px;
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
        }

        .info-item {
            background: #f8fafc;
            padding: 20px 25px;
            border-radius: 16px;
            border: 1px solid #f1f5f9;
            transition: all 0.2s ease;
        }

        .info-item:hover {
            background: #fff;
            border-color: #e2e8f0;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.03);
            transform: translateY(-2px);
        }

        .info-label {
            display: block;
            font-size: 0.8rem;
            color: #64748b;
            font-weight: 800;
            margin-bottom: 8px;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .info-value {
            font-size: 1.1rem;
            color: #0f172a;
            font-weight: 700;
        }

        .full-width {
            grid-column: span 2;
        }

        .btn-update {
            background: #0f172a;
            color: white;
            border: none;
            padding: 16px 36px;
            border-radius: 16px;
            font-weight: 700;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 12px;
            box-shadow: 0 10px 20px rgba(15, 23, 42, 0.15);
        }

        .btn-update:hover {
            background: #1e293b;
            transform: translateY(-2px);
            box-shadow: 0 15px 30px rgba(15, 23, 42, 0.2);
        }
    </style>
</head>

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

    <aside class="sidebar">
        <div class="sidebar-brand-area">
            <div class="sidebar-role-badge">
                <?php
                if ($user['role'] === 'AC') {
                    echo 'A.C';
                } elseif ($user['role'] === 'AAC') {
                    echo 'A.A.C';
                } else {
                    echo htmlspecialchars($user['role'] ?? 'OFFICER');
                }
                ?>
            </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>
            <?php if (!$isSpecialRole): ?>
                <li class="sidebar-item">
                    <a href="notifications.php" class="sidebar-link">
                        <i class="fas fa-bell"></i> Notifications
                    </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="../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>
            <?php endif; ?>
            <li class="sidebar-item">
                <a href="../api/points_card.php" class="sidebar-link">
                    <i class="fas fa-id-card"></i> Points Card
                </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; overflow: hidden; border-radius: 50%; display: flex; align-items: center; justify-content: center; background: #e2e8f0;">
                    <?php if (!empty($user['profile_photo'])): ?>
                        <img src="../<?php echo htmlspecialchars($user['profile_photo']); ?>" alt=""
                            style="width: 100%; height: 100%; object-fit: cover;">
                    <?php else: ?>
                        <span
                            style="font-weight: 700; color: #64748b; font-size: 0.8rem;"><?php echo strtoupper(substr($user['role'] ?? 'OF', 0, 2)); ?></span>
                    <?php endif; ?>
                </div>
                <div class="sidebar-user-info">
                    <div class="sidebar-user-name">
                        <?php echo htmlspecialchars(capitalizeWords($user['first_name'])); ?>
                    </div>
                    <div class="sidebar-user-role">
                        <?php echo htmlspecialchars($user['role'] ?? 'Officer'); ?> Account
                    </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>OFFICER PROFILE AUDIT</p>
                    </div>
                </div>
            </header>

            <div class="profile-container animated-fade-in">
                <div class="profile-header">
                    <div class="profile-photo-container">
                        <?php if ($user['profile_photo']): ?>
                            <img src="../<?php echo htmlspecialchars($user['profile_photo']); ?>" alt="Profile Photo">
                        <?php else: ?>
                            <i class="fas fa-user"></i>
                        <?php endif; ?>
                    </div>
                    <div class="header-info">
                        <h1>
                            <?php echo htmlspecialchars(capitalizeWords($user['first_name'] . ' ' . ($user['middle_name'] ? $user['middle_name'] . ' ' : '') . $user['last_name'] . ($user['extension'] ? ' ' . $user['extension'] : ''))); ?>
                        </h1>
                        <div class="badge-container">
                            <span class="role-badge-large">
                                <?php
                                $r = strtoupper($user['role'] ?? 'OFFICER');
                                if ($r == 'MEMBER' || $r == 'RO')
                                    echo 'R.O';
                                elseif ($r == 'CRO')
                                    echo 'C.R.O';
                                elseif ($r == 'AC')
                                    echo 'A.C';
                                elseif ($r == 'AAC')
                                    echo 'A.A.C';
                                else
                                    echo $r;
                                ?>
                            </span>
                            <?php if (!$isSpecialRole): ?>
                                <span class="area-badge-large"><i class="fas fa-location-dot"></i>
                                    <?php echo htmlspecialchars($user['area'] ?? 'No Area'); ?>
                                </span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <div class="section-title"><i class="fas fa-id-card"></i> MEMBERSHIP DETAILS</div>
                <div class="info-grid">
                    <?php if (!$isSpecialRole): ?>
                        <div class="info-item">
                            <span class="info-label">NROI ID</span>
                            <div class="info-value" style="color:#2563eb">
                                <?php echo htmlspecialchars($user['nroi_id'] ?? 'N/A'); ?>
                            </div>
                        </div>
                        <div class="info-item">
                            <span class="info-label">PPSA ID</span>
                            <div class="info-value">
                                <?php echo htmlspecialchars($user['ppsa_id'] ?? 'N/A'); ?>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="info-item">
                            <span class="info-label">Position</span>
                            <div class="info-value" style="color:#2563eb">
                                <?php echo htmlspecialchars($user['position'] ?? 'N/A'); ?>
                            </div>
                        </div>
                    <?php endif; ?>
                    <div class="info-item">
                        <span class="info-label">Status</span>
                        <div class="info-value" style="color:#2563eb">
                            <?php
                            $rank = strtoupper($user['rank'] ?? '');
                            echo strpos($rank, 'OJT') !== false ? 'OJT' : 'REGULAR';
                            ?>
                        </div>
                    </div>
                </div>

                <?php if (!$isSpecialRole): ?>
                    <div class="section-title"><i class="fas fa-user"></i> PERSONAL DETAILS</div>
                    <div class="info-grid">
                        <div class="info-item">
                            <span class="info-label">Gender</span>
                            <div class="info-value">
                                <?php echo htmlspecialchars($user['gender'] ?: 'N/A'); ?>
                            </div>
                        </div>
                        <div class="info-item">
                            <span class="info-label">Birth Date / Age</span>
                            <div class="info-value">
                                <?php if ($user['dob']): ?>
                                    <?php echo htmlspecialchars($user['dob']); ?> (<?php echo $user['age']; ?> yrs)
                                <?php else: ?>
                                    N/A
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <?php if (!$isSpecialRole): ?>
                    <div class="section-title"><i class="fas fa-map-location-dot"></i> Primary Address</div>
                    <div class="info-grid">
                        <div class="info-item full-width">
                            <span class="info-label">Complete Address</span>
                            <div class="info-value">
                                <?php
                                $address = array_filter([
                                    $user['street'] ? capitalizeWords($user['street']) : '',
                                    capitalizeWords($user['barangay']),
                                    capitalizeWords($user['city_municipality']),
                                    capitalizeWords($user['province']),
                                    capitalizeWords($user['region']),
                                    $user['zipcode']
                                ]);
                                echo htmlspecialchars(implode(', ', $address) ?: 'N/A');
                                ?>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <div class="section-title"><i class="fas fa-paper-plane"></i> Contact & Social</div>
                <div class="info-grid">
                    <div class="info-item">
                        <span class="info-label">Email Address</span>
                        <div class="info-value">
                            <?php echo htmlspecialchars($user['email'] ?: 'N/A'); ?>
                        </div>
                    </div>
                    <div class="info-item">
                        <span class="info-label">Mobile Number</span>
                        <div class="info-value">
                            <?php echo htmlspecialchars($user['phone_number'] ?: 'N/A'); ?>
                        </div>
                    </div>
                    <?php if (!$isSpecialRole): ?>
                        <div class="info-item">
                            <span class="info-label">Viber Number</span>
                            <div class="info-value">
                                <?php echo htmlspecialchars($user['viber_number'] ?: 'N/A'); ?>
                            </div>
                        </div>
                        <div class="info-item">
                            <span class="info-label">Telegram Number</span>
                            <div class="info-value">
                                <?php echo htmlspecialchars($user['telegram_number'] ?: 'N/A'); ?>
                            </div>
                        </div>
                        <div class="info-item full-width">
                            <span class="info-label">Facebook Profile Link</span>
                            <div class="info-value">
                                <?php echo htmlspecialchars($user['facebook_link'] ?: 'N/A'); ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>

                <?php if (!$isSpecialRole): ?>
                    <div class="section-title"><i class="fas fa-life-ring" style="color:#ef4444; background:#fef2f2;"></i>
                        Emergency Contact
                    </div>
                    <div class="info-grid">
                        <div class="info-item">
                            <span class="info-label">Contact Person</span>
                            <div class="info-value">
                                <?php echo htmlspecialchars(capitalizeWords($user['emergency_contact_name'] ?? 'N/A')); ?>
                            </div>
                        </div>
                        <div class="info-item">
                            <span class="info-label">Contact Phone</span>
                            <div class="info-value" style="color:#ef4444">
                                <?php echo htmlspecialchars($user['emergency_contact_number'] ?? 'N/A'); ?>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <div class="section-title"><i class="fas fa-lock" style="color:#ef4444; background:#fef2f2;"></i>
                    SECURITY & PASSWORD
                </div>
                <div class="info-grid">
                    <div class="info-item full-width" id="changePassStep1">
                        <span class="info-label">Update Your Password</span>
                        <div style="display: flex; gap: 15px; align-items: flex-end; margin-top: 10px;">
                            <div style="flex: 1;">
                                <label class="info-label" style="font-size: 0.7rem;">Enter Current Password</label>
                                <input type="password" id="current_password" class="form-input" style="width: 100%;"
                                    placeholder="********">
                            </div>
                            <button class="btn-update" style="margin-top: 0; padding: 12px 24px;" id="requestOtpBtn">
                                REQUEST OTP
                            </button>
                        </div>
                        <p style="font-size: 0.8rem; color: #64748b; margin-top: 10px;">Enter your old password and
                            we'll send a code to your email.</p>
                    </div>

                    <div class="info-item full-width" id="changePassStep2" style="display: none;">
                        <span class="info-label">Enter OTP & New Password</span>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-top: 10px;">
                            <div style="grid-column: span 2;">
                                <div
                                    style="background: #eff6ff; border: 1px solid #dbeafe; padding: 10px 15px; border-radius: 12px; margin-bottom: 15px;">
                                    <p style="margin: 0; color: #1e40af; font-size: 0.85rem;">Check your email: <strong
                                            id="obscuredEmail"></strong>. Code expires in 10 minutes.</p>
                                </div>
                            </div>
                            <div>
                                <label class="info-label" style="font-size: 0.7rem;">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;">New Password</label>
                                <input type="password" id="new_password" class="form-input" style="width: 100%;"
                                    placeholder="********">
                            </div>
                        </div>
                        <div style="margin-top: 20px; text-align: right;">
                            <button class="btn-update" style="background: #2563eb; color: #fff;" id="updatePasswordBtn">
                                UPDATE PASSWORD
                            </button>
                            <button class="btn-update"
                                style="background: #f1f5f9; color: #64748b; box-shadow: none; border: 1px solid #e2e8f0;"
                                id="cancelChangeBtn">
                                CANCEL
                            </button>
                        </div>
                    </div>
                </div>

                <div style="margin-top: 50px; text-align: center;">
                    <button class="btn-update" onclick="openEditModal()">
                        <i class="fas fa-user-edit"></i> UPDATE PROFILE DETAILS
                    </button>
                </div>
            </div>
            <div style="height: 50px;"></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: 2% auto; padding: 30px; border-radius: 24px; width: 600px; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25); max-height: 90vh; overflow-y: auto;">
            <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>
                    Update Your Details</h2>
                <span onclick="closeEditModal()" style="cursor:pointer; font-size: 24px; color:#94a3b8;">&times;</span>
            </div>

            <p style="color: #64748b; font-size: 0.9rem; margin-bottom: 25px;">You can update your membership IDs,
                identity details, and contact information here.</p>

            <form id="editUserForm">
                <div
                    style="margin-top: 0px; padding-bottom: 20px; border-bottom: 1px solid #f1f5f9; margin-bottom: 25px;">
                    <?php if (!$isSpecialRole): ?>
                        <h4
                            style="margin:0 0 15px; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 0.5px; color:#334155;">
                            Membership Identity</h4>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                            <div class="form-group">
                                <label class="form-label">NROI ID</label>
                                <input type="text" name="nroi_id" class="form-input"
                                    value="<?php echo htmlspecialchars($user['nroi_id']); ?>" required>
                            </div>
                            <div class="form-group">
                                <label class="form-label">PPSA ID</label>
                                <input type="text" name="ppsa_id" class="form-input"
                                    value="<?php echo htmlspecialchars($user['ppsa_id']); ?>" required>
                            </div>
                        </div>
                    <?php else: ?>
                        <!-- Hidden fields to preserve existing data for PPSA/NROI roles -->
                        <input type="hidden" name="nroi_id" value="<?php echo htmlspecialchars($user['nroi_id']); ?>">
                        <input type="hidden" name="ppsa_id" value="<?php echo htmlspecialchars($user['ppsa_id']); ?>">
                    <?php endif; ?>
                </div>

                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                    <div class="form-group">
                        <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($user['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;">Click CHANGE to receive a
                            verification link in your current email.</p>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Mobile Number</label>
                        <input type="text" name="phone_number" class="form-input"
                            value="<?php echo htmlspecialchars($user['phone_number']); ?>" required>
                    </div>
                    <?php if ($isSpecialRole): ?>
                        <div class="form-group">
                            <label class="form-label">Position</label>
                            <input type="text" name="position" class="form-input"
                                value="<?php echo htmlspecialchars($user['position']); ?>" required>
                        </div>
                    <?php endif; ?>
                    <?php if (!$isSpecialRole): ?>
                        <div class="form-group">
                            <label class="form-label">Viber Number</label>
                            <input type="text" name="viber_number" class="form-input"
                                value="<?php echo htmlspecialchars($user['viber_number']); ?>">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Telegram Number</label>
                            <input type="text" name="telegram_number" class="form-input"
                                value="<?php echo htmlspecialchars($user['telegram_number']); ?>">
                        </div>
                        <div class="form-group full-width" style="grid-column: span 2;">
                            <label class="form-label">Facebook Profile Link</label>
                            <input type="text" name="facebook_link" class="form-input"
                                value="<?php echo htmlspecialchars($user['facebook_link']); ?>">
                        </div>
                    <?php else: ?>
                        <!-- Hidden fields to preserve existing data -->
                        <input type="hidden" name="viber_number"
                            value="<?php echo htmlspecialchars($user['viber_number']); ?>">
                        <input type="hidden" name="telegram_number"
                            value="<?php echo htmlspecialchars($user['telegram_number']); ?>">
                        <input type="hidden" name="facebook_link"
                            value="<?php echo htmlspecialchars($user['facebook_link']); ?>">
                    <?php endif; ?>
                </div>

                <?php if (!$isSpecialRole): ?>
                    <div style="margin-top: 25px; padding-top: 20px; border-top: 1px solid #f1f5f9;">
                        <h4
                            style="margin:0 0 15px; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 0.5px; color:#334155;">
                            Emergency Contact</h4>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                            <div class="form-group">
                                <label class="form-label">Contact Person</label>
                                <input type="text" name="emergency_contact_name" class="form-input"
                                    value="<?php echo htmlspecialchars(capitalizeWords($user['emergency_contact_name'])); ?>">
                            </div>
                            <div class="form-group">
                                <label class="form-label">Contact Number</label>
                                <input type="text" name="emergency_contact_number" class="form-input"
                                    value="<?php echo htmlspecialchars($user['emergency_contact_number']); ?>">
                            </div>
                        </div>
                    </div>
                <?php else: ?>
                    <input type="hidden" name="emergency_contact_name"
                        value="<?php echo htmlspecialchars($user['emergency_contact_name']); ?>">
                    <input type="hidden" name="emergency_contact_number"
                        value="<?php echo htmlspecialchars($user['emergency_contact_number']); ?>">
                <?php endif; ?>

                <button type="submit" class="btn-primary" id="saveButton" style="margin-top: 30px;">Save Profile
                    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('editUserForm').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_user_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 Profile Changes';
                    }
                })
                .catch(() => {
                    alert('Update failed. Connection error.');
                    saveBtn.disabled = false;
                    saveBtn.innerHTML = 'Save Profile 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 $userId; ?>",
                    user_type: "regular",
                    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 $userId; ?>",
                            user_type: 'regular'
                        })
                    });
                    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>