<?php
use Core\App\Models\AdminProfileModel;

if (session_status() === PHP_SESSION_NONE) session_start();

$adminId = $_SESSION['admin_id'] ?? null;
if (!$adminId) { header('Location: /admin/login'); exit; }

if (!function_exists('mte_normalize_asset_url')) {
    function mte_normalize_asset_url($path): string {
        $path = trim((string)$path);
        if ($path === '') return '';
        if (preg_match('#^https?://#i', $path)) return $path;
        if ($path[0] === '/') return $path;
        return '/' . $path;
    }
}

$model = new AdminProfileModel();
$admin = $model->findById((int)$adminId);
if (!$admin) { echo '<div class="alert alert-danger">' . htmlspecialchars(__('admin.profile.not_found','Admin not found'), ENT_QUOTES, 'UTF-8') . '</div>'; return; }

$avatarSrc = '/admin/assets/adminlte-assets/img/avatar.png';
if (!empty($admin['avatar'])) $avatarSrc = mte_normalize_asset_url($admin['avatar']);

$roleLabels = [
    'owner'      => ['label' => __('team.role_owner','Owner'),      'color' => '#7c3aed', 'bg' => '#f5f3ff', 'icon' => 'bi-crown-fill'],
    'manager'    => ['label' => __('team.role_manager','Manager'),   'color' => '#1d4ed8', 'bg' => '#eff6ff', 'icon' => 'bi-person-fill-gear'],
    'confirmer'  => ['label' => __('team.role_confirmer','Confirmer'),'color' => '#059669','bg' => '#f0fdf4', 'icon' => 'bi-check-circle-fill'],
    'shipping'   => ['label' => __('team.role_shipping','Shipping'), 'color' => '#d97706', 'bg' => '#fffbeb', 'icon' => 'bi-truck-front-fill'],
    'accountant' => ['label' => __('team.role_accountant','Accountant'),'color'=>'#dc2626','bg'=>'#fff1f2','icon'=>'bi-calculator-fill'],
];
$role    = $_SESSION['admin_role'] ?? 'owner';
$roleCfg = $roleLabels[$role] ?? ['label'=>$role,'color'=>'#6b7280','bg'=>'#f9fafb','icon'=>'bi-person'];
?>
<style>
.pf-page   { max-width:860px; margin:0 auto; padding:28px 16px 56px; }
.pf-header { display:flex; align-items:center; gap:24px; margin-bottom:32px; flex-wrap:wrap; }

/* Avatar zone */
.pf-avatar-wrap {
    position:relative; width:96px; height:96px; flex-shrink:0;
}
.pf-avatar {
    width:96px; height:96px; border-radius:50%;
    object-fit:cover;
    border:3px solid #e5e7eb;
    box-shadow:0 4px 16px rgba(0,0,0,.12);
    transition:filter .2s;
}
.pf-avatar-wrap:hover .pf-avatar { filter:brightness(.75); }
.pf-avatar-btn {
    position:absolute; inset:0; border-radius:50%;
    display:flex; align-items:center; justify-content:center;
    background:rgba(0,0,0,.45); color:#fff;
    font-size:22px; opacity:0; cursor:pointer;
    transition:opacity .2s; border:none;
}
.pf-avatar-wrap:hover .pf-avatar-btn { opacity:1; }

/* Header info */
.pf-name  { font-size:22px; font-weight:800; color:#111827; margin:0 0 4px; }
.pf-email { font-size:14px; color:#9ca3af; margin:0 0 8px; }
.pf-role-badge {
    display:inline-flex; align-items:center; gap:6px;
    padding:5px 14px; border-radius:99px;
    font-size:12px; font-weight:700; letter-spacing:.3px;
}

/* Cards */
.pf-card {
    background:#fff; border:1.5px solid #e5e7eb;
    border-radius:16px; overflow:hidden; margin-bottom:20px;
}
.pf-card-head {
    padding:14px 22px; border-bottom:1px solid #f3f4f6;
    display:flex; align-items:center; gap:10px;
    font-size:13px; font-weight:700; color:#374151;
    text-transform:uppercase; letter-spacing:.6px;
}
.pf-card-body { padding:24px 22px; }

/* Input styling */
.pf-label { font-size:12px; font-weight:700; color:#6b7280; text-transform:uppercase; letter-spacing:.5px; margin-bottom:6px; display:block; }
.pf-input {
    width:100%; border:1.5px solid #e5e7eb; border-radius:10px;
    padding:10px 14px; font-size:14px; color:#111827;
    background:#fff; transition:border-color .18s, box-shadow .18s;
    font-family:inherit;
}
.pf-input:focus { outline:none; border-color:var(--bs-primary,#4f7eff); box-shadow:0 0 0 3px rgba(79,126,255,.12); }
.pf-input-icon { position:relative; }
.pf-input-icon .pf-icon { position:absolute; inset-inline-start:13px; top:50%; transform:translateY(-50%); color:#9ca3af; font-size:15px; pointer-events:none; }
.pf-input-icon .pf-input { padding-inline-start:38px; }
.pf-input-icon .pf-eye { position:absolute; inset-inline-end:13px; top:50%; transform:translateY(-50%); background:none; border:none; color:#9ca3af; cursor:pointer; font-size:15px; padding:0; }

/* Password strength */
.pf-strength { height:4px; border-radius:99px; background:#e5e7eb; margin-top:6px; overflow:hidden; }
.pf-strength-bar { height:100%; border-radius:99px; transition:width .3s,background .3s; width:0; }

/* Buttons */
.pf-btn {
    display:inline-flex; align-items:center; gap:8px;
    padding:10px 22px; border-radius:10px;
    font-size:14px; font-weight:700; font-family:inherit;
    border:none; cursor:pointer; transition:transform .18s,box-shadow .18s,filter .18s;
}
.pf-btn:hover { transform:translateY(-2px); filter:brightness(1.06); }
.pf-btn-primary { background:var(--bs-primary,#4f7eff); color:#fff; box-shadow:0 4px 14px rgba(79,126,255,.3); }
.pf-btn-danger  { background:#ef4444; color:#fff; box-shadow:0 4px 14px rgba(239,68,68,.25); }

/* Flash */
.pf-flash { display:flex; align-items:center; gap:10px; padding:12px 18px; border-radius:12px; margin-bottom:20px; font-size:14px; font-weight:600; }
.pf-flash-ok  { background:#f0fdf4; border:1.5px solid #bbf7d0; color:#065f46; }
.pf-flash-err { background:#fff1f2; border:1.5px solid #fecaca; color:#991b1b; }
</style>

<div class="content-wrapper">
<section class="content pt-3">
<div class="pf-page">

    <!-- Flash messages -->
    <?php if (!empty($_SESSION['profile_success'])): ?>
    <div class="pf-flash pf-flash-ok">
        <i class="bi bi-check-circle-fill fs-5"></i>
        <?= htmlspecialchars($_SESSION['profile_success']) ?>
    </div>
    <?php unset($_SESSION['profile_success']); endif; ?>

    <?php if (!empty($_SESSION['profile_error'])): ?>
    <div class="pf-flash pf-flash-err">
        <i class="bi bi-exclamation-circle-fill fs-5"></i>
        <?= htmlspecialchars($_SESSION['profile_error']) ?>
    </div>
    <?php unset($_SESSION['profile_error']); endif; ?>

    <!-- Header -->
    <div class="pf-header">
        <!-- Avatar with click-to-change -->
        <form method="post" enctype="multipart/form-data" action="/admin/profile/update" id="avatarForm">
            <?= \Core\System\Csrf::field() ?>
            <input type="file" name="avatar" id="avatarInput" accept="image/*" style="display:none">
            <div class="pf-avatar-wrap" onclick="document.getElementById('avatarInput').click()" title="<?= __('admin.profile.change_avatar','Change avatar') ?>">
                <img id="avatarPreview" src="<?= htmlspecialchars($avatarSrc,ENT_QUOTES,'UTF-8') ?>" class="pf-avatar" alt="avatar">
                <button type="button" class="pf-avatar-btn"><i class="bi bi-camera-fill"></i></button>
            </div>
        </form>
        <div>
            <h1 class="pf-name"><?= htmlspecialchars($admin['username']) ?></h1>
            <p class="pf-email"><i class="bi bi-envelope me-1"></i><?= htmlspecialchars($admin['email'] ?? '—') ?></p>
            <span class="pf-role-badge" style="background:<?= $roleCfg['bg'] ?>;color:<?= $roleCfg['color'] ?>;border:1.5px solid <?= $roleCfg['color'] ?>30">
                <i class="bi <?= $roleCfg['icon'] ?>"></i>
                <?= $roleCfg['label'] ?>
            </span>
        </div>
    </div>

    <!-- ── Profile Info ── -->
    <div class="pf-card">
        <div class="pf-card-head">
            <i class="bi bi-person-fill" style="color:var(--bs-primary,#4f7eff)"></i>
            <?= __('admin.profile.info','Profile Information') ?>
        </div>
        <div class="pf-card-body">
            <form method="post" action="/admin/profile/update">
                <?= \Core\System\Csrf::field() ?>
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="pf-label"><?= __('admin.profile.username','Username') ?></label>
                        <div class="pf-input-icon">
                            <i class="bi bi-person pf-icon"></i>
                            <input type="text" name="username" class="pf-input"
                                   value="<?= htmlspecialchars($admin['username']) ?>" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="pf-label"><?= __('admin.profile.email','Email') ?></label>
                        <div class="pf-input-icon">
                            <i class="bi bi-envelope pf-icon"></i>
                            <input type="email" name="email" class="pf-input"
                                   value="<?= htmlspecialchars($admin['email'] ?? '') ?>">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="pf-label"><?= __('admin.profile.phone','Phone (WhatsApp)') ?></label>
                        <div class="pf-input-icon">
                            <i class="bi bi-phone pf-icon"></i>
                            <input type="tel" name="phone" class="pf-input"
                                   value="<?= htmlspecialchars($admin['phone'] ?? '') ?>"
                                   placeholder="+213xxxxxxxxx">
                        </div>
                        <div class="text-muted mt-1" style="font-size:.72rem">
                            <i class="bi bi-whatsapp me-1 text-success"></i><?= __('admin.profile.phone_note','Used for WhatsApp meeting reminders') ?>
                        </div>
                    </div>
                </div>
                <div class="mt-4">
                    <button type="submit" class="pf-btn pf-btn-primary">
                        <i class="bi bi-check-lg"></i>
                        <?= __('actions.save','Save Changes') ?>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- ── Change Password ── -->
    <div class="pf-card">
        <div class="pf-card-head">
            <i class="bi bi-shield-lock-fill" style="color:#ef4444"></i>
            <?= __('admin.profile.password','Change Password') ?>
        </div>
        <div class="pf-card-body">
            <form method="post" action="/admin/profile/update">
                <?= \Core\System\Csrf::field() ?>
                <div class="row g-3">
                    <div class="col-12">
                        <label class="pf-label"><?= __('admin.profile.current_password','Current Password') ?></label>
                        <div class="pf-input-icon">
                            <i class="bi bi-key pf-icon"></i>
                            <input type="password" name="current_password" id="currentPw" class="pf-input" required>
                            <button type="button" class="pf-eye" onclick="togglePw('currentPw','eyeC')"><i class="bi bi-eye" id="eyeC"></i></button>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="pf-label"><?= __('admin.profile.new_password','New Password') ?></label>
                        <div class="pf-input-icon">
                            <i class="bi bi-lock pf-icon"></i>
                            <input type="password" name="new_password" id="newPw" class="pf-input"
                                   oninput="checkStrength(this.value)" required>
                            <button type="button" class="pf-eye" onclick="togglePw('newPw','eyeN')"><i class="bi bi-eye" id="eyeN"></i></button>
                        </div>
                        <div class="pf-strength mt-2"><div class="pf-strength-bar" id="strengthBar"></div></div>
                        <div class="mt-1" style="font-size:11px;color:#9ca3af" id="strengthLabel"></div>
                    </div>
                    <div class="col-md-6">
                        <label class="pf-label"><?= __('admin.profile.confirm_password','Confirm Password') ?></label>
                        <div class="pf-input-icon">
                            <i class="bi bi-lock-fill pf-icon"></i>
                            <input type="password" name="confirm_password" id="confirmPw" class="pf-input" required>
                            <button type="button" class="pf-eye" onclick="togglePw('confirmPw','eyeConfirm')"><i class="bi bi-eye" id="eyeConfirm"></i></button>
                        </div>
                    </div>
                </div>
                <div class="mt-4">
                    <button type="submit" class="pf-btn pf-btn-danger">
                        <i class="bi bi-shield-fill-check"></i>
                        <?= __('admin.profile.update_password','Update Password') ?>
                    </button>
                </div>
            </form>
        </div>
    </div>

</div>
</section>
</div>

<script>
// ── Avatar preview + auto-submit ──
document.getElementById('avatarInput').addEventListener('change', function () {
    const file = this.files[0];
    if (!file) return;
    document.getElementById('avatarPreview').src = URL.createObjectURL(file);
    document.getElementById('avatarForm').submit();
});

// ── Toggle password visibility ──
function togglePw(inputId, iconId) {
    const inp  = document.getElementById(inputId);
    const icon = document.getElementById(iconId);
    inp.type = inp.type === 'password' ? 'text' : 'password';
    icon.className = inp.type === 'password' ? 'bi bi-eye' : 'bi bi-eye-slash';
}

// ── Password strength ──
function checkStrength(val) {
    const bar   = document.getElementById('strengthBar');
    const label = document.getElementById('strengthLabel');
    let score = 0;
    if (val.length >= 8)  score++;
    if (/[A-Z]/.test(val)) score++;
    if (/[0-9]/.test(val)) score++;
    if (/[^A-Za-z0-9]/.test(val)) score++;

    const cfg = [
        {w:'0%',   bg:'#e5e7eb', txt:''},
        {w:'25%',  bg:'#ef4444', txt:'<?= __('admin.profile.pw_weak','Weak') ?>'},
        {w:'50%',  bg:'#f59e0b', txt:'<?= __('admin.profile.pw_fair','Fair') ?>'},
        {w:'75%',  bg:'#3b82f6', txt:'<?= __('admin.profile.pw_good','Good') ?>'},
        {w:'100%', bg:'#10b981', txt:'<?= __('admin.profile.pw_strong','Strong') ?>'},
    ][score];

    bar.style.width      = cfg.w;
    bar.style.background = cfg.bg;
    label.textContent    = cfg.txt;
    label.style.color    = cfg.bg;
}
</script>