<?php
function pfr_h($v) {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}
$rules = $rules ?? [];
$selectedRole = $_GET['role'] ?? '';
$displayRules = $selectedRole === '' ? $rules : array_values(array_filter($rules, fn($x) => ($x['role_code'] ?? '') === $selectedRole));
$customFields = $customFields ?? [];
$success = $_SESSION['flash_success'] ?? '';
$error = $_SESSION['flash_error'] ?? '';
unset($_SESSION['flash_success'], $_SESSION['flash_error']);

$roleLabels = [
    'author' => 'Author',
    'reviewer' => 'Reviewer',
    'track_chair' => 'Track Chair',
    'conference_chair' => 'Conference Chair',
    'organizer' => 'Organizer',
    'admin' => 'Admin',
    'org_admin' => 'Org Admin',
    'super_admin' => 'Super Admin',
    'all' => 'All Roles',
];
?>

<div class="container-fluid py-3">

    <div class="card border-0 shadow-sm mb-4" style="border-radius:24px;background:linear-gradient(135deg,#0f172a,#1d4ed8);color:#fff;">
        <div class="card-body p-4">
            <h3 class="fw-bold mb-1"><i class="fa fa-list-check"></i> Profile Field Rules</h3>
            <div class="opacity-75">
                Choose mandatory/optional profile fields per role and add custom fields for this conference.
            </div>
        </div>
    </div>

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

    <?php if ($error): ?>
        <div class="alert alert-danger"><?= pfr_h($error) ?></div>
    <?php endif; ?>

    <div class="card border-0 shadow-sm mb-4" style="border-radius:22px;">
        <div class="card-body p-4">
            <h5 class="fw-bold mb-3">Add Custom Profile Field</h5>

            <form method="post" action="/easychair/admin/profile-fields/custom/store" class="row g-3">
                <div class="col-md-2">
                    <label class="form-label fw-bold">Role</label>
                    <select name="role_code" class="form-select">
                        <?php foreach ($roleLabels as $code => $label): ?>
                            <option value="<?= pfr_h($code) ?>"><?= pfr_h($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-2">
                    <label class="form-label fw-bold">Field Key</label>
                    <input name="field_key" class="form-control" placeholder="passport_no">
                </div>

                <div class="col-md-3">
                    <label class="form-label fw-bold">Label EN</label>
                    <input name="field_label" class="form-control" required placeholder="Passport Number">
                </div>

                <div class="col-md-3">
                    <label class="form-label fw-bold">Label AR</label>
                    <input name="field_label_ar" class="form-control" dir="rtl" placeholder="رقم الجواز">
                </div>

                <div class="col-md-2">
                    <label class="form-label fw-bold">Type</label>
                    <select name="field_type" class="form-select">
                        <?php foreach (['text','textarea','select','number','date','url','email'] as $type): ?>
                            <option value="<?= pfr_h($type) ?>"><?= pfr_h($type) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-4">
                    <label class="form-label fw-bold">Options for select</label>
                    <input name="options_text" class="form-control" placeholder="Option 1|Option 2|Option 3">
                </div>

                <div class="col-md-4">
                    <label class="form-label fw-bold">Help Text</label>
                    <input name="help_text" class="form-control">
                </div>

                <div class="col-md-2">
                    <label class="form-label fw-bold">Sort</label>
                    <input type="number" name="sort_order" class="form-control" value="500">
                </div>

                <div class="col-md-1">
                    <label class="fw-bold">
                        <input type="checkbox" name="is_required" value="1">
                        Required
                    </label>
                </div>

                <div class="col-md-1">
                    <label class="fw-bold">
                        <input type="checkbox" name="is_visible" value="1" checked>
                        Visible
                    </label>
                </div>

                <div class="col-12 text-end">
                    <button class="btn btn-success rounded-pill px-5">Add Custom Field</button>
                </div>
            </form>
        </div>
    </div>


    <div class="card border-0 shadow-sm mb-4" style="border-radius:22px;">
        <div class="card-body p-4">
            <h5 class="fw-bold mb-3">Quick Role Filter & Bulk Update</h5>

            <form method="get" action="/easychair/admin/profile-fields" class="row g-2 align-items-end mb-3">
                <div class="col-md-4">
                    <label class="form-label fw-bold">Show Role</label>
                    <select name="role" class="form-select" onchange="this.form.submit()">
                        <option value="">All roles</option>
                        <?php foreach ($roleLabels as $code => $label): if ($code === 'all') continue; ?>
                            <option value="<?= pfr_h($code) ?>" <?= (($_GET['role'] ?? '') === $code) ? 'selected' : '' ?>>
                                <?= pfr_h($label) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <a class="btn btn-outline-secondary w-100" href="/easychair/admin/profile-fields">Reset</a>
                </div>
            </form>

            <form method="post" action="/easychair/admin/profile-fields/bulk" class="row g-2 align-items-end">
                <div class="col-md-3">
                    <label class="form-label fw-bold">Role</label>
                    <select name="role_code" class="form-select" required>
                        <?php foreach ($roleLabels as $code => $label): if ($code === 'all') continue; ?>
                            <option value="<?= pfr_h($code) ?>"><?= pfr_h($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-3">
                    <label class="form-label fw-bold">Field</label>
                    <select name="field_key" class="form-select" required>
                        <?php
                        $seenKeys = [];
                        foreach ($rules as $rr):
                            if (isset($seenKeys[$rr['field_key']])) continue;
                            $seenKeys[$rr['field_key']] = true;
                        ?>
                            <option value="<?= pfr_h($rr['field_key']) ?>">
                                <?= pfr_h($rr['field_label'] . ' / ' . $rr['field_key']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-3">
                    <label class="form-label fw-bold">Action</label>
                    <select name="bulk_action" class="form-select" required>
                        <option value="required">Make Required + Visible</option>
                        <option value="optional">Make Optional</option>
                        <option value="visible">Make Visible</option>
                        <option value="hidden">Hide + Optional</option>
                    </select>
                </div>

                <div class="col-md-3">
                    <button class="btn btn-warning w-100"
                            onclick="return confirm('Apply this bulk update?')">
                        Apply Bulk Update
                    </button>
                </div>
            </form>
        </div>
    </div>

    <form method="post" action="/easychair/admin/profile-fields/rules/save">
        <div class="card border-0 shadow-sm mb-4" style="border-radius:22px;">
            <div class="card-body p-4">
                <h5 class="fw-bold mb-3">Default Profile Fields</h5>

                <div class="table-responsive">
                    <table class="table table-bordered align-middle">
                        <thead class="table-dark">
                        <tr>
                            <th>Role</th>
                            <th>Field</th>
                            <th>Required</th>
                            <th>Visible</th>
                            <th>Sort</th>
                            <th>Help Text</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($displayRules as $r): ?>
                            <tr>
                                <td>
                                    <span class="badge bg-primary"><?= pfr_h($roleLabels[$r['role_code']] ?? $r['role_code']) ?></span>
                                </td>
                                <td>
                                    <strong><?= pfr_h($r['field_label']) ?></strong>
                                    <div class="text-muted small"><?= pfr_h($r['field_key']) ?></div>
                                </td>
                                <td class="text-center">
                                    <input type="checkbox" name="rules[<?= (int)$r['id'] ?>][is_required]" value="1" <?= !empty($r['is_required']) ? 'checked' : '' ?>>
                                </td>
                                <td class="text-center">
                                    <input type="checkbox" name="rules[<?= (int)$r['id'] ?>][is_visible]" value="1" <?= !empty($r['is_visible']) ? 'checked' : '' ?>>
                                </td>
                                <td>
                                    <input type="number" name="rules[<?= (int)$r['id'] ?>][sort_order]" class="form-control" value="<?= (int)$r['sort_order'] ?>">
                                </td>
                                <td>
                                    <input name="rules[<?= (int)$r['id'] ?>][help_text]" class="form-control" value="<?= pfr_h($r['help_text'] ?? '') ?>">
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <button class="btn btn-success btn-lg rounded-pill px-5">Save Field Rules</button>
            </div>
        </div>
    </form>

    <div class="card border-0 shadow-sm" style="border-radius:22px;">
        <div class="card-body p-4">
            <h5 class="fw-bold mb-3">Custom Profile Fields</h5>

            <div class="table-responsive">
                <table class="table table-bordered align-middle">
                    <thead class="table-dark">
                    <tr>
                        <th>Role</th>
                        <th>Field</th>
                        <th>Type</th>
                        <th>Required</th>
                        <th>Visible</th>
                        <th>Sort</th>
                        <th>Delete</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($customFields as $f): ?>
                        <tr>
                            <td><span class="badge bg-primary"><?= pfr_h($roleLabels[$f['role_code']] ?? $f['role_code']) ?></span></td>
                            <td>
                                <strong><?= pfr_h($f['field_label']) ?></strong>
                                <div class="text-muted small"><?= pfr_h($f['field_key']) ?></div>
                            </td>
                            <td><?= pfr_h($f['field_type']) ?></td>
                            <td><?= !empty($f['is_required']) ? '<span class="badge bg-danger">Required</span>' : '<span class="badge bg-secondary">Optional</span>' ?></td>
                            <td><?= !empty($f['is_visible']) ? '<span class="badge bg-success">Visible</span>' : '<span class="badge bg-secondary">Hidden</span>' ?></td>
                            <td><?= (int)$f['sort_order'] ?></td>
                            <td>
                                <a class="btn btn-sm btn-danger"
                                   onclick="return confirm('Delete this custom field?')"
                                   href="/easychair/admin/profile-fields/custom/delete?id=<?= (int)$f['id'] ?>">
                                    Delete
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>

                    <?php if (!$customFields): ?>
                        <tr><td colspan="7" class="text-center text-muted py-4">No custom fields yet.</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
