<?php
$app = $application;
$lang = current_lang();
?>

<?php $__view->push('styles') ?>
<link href="/modules/applications/css/applications.css" rel="stylesheet">
<?php $__view->endPush() ?>

<div class="container-fluid fade-in">
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <h4 class="mb-1"><?= e($app['full_name_en']) ?></h4>
            <div class="text-muted"><?= e($app['application_number']) ?> <?= status_badge($app['status']) ?> <?= status_badge($app['priority']) ?></div>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <?php if ($app['status'] === 'draft'): ?>
            <button class="btn btn-success" onclick="submitApplication(<?= $app['id'] ?>)"><i class="fas fa-paper-plane me-1"></i><?= lang('applications.submit') ?></button>
            <a href="/applications/<?= $app['id'] ?>/edit" class="btn btn-warning"><i class="fas fa-edit me-1"></i><?= lang('common.edit') ?></a>
            <?php endif; ?>

            <?php if (in_array($app['status'], ['submitted', 'under_review', 'documents_pending', 'interview_completed']) && Gate::can('applications.review')): ?>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#statusModal"><i class="fas fa-exchange-alt me-1"></i><?= lang('applications.change_status') ?></button>
            <?php endif; ?>

            <?php if ($app['status'] === 'submitted' && Gate::can('applications.review')): ?>
            <button class="btn btn-info" data-bs-toggle="modal" data-bs-target="#reviewModal"><i class="fas fa-clipboard-check me-1"></i><?= lang('applications.review') ?></button>
            <?php endif; ?>

            <?php if (in_array($app['status'], ['under_review', 'interview_scheduled']) && Gate::can('applications.review')): ?>
            <button class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#interviewModal"><i class="fas fa-calendar me-1"></i><?= lang('applications.schedule_interview') ?></button>
            <?php endif; ?>

            <?php if ($app['status'] === 'board_pending' && Gate::can('applications.approve')): ?>
            <a href="/applications/<?= $app['id'] ?>/board-vote" class="btn btn-dark"><i class="fas fa-vote-yea me-1"></i><?= lang('applications.board_vote') ?></a>
            <?php endif; ?>

            <?php if ($app['status'] === 'approved' && !$app['resulting_member_id'] && Gate::can('applications.approve')): ?>
            <button class="btn btn-success" onclick="createMember(<?= $app['id'] ?>)"><i class="fas fa-user-plus me-1"></i><?= lang('applications.create_member') ?></button>
            <?php endif; ?>

            <a href="/applications/<?= $app['id'] ?>/print" class="btn btn-outline-secondary" target="_blank"><i class="fas fa-print me-1"></i><?= lang('common.print') ?></a>
        </div>
    </div>

    <?php if ($app['resulting_member_id']): ?>
    <div class="alert alert-success"><i class="fas fa-check-circle me-2"></i>Member created: <a href="/members/<?= $app['resulting_member_id'] ?>" class="fw-bold"><?= e($app['resulting_member_number'] ?? '#' . $app['resulting_member_id']) ?></a></div>
    <?php endif; ?>

    <!-- Tabs -->
    <ul class="nav nav-tabs mb-4" role="tablist">
        <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#tab-details"><i class="fas fa-info-circle me-1"></i>Details</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-documents"><i class="fas fa-file me-1"></i>Documents <span class="badge bg-primary"><?= count($documents) ?></span></a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-sponsors"><i class="fas fa-handshake me-1"></i>Sponsors <span class="badge bg-secondary"><?= count($sponsors) ?></span></a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-reviews"><i class="fas fa-clipboard-check me-1"></i>Reviews</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-interviews"><i class="fas fa-calendar me-1"></i>Interviews</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-fees"><i class="fas fa-money-bill me-1"></i>Fees</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-history"><i class="fas fa-history me-1"></i>History</a></li>
    </ul>

    <div class="tab-content">
        <!-- Details Tab -->
        <div class="tab-pane fade show active" id="tab-details">
            <div class="row g-3">
                <div class="col-md-3">
                    <div class="card h-100">
                        <div class="card-body text-center">
                            <?php if ($app['photo_path']): ?>
                            <img src="/<?= e($app['photo_path']) ?>" class="img-fluid rounded mb-2" style="max-height:200px">
                            <?php else: ?>
                            <i class="fas fa-user-circle fa-5x text-muted mb-2"></i>
                            <?php endif; ?>
                            <h5><?= e($app['full_name_en']) ?></h5>
                            <?php if ($app['full_name_ar']): ?>
                            <p class="text-muted"><?= e($app['full_name_ar']) ?></p>
                            <?php endif; ?>
                            <p><?= status_badge($app['status']) ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-md-9">
                    <div class="card">
                        <div class="card-body">
                            <div class="row g-2">
                                <div class="col-md-4"><strong><?= lang('applications.membership_type') ?>:</strong><br><?= e($app['type_name_en']) ?></div>
                                <div class="col-md-4"><strong><?= lang('applications.national_id') ?>:</strong><br><?= e($app['national_id'] ?? '-') ?></div>
                                <div class="col-md-4"><strong><?= lang('applications.dob') ?>:</strong><br><?= $app['date_of_birth'] ? format_date($app['date_of_birth']) : '-' ?></div>
                                <div class="col-md-4"><strong><?= lang('applications.gender') ?>:</strong><br><?= ucfirst(e($app['gender'])) ?></div>
                                <div class="col-md-4"><strong><?= lang('applications.nationality') ?>:</strong><br><?= e($app['nationality_name_en'] ?? '-') ?></div>
                                <div class="col-md-4"><strong><?= lang('applications.marital_status') ?>:</strong><br><?= ucfirst(e($app['marital_status'] ?? '-')) ?></div>
                                <div class="col-md-4"><strong><?= lang('applications.primary_phone') ?>:</strong><br><?= e($app['primary_phone']) ?></div>
                                <div class="col-md-4"><strong><?= lang('applications.email') ?>:</strong><br><?= e($app['email'] ?? '-') ?></div>
                                <div class="col-md-4"><strong><?= lang('applications.source') ?>:</strong><br><?= ucfirst(str_replace('_', ' ', e($app['source']))) ?></div>
                                <div class="col-md-4"><strong><?= lang('applications.occupation') ?>:</strong><br><?= e($app['occupation'] ?? '-') ?></div>
                                <div class="col-md-4"><strong><?= lang('applications.employer') ?>:</strong><br><?= e($app['employer'] ?? '-') ?></div>
                                <div class="col-md-4"><strong><?= lang('applications.assigned_to') ?>:</strong><br><?= e($app['assigned_to_name'] ?? '-') ?></div>
                                <div class="col-md-6"><strong><?= lang('applications.address') ?>:</strong><br><?= e($app['address_line1'] ?? '-') ?> <?= e($app['city_name_en'] ?? '') ?> <?= e($app['country_name_en'] ?? '') ?></div>
                                <div class="col-md-3"><strong><?= lang('applications.submission_date') ?>:</strong><br><?= $app['submission_date'] ? format_date($app['submission_date']) : '-' ?></div>
                                <div class="col-md-3"><strong><?= lang('applications.created') ?>:</strong><br><?= format_datetime($app['created_at']) ?></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Documents Tab -->
        <div class="tab-pane fade" id="tab-documents">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">Documents</h6>
                    <?php if (in_array($app['status'], ['draft', 'submitted', 'documents_pending', 'under_review'])): ?>
                    <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#uploadDocModal"><i class="fas fa-upload me-1"></i>Upload Document</button>
                    <?php endif; ?>
                </div>
                <div class="card-body">
                    <?php if ($requiredDocs): ?>
                    <div class="alert alert-info mb-3"><strong>Required documents:</strong>
                        <ul class="mb-0 mt-1">
                        <?php foreach ($requiredDocs as $rd): ?>
                        <li><?= e($lang === 'ar' ? $rd['document_name_ar'] : $rd['document_name_en']) ?> <?= $rd['is_mandatory'] ? '<span class="text-danger">*</span>' : '' ?></li>
                        <?php endforeach; ?>
                        </ul>
                    </div>
                    <?php endif; ?>

                    <?php if (empty($documents)): ?>
                    <p class="text-muted text-center py-3">No documents uploaded yet.</p>
                    <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead><tr><th>Type</th><th>Name</th><th>Size</th><th>Uploaded</th><th>Verified</th><th>Actions</th></tr></thead>
                            <tbody>
                            <?php foreach ($documents as $doc): ?>
                            <tr>
                                <td><?= e($doc['document_type']) ?></td>
                                <td><?= e($doc['document_name']) ?></td>
                                <td><?= $doc['file_size_bytes'] ? round($doc['file_size_bytes'] / 1024) . ' KB' : '-' ?></td>
                                <td><?= format_datetime($doc['uploaded_at']) ?></td>
                                <td><?= $doc['is_verified'] ? '<span class="badge bg-success">Verified</span>' : '<span class="badge bg-warning">Pending</span>' ?></td>
                                <td>
                                    <a href="/<?= e($doc['file_path']) ?>" class="btn btn-sm btn-outline-primary" target="_blank"><i class="fas fa-download"></i></a>
                                    <?php if (!$doc['is_verified'] && Gate::can('applications.review')): ?>
                                    <button class="btn btn-sm btn-outline-success" onclick="verifyDoc(<?= $app['id'] ?>, <?= $doc['id'] ?>)"><i class="fas fa-check"></i></button>
                                    <?php endif; ?>
                                    <button class="btn btn-sm btn-outline-danger" onclick="deleteDoc(<?= $app['id'] ?>, <?= $doc['id'] ?>)"><i class="fas fa-trash"></i></button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Sponsors Tab -->
        <div class="tab-pane fade" id="tab-sponsors">
            <div class="card"><div class="card-body">
                <?php if (empty($sponsors)): ?>
                <p class="text-muted text-center py-3">No sponsors assigned.</p>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead><tr><th>#</th><th>Member</th><th>Name</th><th>Phone</th><th>Status</th><th>Date</th></tr></thead>
                        <tbody>
                        <?php foreach ($sponsors as $sp): ?>
                        <tr>
                            <td><?= $sp['sponsor_order'] ?></td>
                            <td><a href="/members/<?= $sp['sponsor_member_id'] ?>"><?= e($sp['membership_number']) ?></a></td>
                            <td><?= e($sp['sponsor_name']) ?></td>
                            <td><?= e($sp['sponsor_phone'] ?? '-') ?></td>
                            <td><?= status_badge($sp['status']) ?></td>
                            <td><?= $sp['recommendation_date'] ? format_date($sp['recommendation_date']) : '-' ?></td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div></div>
        </div>

        <!-- Reviews Tab -->
        <div class="tab-pane fade" id="tab-reviews">
            <div class="card"><div class="card-body">
                <?php if (empty($reviews)): ?>
                <p class="text-muted text-center py-3">No reviews recorded.</p>
                <?php else: ?>
                <?php foreach ($reviews as $rev): ?>
                <div class="border-start border-3 border-<?= $rev['decision'] === 'approve' ? 'success' : ($rev['decision'] === 'reject' ? 'danger' : 'warning') ?> ps-3 mb-3">
                    <div class="d-flex justify-content-between">
                        <strong><?= e($rev['reviewer_name']) ?></strong>
                        <small class="text-muted"><?= format_datetime($rev['reviewed_at']) ?></small>
                    </div>
                    <div>Type: <?= e($rev['review_type']) ?> | Decision: <?= status_badge($rev['decision']) ?></div>
                    <?php if ($rev['comments']): ?><p class="mb-0 mt-1"><?= e($rev['comments']) ?></p><?php endif; ?>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div></div>
        </div>

        <!-- Interviews Tab -->
        <div class="tab-pane fade" id="tab-interviews">
            <div class="card"><div class="card-body">
                <?php if (empty($interviews)): ?>
                <p class="text-muted text-center py-3">No interviews scheduled.</p>
                <?php else: ?>
                <?php foreach ($interviews as $int): ?>
                <div class="border rounded p-3 mb-3">
                    <div class="d-flex justify-content-between">
                        <strong>Scheduled: <?= format_datetime($int['scheduled_date']) ?></strong>
                        <span><?= status_badge($int['status']) ?></span>
                    </div>
                    <?php if ($int['location']): ?><p class="mb-1">Location: <?= e($int['location']) ?></p><?php endif; ?>
                    <?php if ($int['recommendation']): ?><p class="mb-1">Recommendation: <?= status_badge($int['recommendation']) ?></p><?php endif; ?>
                    <?php if ($int['rating']): ?><p class="mb-1">Rating: <?= $int['rating'] ?>/10</p><?php endif; ?>
                    <?php if ($int['interview_notes']): ?><p class="mb-0 text-muted"><?= e($int['interview_notes']) ?></p><?php endif; ?>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div></div>
        </div>

        <!-- Fees Tab -->
        <div class="tab-pane fade" id="tab-fees">
            <div class="card"><div class="card-body">
                <?php if (empty($fees)): ?>
                <p class="text-muted text-center py-3">No fees calculated.</p>
                <?php else: ?>
                <table class="table table-sm">
                    <thead><tr><th>Fee Type</th><th>Description</th><th>Amount</th><th>Paid</th></tr></thead>
                    <tbody>
                    <?php $totalFees = 0; ?>
                    <?php foreach ($fees as $fee): ?>
                    <?php $totalFees += (float)$fee['amount']; ?>
                    <tr>
                        <td><?= e($fee['fee_code']) ?></td>
                        <td><?= e($lang === 'ar' ? $fee['description_ar'] : $fee['description_en']) ?></td>
                        <td><?= money($fee['amount']) ?></td>
                        <td><?= $fee['is_paid'] ? '<span class="badge bg-success">Yes</span>' : '<span class="badge bg-danger">No</span>' ?></td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                    <tfoot><tr><th colspan="2">Total</th><th><?= money($totalFees) ?></th><th></th></tr></tfoot>
                </table>
                <?php endif; ?>
            </div></div>
        </div>

        <!-- History Tab -->
        <div class="tab-pane fade" id="tab-history">
            <div class="card"><div class="card-body">
                <?php if (empty($statusHistory)): ?>
                <p class="text-muted text-center py-3">No status changes recorded.</p>
                <?php else: ?>
                <div class="timeline">
                <?php foreach ($statusHistory as $sh): ?>
                <div class="d-flex mb-3">
                    <div class="me-3">
                        <div class="bg-primary rounded-circle d-flex align-items-center justify-content-center" style="width:32px;height:32px"><i class="fas fa-circle fa-xs text-white"></i></div>
                    </div>
                    <div>
                        <div class="d-flex gap-2">
                            <?php if ($sh['from_status']): ?><?= status_badge($sh['from_status']) ?> → <?php endif; ?><?= status_badge($sh['to_status']) ?>
                        </div>
                        <small class="text-muted"><?= format_datetime($sh['changed_at']) ?> by <?= e($sh['changed_by_name'] ?? 'System') ?></small>
                        <?php if ($sh['reason']): ?><br><small><?= e($sh['reason']) ?></small><?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div></div>
        </div>
    </div>
</div>

<!-- Status Change Modal -->
<div class="modal fade" id="statusModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title"><?= lang('applications.change_status') ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body">
        <form id="status-form">
            <?= csrf_field() ?>
            <div class="mb-3">
                <label class="form-label">New Status <span class="text-danger">*</span></label>
                <select name="status" class="form-select" required>
                    <option value="under_review">Under Review</option>
                    <option value="documents_pending">Documents Pending</option>
                    <option value="interview_scheduled">Interview Scheduled</option>
                    <option value="board_pending">Board Pending</option>
                    <option value="approved">Approved</option>
                    <option value="rejected">Rejected</option>
                    <option value="waitlisted">Waitlisted</option>
                    <option value="cancelled">Cancelled</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Assign To</label>
                <select name="assigned_to" class="form-select">
                    <option value="">-</option>
                    <?php foreach ($users as $u): ?>
                    <option value="<?= $u['id'] ?>"><?= e($u['full_name_en']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Reason</label>
                <textarea name="reason" class="form-control" rows="2"></textarea>
            </div>
        </form>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= lang('common.cancel') ?></button>
        <button type="button" class="btn btn-primary" onclick="saveStatus()"><?= lang('common.save') ?></button>
    </div>
</div></div></div>

<!-- Review Modal -->
<div class="modal fade" id="reviewModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title"><?= lang('applications.review') ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body">
        <form id="review-form">
            <?= csrf_field() ?>
            <div class="mb-3">
                <label class="form-label">Review Type <span class="text-danger">*</span></label>
                <select name="review_type" class="form-select" required>
                    <option value="initial">Initial Review</option>
                    <option value="document">Document Review</option>
                    <option value="background">Background Check</option>
                    <option value="final">Final Review</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Decision <span class="text-danger">*</span></label>
                <select name="decision" class="form-select" required>
                    <option value="approve">Approve / Forward</option>
                    <option value="return">Return for Documents</option>
                    <option value="escalate">Escalate to Board</option>
                    <option value="reject">Reject</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Comments</label>
                <textarea name="comments" class="form-control" rows="3"></textarea>
            </div>
        </form>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= lang('common.cancel') ?></button>
        <button type="button" class="btn btn-primary" onclick="saveReview()"><?= lang('common.save') ?></button>
    </div>
</div></div></div>

<!-- Interview Modal -->
<div class="modal fade" id="interviewModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title"><?= lang('applications.schedule_interview') ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body">
        <form id="interview-form">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="schedule">
            <div class="mb-3">
                <label class="form-label">Date & Time <span class="text-danger">*</span></label>
                <input type="datetime-local" name="scheduled_date" class="form-control" required>
            </div>
            <div class="mb-3">
                <label class="form-label">Location</label>
                <input type="text" name="location" class="form-control">
            </div>
        </form>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= lang('common.cancel') ?></button>
        <button type="button" class="btn btn-primary" onclick="saveInterview()"><?= lang('common.save') ?></button>
    </div>
</div></div></div>

<!-- Upload Document Modal -->
<div class="modal fade" id="uploadDocModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title">Upload Document</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body">
        <form id="upload-doc-form" enctype="multipart/form-data">
            <?= csrf_field() ?>
            <div class="mb-3">
                <label class="form-label">Document Type</label>
                <select name="document_type" class="form-select">
                    <option value="general">General</option>
                    <option value="national_id">National ID</option>
                    <option value="passport">Passport</option>
                    <option value="photo">Photo</option>
                    <option value="birth_certificate">Birth Certificate</option>
                    <option value="address_proof">Address Proof</option>
                    <option value="employment_proof">Employment Proof</option>
                    <option value="other">Other</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Document Name</label>
                <input type="text" name="document_name" class="form-control">
            </div>
            <div class="mb-3">
                <label class="form-label">File <span class="text-danger">*</span></label>
                <input type="file" name="document_file" class="form-control" required accept=".pdf,.jpg,.jpeg,.png,.doc,.docx">
            </div>
        </form>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= lang('common.cancel') ?></button>
        <button type="button" class="btn btn-primary" onclick="uploadDocument()">Upload</button>
    </div>
</div></div></div>

<?php $__view->push('scripts') ?>
<script>
const appId = <?= $app['id'] ?>;

function submitApplication(id) {
    Swal.fire({
        title: '<?= lang('applications.confirm_submit') ?>',
        text: '<?= lang('applications.confirm_submit_text') ?>',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: '<?= lang('applications.submit') ?>',
        cancelButtonText: '<?= lang('common.cancel') ?>',
    }).then((result) => {
        if (result.isConfirmed) {
            $.post('/api/applications/' + id + '/submit', { _token: '<?= csrf_token() ?>' }, function(res) {
                if (res.success) {
                    FormHelper.showToast('success', res.message);
                    setTimeout(() => location.reload(), 800);
                } else {
                    FormHelper.showToast('error', res.message);
                }
            });
        }
    });
}

function saveStatus() {
    const data = Object.fromEntries(new FormData(document.getElementById('status-form')));
    $.post('/api/applications/' + appId + '/status', data, function(res) {
        if (res.success) {
            bootstrap.Modal.getInstance(document.getElementById('statusModal')).hide();
            FormHelper.showToast('success', res.message);
            setTimeout(() => location.reload(), 800);
        } else {
            FormHelper.showToast('error', res.message);
        }
    });
}

function saveReview() {
    const data = Object.fromEntries(new FormData(document.getElementById('review-form')));
    $.post('/api/applications/' + appId + '/review', data, function(res) {
        if (res.success) {
            bootstrap.Modal.getInstance(document.getElementById('reviewModal')).hide();
            FormHelper.showToast('success', res.message);
            setTimeout(() => location.reload(), 800);
        } else {
            FormHelper.showToast('error', res.message || 'Failed');
        }
    });
}

function saveInterview() {
    const data = Object.fromEntries(new FormData(document.getElementById('interview-form')));
    $.post('/api/applications/' + appId + '/interview', data, function(res) {
        if (res.success) {
            bootstrap.Modal.getInstance(document.getElementById('interviewModal')).hide();
            FormHelper.showToast('success', res.message);
            setTimeout(() => location.reload(), 800);
        } else {
            FormHelper.showToast('error', res.message || 'Failed');
        }
    });
}

function createMember(id) {
    Swal.fire({
        title: '<?= lang('applications.confirm_create_member') ?>',
        text: '<?= lang('applications.confirm_create_member_text') ?>',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: '<?= lang('applications.create_member') ?>',
    }).then((result) => {
        if (result.isConfirmed) {
            $.post('/api/applications/' + id + '/create-member', { _token: '<?= csrf_token() ?>' }, function(res) {
                if (res.success) {
                    FormHelper.showToast('success', res.message);
                    if (res.redirect) setTimeout(() => window.location.href = res.redirect, 800);
                } else {
                    FormHelper.showToast('error', res.message);
                }
            });
        }
    });
}

function uploadDocument() {
    const form = document.getElementById('upload-doc-form');
    const fd = new FormData(form);
    $.ajax({
        url: '/api/applications/' + appId + '/documents',
        type: 'POST',
        data: fd,
        processData: false,
        contentType: false,
        success: function(res) {
            if (res.success) {
                bootstrap.Modal.getInstance(document.getElementById('uploadDocModal')).hide();
                FormHelper.showToast('success', res.message);
                setTimeout(() => location.reload(), 800);
            } else {
                FormHelper.showToast('error', res.message);
            }
        }
    });
}

function verifyDoc(appId, docId) {
    $.post('/api/applications/' + appId + '/documents/' + docId + '/verify', { _token: '<?= csrf_token() ?>' }, function(res) {
        if (res.success) {
            FormHelper.showToast('success', res.message);
            setTimeout(() => location.reload(), 500);
        }
    });
}

function deleteDoc(appId, docId) {
    Swal.fire({ title: 'Delete document?', icon: 'warning', showCancelButton: true, confirmButtonColor: '#e53e3e' }).then((result) => {
        if (result.isConfirmed) {
            $.post('/api/applications/' + appId + '/documents/' + docId + '/delete', { _token: '<?= csrf_token() ?>' }, function(res) {
                if (res.success) { FormHelper.showToast('success', res.message); setTimeout(() => location.reload(), 500); }
            });
        }
    });
}
</script>
<?php $__view->endPush() ?>