<template>
    <div class="attendance-page row col-md-10 col-md-offset-1">
        <div class="col-md-12">
            <div v-if="Number(data.user.kehadiran) === 0" class="attendance-info-top">
                <div class="attendance-info-top__kicker">Makluman</div>
                <div class="attendance-info-top__body">
                    <p><strong>*</strong> Pendaftaran akan dibuka dari <strong>jam 7.00 pagi hingga 10.00
                            pagi pada hari pengundian.</strong></p>
                    <p>
                        <strong>*</strong> Elaun kehadiran berjumlah <strong>RM300.00 (secara fizikal)</strong>
                        akan
                        diberikan secara TUNAI selepas mesyuarat. <br />
                        Manakala <strong>RM150.00 (secara atas talian)</strong> akan dikreditkan ke akaun
                        anggota
                        yang
                        hadir penuh.
                    </p>
                </div>
            </div>

            <form @submit.prevent="edit()" id="edit_form" class="attendance-card">

                <div class="text-center mt-4 attendance-action-area">
                    <div v-if="data.user.kehadiran != 0 && canProceedToVote" class="attendance-success-card">
                        <div class="attendance-success-kicker">Kehadiran Disahkan</div>
                        <p class="attendance-success-text">Kehadiran anda telah disahkan secara</p>
                        <h5 class="attendance-success-mode">
                            {{ data.user.kehadiran == 1 ? 'FIZIKAL' : 'MAYA' }}
                        </h5>

                        <template v-if="canVoteBySaham">
                            <router-link :to="{ name: 'Vote' }" class="btn btn-warning attendance-vote-button">
                                Undi Sekarang
                            </router-link>
                        </template>
                        <template v-else>
                            <div class="alert alert-warning attendance-saham-block-alert" role="alert">
                                {{ sahamVoteBlockedMessage }}
                            </div>
                            <button type="button" class="btn btn-warning attendance-vote-button" disabled>
                                Undi Sekarang
                            </button>
                        </template>
                    </div>

                    <div v-else-if="data.user.kehadiran != 0 && !canProceedToVote" class="attendance-pending-card">
                        <div class="attendance-pending-kicker">Menunggu pengesahan</div>
                        <p class="attendance-pending-text">
                            Kehadiran <strong>fizikal</strong> anda telah direkod. Sila pergi ke kaunter pendaftaran
                            untuk
                            mengesahkan pendaftaran sebelum anda boleh mengundi.
                        </p>
                        <p class="attendance-pending-hint">
                            Selepas pengesahan, butang mengundi akan dipaparkan di sini. Semak semula halaman ini
                            selepas beberapa ketika.
                        </p>
                        <button type="button" class="btn btn-default attendance-refresh-button"
                            @click="reloadAttendanceState">
                            Muat semula
                        </button>
                    </div>

                    <template v-else>
                        <!-- Title  -->
                        <h5 class="attendance-section-kicker">Butiran Kehadiran</h5>
                        <div class="attendance-register-box">
                            <p class="attendance-precheck">
                                Sila semak maklumat anda di bawah terlebih dahulu sebelum mendaftar kehadiran.
                            </p>

                            <div class="form-group attendance-choice-box">
                                <label for="kehadiran">Kehadiran</label>
                                <select v-model="selectedKehadiran" class="form-control attendance-select"
                                    id="kehadiran" name="kehadiran" required>
                                    <option value="0">Sila Pilih :</option>
                                    <option value="1">Fizikal</option>
                                    <option value="2">Maya</option>
                                </select>
                            </div>

                            <div v-if="selectedKehadiran === '1'" class="form-group attendance-field">
                                <label for="physical_gate_code">Kod skrin kaunter pendaftaran</label>
                                <input type="text" name="physical_gate_code" id="physical_gate_code"
                                    class="form-control attendance-input" autocomplete="off" autocapitalize="characters"
                                    inputmode="text" placeholder="8 aksara, semak skrin di kaunter" maxlength="64"
                                    @input="onPhysicalGateCodeInput" />
                                <small class="form-text text-muted attendance-helper-text">
                                    Kod berputar setiap minit — masukkan kod semasa yang dipaparkan di kaunter sebelum
                                    menghantar.
                                </small>
                            </div>

                            <div class="attendance-register-box__actions">
                                <button type="submit" class="btn btn-lg btn-success attendance-submit-button"
                                    v-if="electionVotingActive">
                                    DAFTAR KEHADIRAN
                                </button>
                                <div v-else class="alert alert-info attendance-voting-notice">
                                    <p class="attendance-voting-notice__title"><strong>Butang “DAFTAR KEHADIRAN” belum
                                            tersedia</strong>
                                    </p>
                                    <p class="attendance-voting-notice__body">
                                        Buat masa ini proses undian / mesyuarat <strong>belum bermula</strong>.
                                    </p>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>

                <div class="attendance-info-grid">
                    <div class="form-group attendance-field">
                        <label for="name">Nama</label>
                        <input type="text" name="name" class="form-control attendance-input" readonly
                            :value="data.user.name" required />
                    </div>

                    <div class="form-group attendance-field">
                        <label for="no_kp">No. Kad Pengenalan</label>
                        <input type="text" name="no_kp" class="form-control attendance-input" readonly
                            :value="data.user.no_kp" required />
                    </div>

                    <div class="form-group attendance-field">
                        <label for="no_anggota">No. Anggota</label>
                        <input type="text" name="no_anggota" class="form-control attendance-input" readonly
                            :value="data.user.no_anggota" required />
                    </div>

                    <div class="form-group attendance-field">
                        <label for="unit">Unit</label>
                        <input type="text" name="unit" class="form-control attendance-input" readonly
                            :value="data.user.unit" required />
                    </div>
                </div>
            </form>
        </div>
    </div>
</template>

<style>
.attendance-page {
    margin-top: 18px;
    margin-bottom: 36px;
}

.attendance-hero {
    margin-bottom: 22px;
    margin-top: 22px;
    padding: 26px 28px;
    border-radius: 22px;
    background: linear-gradient(135deg, #ffffff 0%, #eef6ff 100%);
    border: 1px solid #e2ebf5;
    box-shadow: 0 16px 34px rgba(35, 64, 97, 0.08);
    text-align: center;
}

.attendance-section-kicker {
    margin-bottom: 8px;
    color: #2f80ed;
    font-size: 1.2rem;
    font-weight: 700;
    letter-spacing: 0.08em;
    text-transform: uppercase;
}

.attendance-page-title,
.attendance-page-subtitle {
    max-width: 700px;
    margin: 0 auto 18px;
    color: #5f7388;
    line-height: 1.6;
}

.attendance-download-button {
    display: inline-block;
    padding: 12px 20px;
    border-radius: 999px;
    border: 1px solid #cfe2ff;
    background: #fff;
    color: #0d6efd;
    font-weight: 700;
    text-decoration: none !important;
    box-shadow: 0 10px 24px rgba(13, 110, 253, 0.12);
}

.attendance-card {
    padding: 24px;
    border-radius: 20px;
    background: #fff;
    border: 1px solid #e2ebf5;
    box-shadow: 0 16px 34px rgba(35, 64, 97, 0.08);
}

.attendance-info-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 16px;
}

.attendance-field {
    margin-bottom: 0;
}

.attendance-field label,
.attendance-choice-box label {
    display: block;
    margin-bottom: 8px;
    color: #45617b;
    font-weight: 700;
}

.attendance-input,
.attendance-select {
    height: 46px;
    border-radius: 12px;
    border: 1px solid #d8e3f0;
    box-shadow: none;
}

.attendance-input[readonly] {
    background: #f8fbff;
    color: #1f2937;
}

.attendance-choice-box {
    margin-top: 20px;
    padding: 18px;
    border-radius: 16px;
    border: 1px solid #ffd9a8;
    background: linear-gradient(180deg, #fffaf2 0%, #fff4df 100%);
    box-shadow: 0 10px 24px rgba(255, 193, 7, 0.08);
}

.attendance-helper-text {
    display: block;
    margin-top: 10px;
}

.attendance-precheck {
    margin: 0 0 12px;
    color: #5f7388;
    line-height: 1.5;
}

.attendance-register-box {
    text-align: left;
    padding: 18px;
    border-radius: 18px;
    border: 1px solid #e6edf6;
    background: linear-gradient(180deg, #ffffff 0%, #f7fbff 100%);
    box-shadow: 0 14px 28px rgba(35, 64, 97, 0.08);
}

.attendance-register-box__actions {
    margin-top: 16px;
    text-align: center;
}

.attendance-info-top {
    margin-bottom: 14px;
    padding: 16px 18px;
    border-radius: 16px;
    border: 1px solid #cfe2ff;
    background: linear-gradient(180deg, #f2f8ff 0%, #ffffff 100%);
    box-shadow: 0 10px 24px rgba(13, 110, 253, 0.08);
    text-align: left;
}

.attendance-info-top__kicker {
    margin-bottom: 8px;
    color: #0d6efd;
    font-weight: 800;
    letter-spacing: 0.06em;
    text-transform: uppercase;
    font-size: 0.95rem;
}

.attendance-info-top__body p:last-child {
    margin-bottom: 0;
}

.attendance-info-notice {
    margin-bottom: 0;
    padding: 16px 18px;
    border-radius: 16px;
    border: 1px solid #cde3ff;
    box-shadow: 0 10px 24px rgba(13, 110, 253, 0.08);
}

.attendance-info-notice p:last-child {
    margin-bottom: 0;
}

.attendance-action-area {
    margin-top: 26px;
}

.attendance-success-card {
    padding: 24px;
    border-radius: 18px;
    background: linear-gradient(135deg, #effaf2 0%, #ffffff 100%);
    border: 1px solid #ccebd7;
    box-shadow: 0 14px 28px rgba(40, 167, 69, 0.12);
}

.attendance-success-kicker {
    margin-bottom: 8px;
    color: #1f8b47;
    font-size: 1.2rem;
    font-weight: 700;
    letter-spacing: 0.08em;
    text-transform: uppercase;
}

.attendance-success-text {
    margin-bottom: 8px;
    color: #43617a;
}

.attendance-success-mode {
    margin: 0 0 18px;
    color: #0f5132;
    font-size: 2.2rem;
    font-weight: 800;
    letter-spacing: 0.05em;
}

.attendance-saham-block-alert {
    margin: 0 auto 16px;
    max-width: 520px;
    text-align: left;
    border-radius: 12px;
    font-size: 1.05rem;
    line-height: 1.5;
}

.attendance-pending-card {
    padding: 24px;
    border-radius: 18px;
    background: linear-gradient(135deg, #fffbeb 0%, #ffffff 100%);
    border: 1px solid #fde68a;
    box-shadow: 0 14px 28px rgba(180, 83, 9, 0.1);
}

.attendance-pending-kicker {
    margin-bottom: 10px;
    color: #b45309;
    font-size: 1.2rem;
    font-weight: 700;
    letter-spacing: 0.08em;
    text-transform: uppercase;
}

.attendance-pending-text {
    margin-bottom: 10px;
    color: #43617a;
    line-height: 1.55;
}

.attendance-pending-hint {
    margin-bottom: 18px;
    color: #6b7280;
    font-size: 0.95rem;
    line-height: 1.5;
}

.attendance-refresh-button {
    min-width: 180px;
    padding: 10px 20px;
    border-radius: 999px;
    font-weight: 700;
}

.attendance-submit-button,
.attendance-vote-button {
    min-width: 220px;
    padding: 12px 24px;
    border-radius: 999px;
    font-weight: 700;
    letter-spacing: 0.04em;
    box-shadow: 0 12px 24px rgba(35, 64, 97, 0.14);
}

.attendance-voting-notice {
    max-width: 520px;
    margin: 0 auto;
    border-radius: 14px;
}

.attendance-voting-notice__title {
    margin: 0 0 8px;
}

.attendance-voting-notice__body {
    margin: 0 0 10px;
    line-height: 1.55;
}

@media (max-width: 767px) {

    .attendance-hero,
    .attendance-card {
        padding: 18px;
        border-radius: 16px;
    }

    .attendance-info-grid {
        grid-template-columns: 1fr;
    }

    .attendance-submit-button,
    .attendance-vote-button,
    .attendance-refresh-button {
        width: 100%;
        min-width: 0;
    }
}
</style>


<script>
export default {
    data: function () {
        return {
            loading: false,
            userSubmitted: false, // Add a flag to track if the user has already submitted
            selectedKehadiran: '0',
            portalSettings: null,
        }
    },

    mounted: function () {
        if (this.data && this.data.user && this.data.user.kehadiran == 0) {
            var el = document.getElementById('kehadiran');
            if (el) this.selectedKehadiran = el.value || '0';
        }
        this.fetchPortalSettings();
    },

    computed: {
        etikaUrl: function () {
            var url = this.portalSettings && this.portalSettings.attendance_etika_url
                ? String(this.portalSettings.attendance_etika_url).trim()
                : '';
            if (url) return url;
            return 'https://drive.google.com/uc?export=download&id=1O5DVDIbGy-w0bejV6RqtJGIty-_5LJD8';
        },
        /**
         * Status 2 = pilihan raya sedang berjalan (butang SAYA TERIMA dibuka).
         */
        electionVotingActive: function () {
            var e = this.data && this.data.election;
            if (!e || e.status === undefined || e.status === null) return false;
            return Number(e.status) === 2;
        },

        /**
         * Maya (2) can vote once attendance is set. Fizikal (1) can proceed once verified timestamp exists.
         * (Backend now auto-verifies Fizikal on submit.)
         */
        canProceedToVote: function () {
            var u = this.data && this.data.user;
            if (!u || Number(u.kehadiran) === 0) return false;
            if (Number(u.kehadiran) !== 1) return true;
            return Boolean(u.fizikal_registration_verified_at);
        },

        /** Saham (RM) must be at least 500 to vote — same rule as home / vote pages. */
        canVoteBySaham: function () {
            var s = Number(this.data && this.data.user && this.data.user.saham);
            return !Number.isNaN(s) && s >= 500;
        },

        sahamVoteBlockedMessage: function () {
            return 'Undian tidak tersedia: jumlah saham anda mestilah sekurang-kurangnya RM 500.';
        }
    },

    methods: {
        fetchPortalSettings: async function () {
            try {
                this.util.setAuthorization();
                const res = await axios.get(config.API + "portal-settings");
                if (res && res.data && res.data.status === "success") {
                    this.portalSettings = res.data.data || null;
                }
            } catch (e) {
                // Non-critical — fall back to default URL.
            }
        },
        onPhysicalGateCodeInput: function (e) {
            var el = e.target;
            var upper = el.value.toUpperCase();
            if (el.value === upper) return;
            var start = el.selectionStart;
            var end = el.selectionEnd;
            el.value = upper;
            if (start != null && end != null) {
                el.setSelectionRange(start, end);
            }
        },

        reloadAttendanceState: function () {
            location.reload();
        },
        // refreshUser: function () {

        //     var vm = this;
        //     axios.get(config.API + 'voter/' + this.data.user.id)
        //         .then(response => {
        //             vm.data.user = response.data;
        //             console.log(response.data)
        //         })
        // },

        edit: function () {
            if (this.loading) return;

            const selectedValue = document.getElementById("kehadiran").value;
            if (selectedValue === "0") {
                this.util.notify(" Sila pilih jenis kehadiran anda sebelum meneruskan.", "error");
                return;
            }

            this.loading = true;
            var vm = this;
            this.util.notify('Adding Attendance', 'loading');

            axios.put(config.API + 'attendance/' + this.data.user.id, $('#edit_form').serialize())
                .then(response => {
                    $.notifyClose();
                    vm.loading = false;

                    if (vm.util.showResult(response, 'success')) {
                        location.reload();
                        if (vm.canVoteBySaham) {
                            vm.$router.push({ name: 'Vote' });
                        }
                    }
                })
                .catch(error => {
                    $.notifyClose();
                    vm.loading = false;
                    vm.util.showResult(error, 'error');
                });
        }

    }
}
</script>