<?php
function bt_h($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function bt_t($k,$f){ if(function_exists('ec_t')) return ec_t($k,$f); if(function_exists('t')) return t($k,$f); return $f; }

$tool = $tool ?? '';
$rows = $rows ?? [];
$titleMap = [
    'committee_images' => ['Committee & Participant Images','صور اللجان والمشاركين','fa-images'],
    'reviewer_assignments' => ['Reviewer Assignments','توزيع المحكمين','fa-user-plus'],
    'submission_stage_rules' => ['Submission Stage Rules','قواعد مراحل التقديم','fa-list-ol'],
    'test_email' => ['Test Email','اختبار البريد','fa-paper-plane'],
    'conference_role_permissions' => ['Conference Role Permissions','صلاحيات أدوار المؤتمر','fa-user-lock'],
    'conference_business_permissions' => ['Conference Business Permissions','صلاحيات أعمال المؤتمر','fa-shield-halved'],
    'custom_rights' => ['Custom Rights','الحقوق المخصصة','fa-key'],
];
$meta = $titleMap[$tool] ?? ['Business Tool','أداة أعمال','fa-gear'];
$title = function_exists('ec_lang') && ec_lang()==='ar' ? $meta[1] : $meta[0];
?>
<?php
$btUrl = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?: '';
$btCanCreate = function_exists('ec_can_action') ? ec_can_action($btUrl, 'create') : true;
$btCanUpdate = function_exists('ec_can_action') ? ec_can_action($btUrl, 'update') : true;
$btCanDelete = function_exists('ec_can_action') ? ec_can_action($btUrl, 'delete') : true;
?>

<div class="container-fluid py-3">
    <div class="card border-0 shadow-sm mb-4" style="border-radius:24px;background:linear-gradient(135deg,#0f172a,#2563eb);color:white;">
        <div class="card-body p-4">
            <h3 class="fw-bold mb-1"><i class="fa <?= bt_h($meta[2]) ?>"></i> <?= bt_h($title) ?></h3>
            <div class="opacity-75"><?= bt_h($conference['short_name'] ?? '') ?></div>
        </div>
    </div>

    <?php if ($tool === 'committee_images'): ?>
        <div class="card border-0 shadow-sm mb-4" style="border-radius:22px;">
            <div class="card-body p-4">
                <form method="post" enctype="multipart/form-data" action="/easychair/admin/committee-images/save" class="row g-3 align-items-end">
                    <div class="col-md-2">
                        <label class="form-label fw-bold">Type</label>
                        <select name="committee_type" class="form-select">
                            <option value="tpc">TPC</option>
                            <option value="chair">Chair</option>
                            <option value="editor">Editor</option>
                            <option value="patron">Patron</option>
                            <option value="organizing">Organizing</option>
                            <option value="scientific">Scientific</option>
                            <option value="reviewer">Reviewer</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                    <div class="col-md-2"><label class="form-label fw-bold">Name EN</label><input name="full_name_en" class="form-control"></div>
                    <div class="col-md-2"><label class="form-label fw-bold">Name AR</label><input name="full_name_ar" class="form-control"></div>
                    <div class="col-md-2"><label class="form-label fw-bold">Email</label><input name="email" class="form-control"></div>
                    <div class="col-md-2"><label class="form-label fw-bold">Image</label><input type="file" name="image" class="form-control"></div>
                    <div class="col-md-1"><label class="form-label fw-bold">Order</label><input name="sort_order" value="0" class="form-control"></div>
                    <div class="col-md-1"><?php if ($btCanCreate): ?><button class="btn btn-success w-100">Add</button><?php endif; ?></div>
                    <input type="hidden" name="is_visible" value="1">
                </form>
            </div>
        </div>

        <div class="card border-0 shadow-sm" style="border-radius:22px;"><div class="card-body p-4"><div class="table-responsive">
            <table class="table table-bordered align-middle">
                <thead class="table-dark"><tr><th>#</th><th>Image</th><th>Type</th><th>Name</th><th>Email</th><th>Order</th><th>Action</th></tr></thead>
                <tbody>
                <?php foreach($rows as $r): ?>
                    <tr>
                        <td><?= (int)$r['id'] ?></td>
                        <td><?php if(!empty($r['image_path'])): ?><img src="/easychair/public/<?= bt_h($r['image_path']) ?>" style="width:54px;height:54px;object-fit:cover;border-radius:50%;"><?php endif; ?></td>
                        <td><?= bt_h($r['committee_type'] ?? '') ?></td>
                        <td><strong><?= bt_h(($r['full_name_en'] ?? '') ?: ($r['full_name_ar'] ?? '')) ?></strong><div class="text-muted small"><?= bt_h($r['full_name_ar'] ?? '') ?></div></td>
                        <td><?= bt_h($r['email'] ?? '') ?></td>
                        <td><?= (int)($r['sort_order'] ?? 0) ?></td>
                        <td><?php if ($btCanDelete): ?><a class="btn btn-sm btn-danger" href="/easychair/admin/committee-images/delete?id=<?= (int)$r['id'] ?>" onclick="return confirm('Delete?')">Delete</a><?php endif; ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div></div></div>

    <?php elseif ($tool === 'reviewer_assignments'): ?>
        <div class="card border-0 shadow-sm mb-4" style="border-radius:22px;">
            <div class="card-body p-4">
                <form method="post" action="/easychair/admin/reviewer-assignments/save" class="row g-3 align-items-end">
                    <div class="col-md-5">
                        <label class="form-label fw-bold">Submission</label>
                        <select name="submission_id" class="form-select" required>
                            <?php foreach(($submissions ?? []) as $s): ?>
                                <option value="<?= (int)$s['id'] ?>"><?= bt_h(($s['submission_no'] ?? '') . ' - ' . (($s['title'] ?? '') ?: ($s['title_ar'] ?? ''))) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label fw-bold">Reviewer</label>
                        <select name="reviewer_id" class="form-select" required>
                            <?php foreach(($reviewers ?? []) as $u): ?>
                                <option value="<?= (int)$u['id'] ?>"><?= bt_h(trim(($u['first_name'] ?? '').' '.($u['last_name'] ?? '')) ?: ($u['email'] ?? '')) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2"><label class="form-label fw-bold">Due Date</label><input type="date" name="due_date" class="form-control"></div>
                    <div class="col-md-1"><?php if ($btCanCreate): ?><button class="btn btn-success w-100">Assign</button><?php endif; ?></div>
                </form>
            </div>
        </div>

        <div class="card border-0 shadow-sm" style="border-radius:22px;"><div class="card-body p-4"><div class="table-responsive">
            <table class="table table-bordered align-middle">
                <thead class="table-dark"><tr><th>#</th><th>Submission</th><th>Reviewer</th><th>Status</th><th>Due</th><th>Action</th></tr></thead>
                <tbody>
                <?php foreach($rows as $r): ?>
                    <tr>
                        <td><?= (int)$r['id'] ?></td>
                        <td><?= bt_h(($r['submission_no'] ?? '') . ' - ' . (($r['title'] ?? '') ?: ($r['title_ar'] ?? ''))) ?></td>
                        <td><?= bt_h(trim(($r['first_name'] ?? '').' '.($r['last_name'] ?? '')) ?: ($r['email'] ?? '')) ?></td>
                        <td><span class="badge bg-info text-dark"><?= bt_h($r['status'] ?? 'assigned') ?></span></td>
                        <td><?= bt_h($r['due_date'] ?? '') ?></td>
                        <td><?php if ($btCanDelete): ?><a class="btn btn-sm btn-danger" href="/easychair/admin/reviewer-assignments/delete?id=<?= (int)$r['id'] ?>" onclick="return confirm('Delete?')">Delete</a><?php endif; ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div></div></div>

    <?php elseif ($tool === 'submission_stage_rules'): ?>
        <div class="card border-0 shadow-sm mb-4" style="border-radius:22px;">
            <div class="card-body p-4">
                <form method="post" action="/easychair/admin/submission-stage-rules/save" class="row g-3 align-items-end">
                    <div class="col-md-2"><label class="form-label fw-bold">Stage Key</label><input name="stage_key" class="form-control" required></div>
                    <div class="col-md-2"><label class="form-label fw-bold">Title EN</label><input name="stage_title_en" class="form-control"></div>
                    <div class="col-md-2"><label class="form-label fw-bold">Title AR</label><input name="stage_title_ar" class="form-control"></div>
                    <div class="col-md-1"><label class="form-label fw-bold">Order</label><input name="sort_order" class="form-control" value="0"></div>
                    <div class="col-md-1"><label>Upload</label><input type="checkbox" name="allow_author_upload" value="1" class="form-check-input d-block"></div>
                    <div class="col-md-1"><label>Notify</label><input type="checkbox" name="notify_author" value="1" checked class="form-check-input d-block"></div>
                    <div class="col-md-1"><label>Review</label><input type="checkbox" name="require_review_complete" value="1" class="form-check-input d-block"></div>
                    <div class="col-md-1"><label>Active</label><input type="checkbox" name="is_active" value="1" checked class="form-check-input d-block"></div>
                    <div class="col-md-1"><?php if ($btCanCreate || $btCanUpdate): ?><button class="btn btn-success w-100">Save</button><?php endif; ?></div>
                </form>
            </div>
        </div>

        <div class="card border-0 shadow-sm" style="border-radius:22px;"><div class="card-body p-4"><div class="table-responsive">
            <table class="table table-bordered align-middle">
                <thead class="table-dark"><tr><th>Key</th><th>EN</th><th>AR</th><th>Order</th><th>Upload</th><th>Notify</th><th>Review</th><th>Active</th><th></th></tr></thead>
                <tbody>
                <?php foreach($rows as $r): ?>
                    <tr>
                        <td><?= bt_h($r['stage_key'] ?? '') ?></td>
                        <td><?= bt_h($r['stage_title_en'] ?? '') ?></td>
                        <td><?= bt_h($r['stage_title_ar'] ?? '') ?></td>
                        <td><?= (int)$r['sort_order'] ?></td>
                        <td><?= !empty($r['allow_author_upload'])?'Yes':'No' ?></td>
                        <td><?= !empty($r['notify_author'])?'Yes':'No' ?></td>
                        <td><?= !empty($r['require_review_complete'])?'Yes':'No' ?></td>
                        <td><?= !empty($r['is_active'])?'Yes':'No' ?></td>
                        <td><?php if ($btCanDelete): ?><a class="btn btn-sm btn-danger" href="/easychair/admin/submission-stage-rules/delete?id=<?= (int)$r['id'] ?>" onclick="return confirm('Delete?')">Delete</a><?php endif; ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div></div></div>

    <?php elseif ($tool === 'test_email'): ?>
        <div class="card border-0 shadow-sm mb-4" style="border-radius:22px;">
            <div class="card-body p-4">
                <form method="post" action="/easychair/admin/test-email/send" class="row g-3">
                    <div class="col-md-4"><label class="form-label fw-bold">Recipient</label><input name="recipient_email" class="form-control" required></div>
                    <div class="col-md-8"><label class="form-label fw-bold">Subject</label><input name="subject" class="form-control" value="EasyChair Test Email"></div>
                    <div class="col-12"><label class="form-label fw-bold">Body</label><textarea name="body" class="form-control" rows="5">This is a test email from EasyChair.</textarea></div>
                    <div class="col-12"><?php if ($btCanCreate): ?><button class="btn btn-success rounded-pill px-4">Queue Test Email</button><?php endif; ?></div>
                </form>
            </div>
        </div>
        <div class="card border-0 shadow-sm" style="border-radius:22px;"><div class="card-body p-4"><div class="table-responsive">
            <table class="table table-bordered"><thead class="table-dark"><tr><th>#</th><th>Recipient</th><th>Subject</th><th>Status</th><th>Error</th><th>Date</th></tr></thead><tbody>
            <?php foreach($rows as $r): ?><tr><td><?= (int)$r['id'] ?></td><td><?= bt_h($r['recipient_email']) ?></td><td><?= bt_h($r['subject']) ?></td><td><?= bt_h($r['status']) ?></td><td><?= bt_h($r['error_message'] ?? '') ?></td><td><?= bt_h($r['created_at']) ?></td></tr><?php endforeach; ?>
            </tbody></table>
        </div></div></div>

    <?php elseif ($tool === 'conference_role_permissions'): ?>
        <?php
            $selectedRoleId = (int)($_GET['role_id'] ?? ($roles[0]['id'] ?? 0));
            $permissionMap = $permissionMap ?? [];
        ?>

        <div class="card border-0 shadow-sm mb-4" style="border-radius:22px;">
            <div class="card-body p-4">
                <h5 class="fw-bold mb-2">Conference Role Permissions</h5>
                <div class="text-muted mb-3">
                    Super admin can enable/disable all privileges. Org admin can manage conference-level roles only.
                </div>

                <form method="get" action="/easychair/admin/conference-role-permissions" class="row g-3 align-items-end">
                    <div class="col-md-5">
                        <label class="form-label fw-bold">Select Role</label>
                        <select name="role_id" class="form-select" onchange="this.form.submit()">
                            <?php foreach(($roles ?? []) as $r): ?>
                                <option value="<?= (int)$r['id'] ?>" <?= $selectedRoleId === (int)$r['id'] ? 'selected' : '' ?>>
                                    <?= bt_h(($r['code'] ?? '') . ' - ' . ($r['name'] ?? '')) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </form>
            </div>
        </div>

        <div class="card border-0 shadow-sm" style="border-radius:22px;">
            <div class="card-body p-4">
                <form method="post" action="/easychair/admin/conference-role-permissions/save">
                    <input type="hidden" name="role_id" value="<?= (int)$selectedRoleId ?>">

                    <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
                        <h5 class="fw-bold mb-0">Enable / Disable Privileges</h5>
                        <button class="btn btn-success rounded-pill px-4">
                            <i class="fa fa-save"></i>
                            Save Privileges
                        </button>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-bordered align-middle">
                            <thead class="table-dark">
                                <tr>
                                    <th>Enabled</th>
                                    <th>Menu</th>
                                    <th>URL</th>
                                    <th>View</th>
                                    <th>Create</th>
                                    <th>Update</th>
                                    <th>Delete</th>
                                    <th>Menu Active</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php foreach(($menus ?? []) as $m): ?>
                                <?php
                                    $mid = (int)$m['id'];
                                    $perm = $permissionMap[$selectedRoleId][$mid] ?? [];
                                    $isAllowed = !empty($perm) ? !empty($perm['is_allowed']) : false;
                                    $canView = !empty($perm) ? !empty($perm['can_view']) : $isAllowed;
                                    $canCreate = !empty($perm['can_create']);
                                    $canUpdate = !empty($perm['can_update']);
                                    $canDelete = !empty($perm['can_delete']);
                                ?>
                                <tr>
                                    <td class="text-center">
                                        <input type="checkbox" name="items[<?= $mid ?>][is_allowed]" value="1" <?= $isAllowed ? 'checked' : '' ?>>
                                    </td>
                                    <td>
                                        <strong><?= bt_h(($m['label'] ?? '') ?: ($m['menu_key'] ?? '')) ?></strong>
                                        <div class="text-muted small"><?= bt_h($m['label_ar'] ?? '') ?></div>
                                    </td>
                                    <td><code><?= bt_h($m['url'] ?? '') ?></code></td>
                                    <td class="text-center"><input type="checkbox" name="items[<?= $mid ?>][can_view]" value="1" <?= $canView ? 'checked' : '' ?>></td>
                                    <td class="text-center"><input type="checkbox" name="items[<?= $mid ?>][can_create]" value="1" <?= $canCreate ? 'checked' : '' ?>></td>
                                    <td class="text-center"><input type="checkbox" name="items[<?= $mid ?>][can_update]" value="1" <?= $canUpdate ? 'checked' : '' ?>></td>
                                    <td class="text-center"><input type="checkbox" name="items[<?= $mid ?>][can_delete]" value="1" <?= $canDelete ? 'checked' : '' ?>></td>
                                    <td><?= !empty($m['is_active']) ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>' ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <button class="btn btn-success rounded-pill px-5 mt-3">
                        <i class="fa fa-save"></i>
                        Save Privileges
                    </button>
                </form>
            </div>
        </div>

    <?php elseif ($tool === 'conference_business_permissions'): ?>
        <div class="card border-0 shadow-sm mb-4" style="border-radius:22px;"><div class="card-body p-4">
            <form method="post" action="/easychair/admin/conference-business-permissions/save" class="row g-3 align-items-end">
                <div class="col-md-2"><label>Role</label><input name="role_code" class="form-control" placeholder="org_admin" required></div>
                <div class="col-md-3"><label>Business Key</label><input name="business_key" class="form-control" placeholder="production.delete" required></div>
                <div class="col-md-1"><label>View</label><input type="checkbox" name="can_view" value="1" checked class="form-check-input d-block"></div>
                <div class="col-md-1"><label>Create</label><input type="checkbox" name="can_create" value="1" class="form-check-input d-block"></div>
                <div class="col-md-1"><label>Update</label><input type="checkbox" name="can_update" value="1" class="form-check-input d-block"></div>
                <div class="col-md-1"><label>Delete</label><input type="checkbox" name="can_delete" value="1" class="form-check-input d-block"></div>
                <div class="col-md-2"><?php if ($btCanCreate || $btCanUpdate): ?><button class="btn btn-success w-100">Save</button><?php endif; ?></div>
            </form>
        </div></div>
        <div class="card border-0 shadow-sm" style="border-radius:22px;"><div class="card-body p-4"><div class="table-responsive">
            <table class="table table-bordered"><thead class="table-dark"><tr><th>Role</th><th>Business</th><th>View</th><th>Create</th><th>Update</th><th>Delete</th><th></th></tr></thead><tbody>
            <?php foreach($rows as $r): ?><tr><td><?= bt_h($r['role_code']) ?></td><td><?= bt_h($r['business_key']) ?></td><td><?= (int)$r['can_view'] ?></td><td><?= (int)$r['can_create'] ?></td><td><?= (int)$r['can_update'] ?></td><td><?= (int)$r['can_delete'] ?></td><td><?php if ($btCanDelete): ?><a class="btn btn-sm btn-danger" href="/easychair/admin/conference-business-permissions/delete?id=<?= (int)$r['id'] ?>">Delete</a><?php endif; ?></td></tr><?php endforeach; ?>
            </tbody></table>
        </div></div></div>

    <?php elseif ($tool === 'custom_rights'): ?>
        <div class="card border-0 shadow-sm mb-4" style="border-radius:22px;"><div class="card-body p-4">
            <form method="post" action="/easychair/admin/custom-rights/save" class="row g-3 align-items-end">
                <div class="col-md-2"><label>Role</label><input name="role_code" class="form-control" required></div>
                <div class="col-md-2"><label>Right Key</label><input name="right_key" class="form-control" required></div>
                <div class="col-md-2"><label>Label EN</label><input name="right_label_en" class="form-control"></div>
                <div class="col-md-2"><label>Label AR</label><input name="right_label_ar" class="form-control"></div>
                <div class="col-md-1"><label>Allow</label><input type="checkbox" name="is_allowed" value="1" checked class="form-check-input d-block"></div>
                <div class="col-md-2"><label>Notes</label><input name="notes" class="form-control"></div>
                <div class="col-md-1"><?php if ($btCanCreate || $btCanUpdate): ?><button class="btn btn-success w-100">Save</button><?php endif; ?></div>
            </form>
        </div></div>
        <div class="card border-0 shadow-sm" style="border-radius:22px;"><div class="card-body p-4"><div class="table-responsive">
            <table class="table table-bordered"><thead class="table-dark"><tr><th>Role</th><th>Key</th><th>EN</th><th>AR</th><th>Allowed</th><th></th></tr></thead><tbody>
            <?php foreach($rows as $r): ?><tr><td><?= bt_h($r['role_code']) ?></td><td><?= bt_h($r['right_key']) ?></td><td><?= bt_h($r['right_label_en']) ?></td><td><?= bt_h($r['right_label_ar']) ?></td><td><?= (int)$r['is_allowed'] ?></td><td><?php if ($btCanDelete): ?><a class="btn btn-sm btn-danger" href="/easychair/admin/custom-rights/delete?id=<?= (int)$r['id'] ?>">Delete</a><?php endif; ?></td></tr><?php endforeach; ?>
            </tbody></table>
        </div></div></div>
    <?php endif; ?>
</div>
