<?php $app = $application; ?>

<div class="container-fluid fade-in">
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-vote-yea me-2"></i><?= lang('applications.board_vote') ?> - <?= e($app['application_number']) ?></h5>
            <small class="text-muted"><?= e($app['full_name_en']) ?> | <?= e($app['type_name_en']) ?></small>
        </div>
        <div class="card-body">
            <?php if (empty($boardMembers)): ?>
            <div class="alert alert-warning">No active board term or board members found.</div>
            <?php else: ?>
            <form id="vote-form">
                <?= csrf_field() ?>
                <table class="table">
                    <thead><tr><th>Board Member</th><th>Position</th><th>Vote</th><th>Comments</th></tr></thead>
                    <tbody>
                    <?php foreach ($boardMembers as $bm): ?>
                    <?php
                        $existingVote = null;
                        foreach ($existingVotes as $ev) {
                            if ($ev['voter_name'] && $bm['user_id'] && $ev['board_member_user_id'] == $bm['user_id']) {
                                $existingVote = $ev;
                                break;
                            }
                        }
                    ?>
                    <tr>
                        <td><?= e($bm['full_name_en'] ?: $bm['user_name'] ?? '-') ?></td>
                        <td><?= e($bm['position_title']) ?></td>
                        <td>
                            <?php if ($bm['user_id']): ?>
                            <select name="votes[<?= $bm['user_id'] ?>][vote]" class="form-select form-select-sm">
                                <option value="approve" <?= selected('approve', $existingVote['vote'] ?? '') ?>>Approve</option>
                                <option value="reject" <?= selected('reject', $existingVote['vote'] ?? '') ?>>Reject</option>
                                <option value="abstain" <?= selected('abstain', $existingVote['vote'] ?? '') ?>>Abstain</option>
                            </select>
                            <?php else: ?>
                            <span class="text-muted">No user linked</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($bm['user_id']): ?>
                            <input type="text" name="votes[<?= $bm['user_id'] ?>][comments]" class="form-control form-control-sm" value="<?= e($existingVote['comments'] ?? '') ?>">
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>

                <?php if (!empty($existingVotes)): ?>
                <div class="alert alert-info">
                    <strong>Current tally:</strong>
                    <?php
                    $for = $against = $abstain = 0;
                    foreach ($existingVotes as $v) {
                        if ($v['vote'] === 'approve') $for++;
                        elseif ($v['vote'] === 'reject') $against++;
                        else $abstain++;
                    }
                    ?>
                    <span class="badge bg-success">For: <?= $for ?></span>
                    <span class="badge bg-danger">Against: <?= $against ?></span>
                    <span class="badge bg-secondary">Abstain: <?= $abstain ?></span>
                </div>
                <?php endif; ?>

                <div class="d-flex gap-2 mt-3">
                    <button type="button" class="btn btn-primary" onclick="saveVotes()"><i class="fas fa-save me-1"></i>Save & Calculate Result</button>
                    <a href="/applications/<?= $app['id'] ?>" class="btn btn-secondary"><?= lang('common.back') ?></a>
                </div>
            </form>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php $__view->push('scripts') ?>
<script>
function saveVotes() {
    const form = document.getElementById('vote-form');
    const fd = new FormData(form);
    const data = {};
    for (const [key, value] of fd.entries()) {
        const keys = key.match(/votes\[(\d+)]\[(\w+)]/);
        if (keys) {
            if (!data['votes']) data['votes'] = {};
            if (!data['votes'][keys[1]]) data['votes'][keys[1]] = {};
            data['votes'][keys[1]][keys[2]] = value;
        } else {
            data[key] = value;
        }
    }

    $.ajax({
        url: '/api/applications/<?= $app['id'] ?>/board-vote',
        type: 'POST',
        data: JSON.stringify(data),
        contentType: 'application/json',
        headers: { 'X-CSRF-TOKEN': '<?= csrf_token() ?>' },
        success: function(res) {
            if (res.success) {
                FormHelper.showToast('success', res.message);
                setTimeout(() => window.location.href = '/applications/<?= $app['id'] ?>', 800);
            } else {
                FormHelper.showToast('error', res.message);
            }
        }
    });
}
</script>
<?php $__view->endPush() ?>