<?php
function pf_h($v) {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

$user = $user ?? [];
$profile = $profile ?? [];
$conference = $conference ?? [];
$fieldRules = $fieldRules ?? [];
$customFields = $customFields ?? [];
$customValues = $customValues ?? [];
$missingFields = $missingFields ?? [];

$roleCode = (string)($roleCode ?? ($user['role_code'] ?? ($_SESSION['conference_role'] ?? $_SESSION['role'] ?? '')));
$success = $_SESSION['flash_success'] ?? '';
$guardMessage = $_SESSION['profile_guard_message'] ?? '';
unset($_SESSION['flash_success'], $_SESSION['profile_guard_message']);

$fullName = trim((string)($user['first_name'] ?? '') . ' ' . (string)($user['last_name'] ?? ''));
if ($fullName === '') {
    $fullName = (string)($user['email'] ?? 'User');
}

function pf_rule($fieldRules, $key) {
    return $fieldRules[$key] ?? ['field_label' => $key, 'is_required' => 0, 'help_text' => ''];
}

function pf_badge($rule) {
    if (!empty($rule['is_required'])) {
        return '<span class="ec-required-badge">Required</span>';
    }
    return '<span class="ec-optional-badge">Optional</span>';
}

function pf_visible($fieldRules, $key) {
    return isset($fieldRules[$key]);
}

function pf_label($fieldRules, $key, $fallback) {
    $r = pf_rule($fieldRules, $key);
    return pf_h($r['field_label'] ?? $fallback) . ' ' . pf_badge($r);
}

function pf_hint($fieldRules, $key) {
    $r = pf_rule($fieldRules, $key);
    if (!empty($r['help_text'])) {
        return '<div class="ec-field-hint">' . pf_h($r['help_text']) . '</div>';
    }
    return '';
}

$return = $_GET['return'] ?? '';
?>

<style>
.ec-profile-shell {
    max-width: 1180px;
    margin: 0 auto;
}
.ec-profile-hero {
    border-radius: 28px;
    background: linear-gradient(135deg,#0f172a,#1d4ed8);
    color: #fff;
    box-shadow: 0 16px 40px rgba(15,23,42,.18);
}
.ec-profile-card {
    border: 0;
    border-radius: 24px;
    box-shadow: 0 14px 35px rgba(15,23,42,.08);
}
.ec-required-badge,
.ec-optional-badge {
    display: inline-block;
    font-size: 11px;
    font-weight: 900;
    padding: 2px 8px;
    border-radius: 999px;
    margin-inline-start: 6px;
    vertical-align: middle;
}
.ec-required-badge {
    background: #dc2626;
    color: #fff;
}
.ec-optional-badge {
    background: #e5e7eb;
    color: #374151;
}
.ec-field-hint {
    color: #64748b;
    font-size: 12px;
    margin-top: 4px;
}
.ec-required-note {
    background: #fff7ed;
    border: 1px solid #fed7aa;
    color: #7c2d12;
    border-radius: 20px;
    padding: 16px 18px;
    margin-bottom: 20px;
}
.ec-profile-section-title {
    font-weight: 900;
    margin-bottom: 18px;
    display: flex;
    align-items: center;
    gap: 8px;
}
.ec-profile-section-title i {
    color: #1d4ed8;
}
</style>

<div class="container-fluid py-3">
    <div class="ec-profile-shell">

        <div class="ec-profile-hero mb-4">
            <div class="p-4 d-flex align-items-center justify-content-between gap-3 flex-wrap">
                <div class="d-flex align-items-center gap-3">
                    <?php if (!empty($profile['profile_image'])): ?>
                        <img src="/easychair/storage/<?= pf_h($profile['profile_image']) ?>" style="width:86px;height:86px;border-radius:50%;object-fit:cover;border:3px solid #fff;">
                    <?php else: ?>
                        <div style="width:86px;height:86px;border-radius:50%;background:#fff;color:#1d4ed8;display:flex;align-items:center;justify-content:center;font-size:34px;font-weight:900;">
                            <?= pf_h(mb_substr($fullName, 0, 1)) ?>
                        </div>
                    <?php endif; ?>

                    <div>
                        <h3 class="fw-bold mb-1">My Academic Profile</h3>
                        <div class="opacity-75">
                            <?= pf_h($fullName) ?> |
                            <?= pf_h($user['email'] ?? '') ?> |
                            <?= pf_h($roleCode) ?> |
                            <?= pf_h($conference['short_name'] ?? '') ?>
                        </div>
                    </div>
                </div>

                <div>
                    <span class="badge <?= !empty($profile['is_profile_complete']) ? 'bg-success' : 'bg-warning text-dark' ?>" style="font-size:14px;padding:10px 14px;border-radius:999px;">
                        <?= !empty($profile['is_profile_complete']) ? 'Complete Profile' : 'Incomplete Profile' ?>
                    </span>
                </div>
            </div>
        </div>

        <?php if ($success): ?>
            <div class="alert alert-success"><?= pf_h($success) ?></div>
        <?php endif; ?>

        <?php if (!empty($missingFields)): ?>
            <div class="ec-required-note">
                <div style="font-weight:900;font-size:16px;">
                    <i class="fa fa-circle-info"></i>
                    <?= $guardMessage ? pf_h($guardMessage) : 'Profile completion required.' ?>
                </div>
                <div class="mt-1">
                    Missing required fields:
                    <strong><?= pf_h(implode(', ', $missingFields)) ?></strong>
                </div>
                <div class="mt-2 small">
                    Required fields are controlled by conference administrators from Profile Field Rules.
                </div>
            </div>
        <?php endif; ?>

        <form method="post" action="/easychair/profile/save" enctype="multipart/form-data">
            <?php if ($return): ?>
                <input type="hidden" name="return" value="<?= pf_h($return) ?>">
            <?php endif; ?>

            <div class="row g-4">

                <div class="col-xl-6">
                    <div class="card ec-profile-card h-100">
                        <div class="card-body p-4">
                            <h5 class="ec-profile-section-title"><i class="fa fa-building-columns"></i> Affiliation</h5>

                            <div class="row g-3">
                                <?php if (pf_visible($fieldRules, 'affiliation')): ?>
                                    <div class="col-md-12">
                                        <label class="form-label fw-bold"><?= pf_label($fieldRules, 'affiliation', 'Affiliation / University') ?></label>
                                        <?= pf_hint($fieldRules, 'affiliation') ?>
                                        <input name="affiliation" class="form-control" value="<?= pf_h($profile['affiliation'] ?? '') ?>">
                                    </div>
                                <?php endif; ?>

                                <?php if (pf_visible($fieldRules, 'affiliation_ar')): ?>
                                    <div class="col-md-12">
                                        <label class="form-label fw-bold"><?= pf_label($fieldRules, 'affiliation_ar', 'Affiliation Arabic') ?></label>
                                        <?= pf_hint($fieldRules, 'affiliation_ar') ?>
                                        <input name="affiliation_ar" class="form-control" dir="rtl" value="<?= pf_h($profile['affiliation_ar'] ?? '') ?>">
                                    </div>
                                <?php endif; ?>

                                <?php foreach (['college'=>'College / Faculty','department'=>'Department','academic_rank'=>'Academic Rank'] as $key=>$label): ?>
                                    <?php if (pf_visible($fieldRules, $key)): ?>
                                        <div class="col-md-<?= $key === 'academic_rank' ? '12' : '6' ?>">
                                            <label class="form-label fw-bold"><?= pf_label($fieldRules, $key, $label) ?></label>
                                            <?= pf_hint($fieldRules, $key) ?>
                                            <?php if ($key === 'academic_rank'): ?>
                                                <select name="academic_rank" class="form-select">
                                                    <?php foreach (['','Professor','Associate Professor','Assistant Professor','Lecturer','Researcher','Graduate Student','Industry Professional','Other'] as $x): ?>
                                                        <option value="<?= pf_h($x) ?>" <?= (($profile['academic_rank'] ?? '') === $x) ? 'selected' : '' ?>>
                                                            <?= $x === '' ? 'Select' : pf_h($x) ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            <?php else: ?>
                                                <input name="<?= pf_h($key) ?>" class="form-control" value="<?= pf_h($profile[$key] ?? '') ?>">
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xl-6">
                    <div class="card ec-profile-card h-100">
                        <div class="card-body p-4">
                            <h5 class="ec-profile-section-title"><i class="fa fa-graduation-cap"></i> Education & Specialization</h5>

                            <div class="row g-3">
                                <?php foreach (['major'=>'Major','specialization'=>'Specialization'] as $key=>$label): ?>
                                    <?php if (pf_visible($fieldRules, $key)): ?>
                                        <div class="col-md-6">
                                            <label class="form-label fw-bold"><?= pf_label($fieldRules, $key, $label) ?></label>
                                            <?= pf_hint($fieldRules, $key) ?>
                                            <input name="<?= pf_h($key) ?>" class="form-control" value="<?= pf_h($profile[$key] ?? '') ?>">
                                        </div>
                                    <?php endif; ?>
                                <?php endforeach; ?>

                                <?php if (pf_visible($fieldRules, 'education_level')): ?>
                                    <div class="col-md-6">
                                        <label class="form-label fw-bold"><?= pf_label($fieldRules, 'education_level', 'Education Level') ?></label>
                                        <?= pf_hint($fieldRules, 'education_level') ?>
                                        <select name="education_level" class="form-select">
                                            <?php foreach (['','Bachelor','Master','PhD','Postdoc','Professional Certificate','Other'] as $x): ?>
                                                <option value="<?= pf_h($x) ?>" <?= (($profile['education_level'] ?? '') === $x) ? 'selected' : '' ?>>
                                                    <?= $x === '' ? 'Select' : pf_h($x) ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                <?php endif; ?>

                                <?php foreach (['highest_degree'=>'Highest Degree','degree_university'=>'Degree University','graduation_year'=>'Graduation Year'] as $key=>$label): ?>
                                    <?php if (pf_visible($fieldRules, $key)): ?>
                                        <div class="col-md-<?= $key === 'degree_university' ? '8' : '4' ?>">
                                            <label class="form-label fw-bold"><?= pf_label($fieldRules, $key, $label) ?></label>
                                            <?= pf_hint($fieldRules, $key) ?>
                                            <input name="<?= pf_h($key) ?>" class="form-control" value="<?= pf_h($profile[$key] ?? '') ?>">
                                        </div>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xl-6">
                    <div class="card ec-profile-card h-100">
                        <div class="card-body p-4">
                            <h5 class="ec-profile-section-title"><i class="fa fa-address-card"></i> Contact & Files</h5>

                            <div class="row g-3">
                                <?php foreach (['mobile'=>'Mobile','phone'=>'Phone','country'=>'Country','city'=>'City'] as $key=>$label): ?>
                                    <?php if (pf_visible($fieldRules, $key)): ?>
                                        <div class="col-md-6">
                                            <label class="form-label fw-bold"><?= pf_label($fieldRules, $key, $label) ?></label>
                                            <?= pf_hint($fieldRules, $key) ?>
                                            <input name="<?= pf_h($key) ?>" class="form-control" value="<?= pf_h($profile[$key] ?? ($user[$key] ?? '')) ?>">
                                        </div>
                                    <?php endif; ?>
                                <?php endforeach; ?>

                                <?php if (pf_visible($fieldRules, 'profile_image')): ?>
                                    <div class="col-md-6">
                                        <label class="form-label fw-bold"><?= pf_label($fieldRules, 'profile_image', 'Profile Picture') ?></label>
                                        <?= pf_hint($fieldRules, 'profile_image') ?>
                                        <input type="file" name="profile_image" class="form-control" accept=".jpg,.jpeg,.png,.webp">
                                    </div>
                                <?php endif; ?>

                                <?php if (pf_visible($fieldRules, 'cv_file')): ?>
                                    <div class="col-md-6">
                                        <label class="form-label fw-bold"><?= pf_label($fieldRules, 'cv_file', 'CV File') ?></label>
                                        <?= pf_hint($fieldRules, 'cv_file') ?>
                                        <input type="file" name="cv_file" class="form-control" accept=".pdf,.doc,.docx">
                                        <?php if (!empty($profile['cv_file'])): ?>
                                            <div class="mt-2"><a target="_blank" href="/easychair/storage/<?= pf_h($profile['cv_file']) ?>">Current CV</a></div>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xl-6">
                    <div class="card ec-profile-card h-100">
                        <div class="card-body p-4">
                            <h5 class="ec-profile-section-title"><i class="fa fa-id-badge"></i> Researcher IDs</h5>

                            <div class="row g-3">
                                <?php foreach (['orcid'=>'ORCID','scopus_id'=>'Scopus ID','google_scholar'=>'Google Scholar URL','personal_website'=>'Personal Website','linkedin_url'=>'LinkedIn URL'] as $key=>$label): ?>
                                    <?php if (pf_visible($fieldRules, $key)): ?>
                                        <div class="col-md-<?= in_array($key, ['google_scholar'], true) ? '12' : '6' ?>">
                                            <label class="form-label fw-bold"><?= pf_label($fieldRules, $key, $label) ?></label>
                                            <?= pf_hint($fieldRules, $key) ?>
                                            <input name="<?= pf_h($key) ?>" class="form-control" value="<?= pf_h($profile[$key] ?? ($user[$key] ?? '')) ?>">
                                        </div>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-xl-12">
                    <div class="card ec-profile-card">
                        <div class="card-body p-4">
                            <h5 class="ec-profile-section-title"><i class="fa fa-microscope"></i> Research Profile</h5>

                            <div class="row g-3">
                                <?php foreach (['research_interests'=>'Research Interests','keywords'=>'Keywords','bio'=>'Bio','bio_ar'=>'Bio Arabic'] as $key=>$label): ?>
                                    <?php if (pf_visible($fieldRules, $key)): ?>
                                        <div class="col-md-6">
                                            <label class="form-label fw-bold"><?= pf_label($fieldRules, $key, $label) ?></label>
                                            <?= pf_hint($fieldRules, $key) ?>
                                            <textarea name="<?= pf_h($key) ?>" rows="5" class="form-control" <?= $key === 'bio_ar' ? 'dir="rtl"' : '' ?>><?= pf_h($profile[$key] ?? '') ?></textarea>
                                        </div>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <?php
                $reviewerKeys = ['reviewer_expertise','review_keywords','preferred_tracks','reviewer_capacity','conflict_of_interest'];
                $showReviewerBlock = false;
                foreach ($reviewerKeys as $k) {
                    if (pf_visible($fieldRules, $k)) { $showReviewerBlock = true; break; }
                }
                ?>

                <?php if ($showReviewerBlock): ?>
                    <div class="col-xl-12">
                        <div class="card ec-profile-card">
                            <div class="card-body p-4">
                                <h5 class="ec-profile-section-title"><i class="fa fa-user-check"></i> Reviewer Profile</h5>

                                <div class="row g-3">
                                    <?php foreach (['reviewer_expertise'=>'Reviewer Expertise','review_keywords'=>'Review Keywords','preferred_tracks'=>'Preferred Tracks','conflict_of_interest'=>'Conflict of Interest'] as $key=>$label): ?>
                                        <?php if (pf_visible($fieldRules, $key)): ?>
                                            <div class="col-md-6">
                                                <label class="form-label fw-bold"><?= pf_label($fieldRules, $key, $label) ?></label>
                                                <?= pf_hint($fieldRules, $key) ?>
                                                <textarea name="<?= pf_h($key) ?>" rows="5" class="form-control"><?= pf_h($profile[$key] ?? ($key === 'reviewer_expertise' ? ($user['expertise'] ?? '') : '')) ?></textarea>
                                            </div>
                                        <?php endif; ?>
                                    <?php endforeach; ?>

                                    <?php if (pf_visible($fieldRules, 'reviewer_capacity')): ?>
                                        <div class="col-md-3">
                                            <label class="form-label fw-bold"><?= pf_label($fieldRules, 'reviewer_capacity', 'Reviewer Capacity') ?></label>
                                            <?= pf_hint($fieldRules, 'reviewer_capacity') ?>
                                            <input type="number" min="0" name="reviewer_capacity" class="form-control" value="<?= (int)($profile['reviewer_capacity'] ?? 0) ?>">
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <?php if ($customFields): ?>
                    <div class="col-xl-12">
                        <div class="card ec-profile-card">
                            <div class="card-body p-4">
                                <h5 class="ec-profile-section-title"><i class="fa fa-puzzle-piece"></i> Additional Conference Fields</h5>

                                <div class="row g-3">
                                    <?php foreach ($customFields as $cf): ?>
                                        <?php
                                        $cid = (int)$cf['id'];
                                        $val = (string)($customValues[$cid] ?? '');
                                        $requiredBadge = !empty($cf['is_required'])
                                            ? '<span class="ec-required-badge">Required</span>'
                                            : '<span class="ec-optional-badge">Optional</span>';
                                        ?>
                                        <div class="col-md-6">
                                            <label class="form-label fw-bold">
                                                <?= pf_h($cf['field_label']) ?> <?= $requiredBadge ?>
                                            </label>
                                            <?php if (!empty($cf['help_text'])): ?>
                                                <div class="ec-field-hint"><?= pf_h($cf['help_text']) ?></div>
                                            <?php endif; ?>

                                            <?php if ($cf['field_type'] === 'textarea'): ?>
                                                <textarea name="custom_<?= $cid ?>" rows="4" class="form-control"><?= pf_h($val) ?></textarea>
                                            <?php elseif ($cf['field_type'] === 'select'): ?>
                                                <select name="custom_<?= $cid ?>" class="form-select">
                                                    <option value="">Select</option>
                                                    <?php foreach (explode('|', (string)$cf['options_text']) as $opt): ?>
                                                        <?php $opt = trim($opt); if ($opt === '') continue; ?>
                                                        <option value="<?= pf_h($opt) ?>" <?= $val === $opt ? 'selected' : '' ?>><?= pf_h($opt) ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            <?php else: ?>
                                                <input type="<?= pf_h($cf['field_type']) ?>" name="custom_<?= $cid ?>" class="form-control" value="<?= pf_h($val) ?>">
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <?php if (pf_visible($fieldRules, 'author_notes')): ?>
                    <div class="col-xl-12">
                        <div class="card ec-profile-card">
                            <div class="card-body p-4">
                                <h5 class="ec-profile-section-title"><i class="fa fa-note-sticky"></i> Author Notes</h5>
                                <label class="form-label fw-bold"><?= pf_label($fieldRules, 'author_notes', 'Author Notes') ?></label>
                                <?= pf_hint($fieldRules, 'author_notes') ?>
                                <textarea name="author_notes" rows="5" class="form-control"><?= pf_h($profile['author_notes'] ?? '') ?></textarea>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <div class="col-xl-12">
                    <div class="card ec-profile-card">
                        <div class="card-body p-4 text-end">
                            <button class="btn btn-success btn-lg rounded-pill px-5">
                                <i class="fa fa-save"></i>
                                Save Profile
                            </button>
                        </div>
                    </div>
                </div>

            </div>
        </form>

    </div>
</div>
