<?php
$db=\App\Core\Database::getInstance();

$row = $row ?? $submission ?? [];
$id = (int)($row['id'] ?? ($_GET['id'] ?? 0));

$stmt=$db->prepare("
SELECT *
FROM submission_authors
WHERE submission_id=?
ORDER BY is_corresponding DESC, author_order ASC, id ASC
");
$stmt->execute([$id]);
$authors=$stmt->fetchAll(PDO::FETCH_ASSOC);

if (!$authors) {
    $authors[]=[
        'full_name'=>$_SESSION['name'] ?? $_SESSION['full_name'] ?? 'Author',
        'email'=>$_SESSION['email'] ?? '',
        'affiliation'=>'',
        'country'=>'Jordan',
        'is_corresponding'=>1,
        'author_order'=>1
    ];
}

$countries=[
'Jordan','Afghanistan','Albania','Algeria','Andorra','Angola','Antigua and Barbuda','Argentina','Armenia','Australia','Austria','Azerbaijan','Bahamas','Bahrain','Bangladesh','Barbados','Belarus','Belgium','Belize','Benin','Bhutan','Bolivia','Bosnia and Herzegovina','Botswana','Brazil','Brunei','Bulgaria','Burkina Faso','Burundi','Cabo Verde','Cambodia','Cameroon','Canada','Central African Republic','Chad','Chile','China','Colombia','Comoros','Congo (Congo-Brazzaville)','Costa Rica',"Côte d'Ivoire",'Croatia','Cuba','Cyprus','Czechia (Czech Republic)','Democratic Republic of the Congo','Denmark','Djibouti','Dominica','Dominican Republic','Ecuador','Egypt','El Salvador','Equatorial Guinea','Eritrea','Estonia','Eswatini','Ethiopia','Fiji','Finland','France','Gabon','Gambia','Georgia','Germany','Ghana','Greece','Grenada','Guatemala','Guinea','Guinea-Bissau','Guyana','Haiti','Holy See','Honduras','Hungary','Iceland','India','Indonesia','Iran','Iraq','Ireland','Israel','Italy','Jamaica','Japan','Kazakhstan','Kenya','Kiribati','Kuwait','Kyrgyzstan','Laos','Latvia','Lebanon','Lesotho','Liberia','Libya','Liechtenstein','Lithuania','Luxembourg','Madagascar','Malawi','Malaysia','Maldives','Mali','Malta','Marshall Islands','Mauritania','Mauritius','Mexico','Micronesia','Moldova','Monaco','Mongolia','Montenegro','Morocco','Mozambique','Myanmar','Namibia','Nauru','Nepal','Netherlands','New Zealand','Nicaragua','Niger','Nigeria','North Korea','North Macedonia','Norway','Oman','Pakistan','Palau','Palestine State','Panama','Papua New Guinea','Paraguay','Peru','Philippines','Poland','Portugal','Qatar','Romania','Russia','Rwanda','Saint Kitts and Nevis','Saint Lucia','Saint Vincent and the Grenadines','Samoa','San Marino','Sao Tome and Principe','Saudi Arabia','Senegal','Serbia','Seychelles','Sierra Leone','Singapore','Slovakia','Slovenia','Solomon Islands','Somalia','South Africa','South Korea','South Sudan','Spain','Sri Lanka','Sudan','Suriname','Sweden','Switzerland','Syria','Tajikistan','Tanzania','Thailand','Timor-Leste','Togo','Tonga','Trinidad and Tobago','Tunisia','Turkey','Turkmenistan','Tuvalu','Uganda','Ukraine','United Arab Emirates','United Kingdom','United States of America','Uruguay','Uzbekistan','Vanuatu','Venezuela','Vietnam','Yemen','Zambia','Zimbabwe'
];

/*
function eh($v){
    return htmlspecialchars((string)$v,ENT_QUOTES,'UTF-8');
}
*/

$isAr = ($_SESSION['lang'] ?? 'ar') === 'ar';
?>

<style>
.ec-edit-wrap{max-width:1500px;margin:auto}
.ec-card{border:0;border-radius:24px;box-shadow:0 18px 55px rgba(15,23,42,.08);overflow:hidden}
.ec-hero{background:linear-gradient(135deg,#07112d,#1d4ed8);color:#fff;border-radius:28px}
.ec-author-row{border:1px solid #e5e7eb;border-radius:18px;padding:16px;margin-bottom:12px;background:#fff}
.ec-author-row.corresponding{border-color:#2563eb;background:#eff6ff}
.ec-pill{border-radius:999px}
.ec-muted{color:#64748b}
</style>

<div class="container-fluid py-4 ec-edit-wrap" dir="<?= $isAr?'rtl':'ltr' ?>">

<div class="ec-hero p-4 mb-4">
    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
        <div>
            <h2 class="fw-bold mb-1">تحرير التقديم / Edit Submission</h2>
            <div class="opacity-75">EasyChair / EDAS style submission workspace</div>
        </div>
        <div>
            <span class="badge bg-light text-dark ec-pill px-3 py-2">
                #<?= (int)$id ?>
            </span>
            <span class="badge bg-warning text-dark ec-pill px-3 py-2">
                <?= eh($row['status'] ?? 'draft') ?>
            </span>
        </div>
    </div>
</div>

<?php if(!empty($_SESSION['flash_success'])): ?>
<div class="alert alert-success"><?= eh($_SESSION['flash_success']); unset($_SESSION['flash_success']); ?></div>
<?php endif; ?>

<form method="post" action="/easychair/author/submission/update" enctype="multipart/form-data">

<input type="hidden" name="id" value="<?= (int)$id ?>">

<div class="row g-4">

<div class="col-xl-8">

<div class="card ec-card mb-4">
<div class="card-header bg-white p-4">
    <h4 class="fw-bold mb-0">بيانات البحث / Paper Metadata</h4>
</div>
<div class="card-body p-4">

<div class="row g-3">

<div class="col-md-6">
<label class="form-label fw-bold">العنوان الإنجليزي / English Title</label>
<input name="title_en" class="form-control" value="<?= eh($row['title_en'] ?? $row['title'] ?? '') ?>">
</div>

<div class="col-md-6">
<label class="form-label fw-bold">العنوان العربي / Arabic Title</label>
<input name="title_ar" class="form-control" value="<?= eh($row['title_ar'] ?? '') ?>">
</div>

<div class="col-md-6">
<label class="form-label fw-bold">الملخص الإنجليزي / English Abstract</label>
<textarea name="abstract_en" class="form-control" rows="7"><?= eh($row['abstract_en'] ?? $row['abstract'] ?? '') ?></textarea>
</div>

<div class="col-md-6">
<label class="form-label fw-bold">الملخص العربي / Arabic Abstract</label>
<textarea name="abstract_ar" class="form-control" rows="7"><?= eh($row['abstract_ar'] ?? '') ?></textarea>
</div>

<div class="col-md-6">
<label class="form-label fw-bold">الكلمات المفتاحية EN</label>
<input name="keywords_en" class="form-control" value="<?= eh($row['keywords_en'] ?? $row['keywords'] ?? '') ?>">
</div>

<div class="col-md-6">
<label class="form-label fw-bold">الكلمات المفتاحية AR</label>
<input name="keywords_ar" class="form-control" value="<?= eh($row['keywords_ar'] ?? '') ?>">
</div>

</div>

</div>
</div>

<div class="card ec-card mb-4">
<div class="card-header bg-white p-4 d-flex justify-content-between align-items-center">
    <h4 class="fw-bold mb-0">الباحثون / Authors</h4>
    <button type="button" class="btn btn-success ec-pill" onclick="addAuthorRow()">+ إضافة مؤلف</button>
</div>

<div class="card-body p-4" id="authorsBox">

<?php foreach($authors as $idx=>$a): ?>
<div class="ec-author-row <?= !empty($a['is_corresponding'])?'corresponding':'' ?>">
    <div class="row g-3 align-items-end">

        <div class="col-md-3">
            <label class="form-label fw-bold">الاسم / Name</label>
            <input name="author_name[]" class="form-control" value="<?= eh($a['full_name'] ?? '') ?>" required>
        </div>

        <div class="col-md-3">
            <label class="form-label fw-bold">البريد / Email</label>
            <input name="author_email[]" type="email" class="form-control" value="<?= eh($a['email'] ?? '') ?>">
        </div>

        <div class="col-md-3">
            <label class="form-label fw-bold">الجهة / Affiliation</label>
            <input name="author_affiliation[]" class="form-control" value="<?= eh($a['affiliation'] ?? '') ?>">
        </div>

        <div class="col-md-2">
            <label class="form-label fw-bold">الدولة / Country</label>
            <select name="author_country[]" class="form-select">
                <?php foreach($countries as $c): ?>
                <option value="<?= eh($c) ?>" <?= (($a['country'] ?? 'Jordan')===$c)?'selected':'' ?>>
                    <?= eh($c) ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-md-1">
            <label class="form-label fw-bold">مراسل</label>
            <input type="radio"
                   name="corresponding_author"
                   value="<?= (int)$idx ?>"
                   <?= !empty($a['is_corresponding'])?'checked':'' ?>
                   onchange="syncCorresponding()">
        </div>

        <div class="col-12 d-flex justify-content-between">
            <span class="badge bg-primary ec-pill corresponding-badge <?= empty($a['is_corresponding'])?'d-none':'' ?>">
                Corresponding Author
            </span>
            <button type="button" class="btn btn-outline-danger btn-sm ec-pill" onclick="removeAuthorRow(this)">
                حذف / Delete
            </button>
        </div>

    </div>
</div>
<?php endforeach; ?>

</div>
</div>

</div>

<div class="col-xl-4">

<div class="card ec-card mb-4">
<div class="card-header bg-white p-4">
    <h4 class="fw-bold mb-0">الملفات / Files</h4>
</div>
<div class="card-body p-4">

<?php if(!empty($row['file_path'])): ?>
<div class="alert alert-info">
    الملف الحالي:
    <a target="_blank" href="/easychair/public/<?= eh($row['file_path']) ?>">
        <?= eh($row['original_filename'] ?? basename($row['file_path'])) ?>
    </a>
</div>
<?php endif; ?>

<label class="form-label fw-bold">استبدال ملف البحث / Replace Manuscript</label>
<input type="file" name="manuscript_file" class="form-control mb-3">

<div class="small ec-muted">
PDF / DOC / DOCX supported according to your conference rules.
</div>

</div>
</div>

<div class="card ec-card mb-4">
<div class="card-header bg-white p-4">
    <h4 class="fw-bold mb-0">حالة التقديم / Workflow</h4>
</div>
<div class="card-body p-4">
    <div class="mb-2">Status:</div>
    <span class="badge bg-info ec-pill px-3 py-2"><?= eh($row['status'] ?? '') ?></span>

    <?php if(($row['status'] ?? '') === 'revision_required'): ?>
    <a href="/easychair/author/submission/revision?id=<?= (int)$id ?>" class="btn btn-warning w-100 mt-4 ec-pill">
        رفع نسخة معدلة / Upload Revision
    </a>
    <?php else: ?>
    <div class="alert alert-light border mt-4">
        رفع النسخة المعدلة متاح فقط بعد طلب التعديل.
    </div>
    <?php endif; ?>
</div>
</div>

<div class="d-grid gap-2">
    <button class="btn btn-primary btn-lg ec-pill">
        حفظ التعديلات / Save Updates
    </button>
    <a href="/easychair/author/submission/show?id=<?= (int)$id ?>" class="btn btn-outline-secondary ec-pill">
        رجوع / Back
    </a>
</div>

</div>

</div>

</form>

</div>

<script>
const countries = <?= json_encode($countries, JSON_UNESCAPED_UNICODE) ?>;

function countryOptions(selected='Jordan'){
    return countries.map(c => `<option value="${escapeHtml(c)}" ${c===selected?'selected':''}>${escapeHtml(c)}</option>`).join('');
}

function escapeHtml(s){
    return String(s).replace(/[&<>"']/g, m => ({
        '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'
    }[m]));
}

function addAuthorRow(){
    const box=document.getElementById('authorsBox');
    const index=box.querySelectorAll('.ec-author-row').length;

    const div=document.createElement('div');
    div.className='ec-author-row';

    div.innerHTML=`
    <div class="row g-3 align-items-end">
        <div class="col-md-3">
            <label class="form-label fw-bold">الاسم / Name</label>
            <input name="author_name[]" class="form-control" required>
        </div>
        <div class="col-md-3">
            <label class="form-label fw-bold">البريد / Email</label>
            <input name="author_email[]" type="email" class="form-control">
        </div>
        <div class="col-md-3">
            <label class="form-label fw-bold">الجهة / Affiliation</label>
            <input name="author_affiliation[]" class="form-control">
        </div>
        <div class="col-md-2">
            <label class="form-label fw-bold">الدولة / Country</label>
            <select name="author_country[]" class="form-select">${countryOptions('Jordan')}</select>
        </div>
        <div class="col-md-1">
            <label class="form-label fw-bold">مراسل</label>
            <input type="radio" name="corresponding_author" value="${index}" onchange="syncCorresponding()">
        </div>
        <div class="col-12 d-flex justify-content-between">
            <span class="badge bg-primary ec-pill corresponding-badge d-none">Corresponding Author</span>
            <button type="button" class="btn btn-outline-danger btn-sm ec-pill" onclick="removeAuthorRow(this)">حذف / Delete</button>
        </div>
    </div>`;

    box.appendChild(div);
    renumberCorresponding();
}

function removeAuthorRow(btn){
    const rows=document.querySelectorAll('.ec-author-row');

    if(rows.length<=1){
        alert('At least one author is required.');
        return;
    }

    const row=btn.closest('.ec-author-row');
    const was=row.querySelector('input[type=radio]').checked;
    row.remove();

    renumberCorresponding();

    if(was){
        const first=document.querySelector('input[name="corresponding_author"]');
        if(first){
            first.checked=true;
        }
    }

    syncCorresponding();
}

function renumberCorresponding(){
    document.querySelectorAll('input[name="corresponding_author"]').forEach((r,i)=>{
        r.value=i;
    });
}

function syncCorresponding(){
    document.querySelectorAll('.ec-author-row').forEach(row=>{
        row.classList.remove('corresponding');
        const badge=row.querySelector('.corresponding-badge');
        if(badge) badge.classList.add('d-none');
    });

    const checked=document.querySelector('input[name="corresponding_author"]:checked');
    if(!checked){
        const first=document.querySelector('input[name="corresponding_author"]');
        if(first) first.checked=true;
    }

    const active=document.querySelector('input[name="corresponding_author"]:checked');
    if(active){
        const row=active.closest('.ec-author-row');
        row.classList.add('corresponding');
        const badge=row.querySelector('.corresponding-badge');
        if(badge) badge.classList.remove('d-none');
    }
}

syncCorresponding();
</script>
