<?= $this->extend("layout/main_layout"); ?>

<?= $this->section("content"); ?>
<main class="flex-1 p-6 overflow-auto"
      x-data="dailyEntry()">
    <div class="flex justify-between items-center mb-6">
        <div>
            <h1 class="text-2xl font-bold text-base-content tracking-tight">Daily Entry</h1>
            <p class="text-sm mt-1 opacity-70">Record daily QC test results</p>
        </div>
        <button @click="saveResults()"
                :disabled="saving || !canSave"
                class="btn btn-primary"
                :class="{ 'loading': saving }">
            <i class="fa-solid fa-save mr-2"></i>
            Save Results
        </button>
    </div>

    <!-- Filters -->
    <div class="bg-base-100 rounded-xl border border-base-300 shadow-sm p-4 mb-6">
        <div class="flex flex-wrap gap-4 items-end">
            <div class="form-control">
                <label class="label">
                    <span class="label-text font-medium">Date</span>
                </label>
                <input type="date"
                       x-model="date"
                       @change="fetchControls()"
                       :max="today"
                       class="input input-bordered input-sm w-40">
            </div>
            <div class="form-control">
                <label class="label">
                    <span class="label-text font-medium">Quick Date</span>
                </label>
                <div class="flex gap-2">
                    <button @click="setToday()" class="btn btn-sm btn-outline">Today</button>
                    <button @click="setYesterday()" class="btn btn-sm btn-outline">Yesterday</button>
                </div>
            </div>
            <div class="form-control">
                <label class="label">
                    <span class="label-text font-medium">Department</span>
                </label>
                <select x-model="deptId" @change="setDeptId(deptId)" class="select select-bordered select-sm w-48">
                    <option value="">All Departments</option>
                    <template x-if="departments">
                        <template x-for="dept in departments" :key="dept.deptId">
                            <option :value="dept.deptId" x-text="dept.deptName"></option>
                        </template>
                    </template>
                    <template x-if="!departments">
                        <option disabled>Loading...</option>
                    </template>
                </select>
            </div>
            <div class="form-control">
                <label class="label">
                    <span class="label-text font-medium">Control</span>
                </label>
                <select x-model="selectedControl"
                        @change="fetchTests()"
                        class="select select-bordered select-sm w-64">
                    <option value="">Select Control</option>
                    <template x-for="control in controls" :key="control.id">
                        <option :value="control.id" x-text="control.controlName + ' (Lot: ' + control.lot + ')'"></option>
                    </template>
                </select>
            </div>
        </div>
    </div>

    <!-- Loading State -->
    <div x-show="loading" class="flex justify-center py-12">
        <span class="loading loading-spinner loading-lg text-primary"></span>
    </div>

    <!-- Empty State -->
    <div x-show="!loading && selectedControl && tests.length === 0"
         class="bg-base-100 rounded-xl border border-base-300 shadow-sm p-12 text-center">
        <i class="fa-solid fa-flask text-4xl text-base-content/20 mb-3"></i>
        <p class="text-base-content/60">No tests configured for this control</p>
        <p class="text-sm text-base-content/40 mt-1">Add tests in the Control-Tests setup</p>
    </div>

    <!-- No Control Selected -->
    <div x-show="!loading && !selectedControl"
         class="bg-base-100 rounded-xl border border-base-300 shadow-sm p-12 text-center">
        <i class="fa-solid fa-clipboard-list text-4xl text-base-content/20 mb-3"></i>
        <p class="text-base-content/60">Select a control to view tests</p>
    </div>

    <!-- Tests Grid -->
    <div x-show="!loading && selectedControl && tests.length > 0"
         class="bg-base-100 rounded-xl border border-base-300 shadow-sm overflow-hidden">
        <div class="overflow-x-auto">
            <table class="table">
                <thead class="bg-base-200">
                    <tr>
                        <th>Test</th>
                        <th class="text-center">Mean ± 2SD</th>
                        <th class="w-40">Result</th>
                        <th class="w-56">Comment</th>
                        <th class="w-16">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <template x-for="test in tests" :key="test.testId">
                        <tr class="hover">
                            <td>
                                <div class="font-medium" x-text="test.testName"></div>
                                <div class="text-xs text-base-content/50" x-text="test.testUnit || ''"></div>
                            </td>
                            <td class="text-center">
                                <div class="font-mono text-sm">
                                    <span x-text="test.mean !== null ? test.mean : '-'"></span>
                                    <span class="text-base-content/40">±</span>
                                    <span x-text="test.sd !== null ? (2 * test.sd).toFixed(2) : '-'"></span>
                                </div>
                            </td>
                            <td>
                                <input type="number"
                                       step="0.01"
                                       :placeholder="'...'"
                                       class="input input-bordered input-sm w-full font-mono"
                                       :class="getInputClass(test, $el.value) + ' ' + (deletedResults.includes(test.testId) ? 'input-disabled' : '')"
                                       :disabled="deletedResults.includes(test.testId)"
                                       @input.debounce.300ms="updateResult(test.testId, $el.value)"
                                       :value="getResultValue(test.testId)">
                            </td>
                            <td>
                                <textarea
                                      :placeholder="'Optional comment...'"
                                      rows="1"
                                      class="textarea textarea-bordered textarea-xs w-full"
                                      :class="deletedResults.includes(test.testId) ? 'textarea-disabled' : ''"
                                      :disabled="deletedResults.includes(test.testId)"
                                      @input.debounce.300ms="updateComment(test.testId, $el.value)"
                                      :value="getComment(test.testId)"></textarea>
                            </td>
                            <td class="text-center">
                                <button type="button"
                                        @click="toggleDelete(test.testId)"
                                        class="btn btn-ghost btn-sm"
                                        :class="deletedResults.includes(test.testId) ? 'text-warning' : 'text-error'"
                                        :title="deletedResults.includes(test.testId) ? 'Restore' : 'Delete'">
                                    <i class="fa-solid" :class="deletedResults.includes(test.testId) ? 'fa-rotate-left' : 'fa-trash'"></i>
                                </button>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Summary -->
    <div x-show="hasChanges"
         class="mt-4 p-3 bg-info/10 rounded-lg border border-info/20 text-sm">
        <i class="fa-solid fa-info-circle mr-2"></i>
        <span x-text="changedCount"></span> test(s) with changes pending save
    </div>
</main>
<?= $this->endSection(); ?>

<?= $this->section("script"); ?>
<script>
document.addEventListener('alpine:init', () => {
    Alpine.data("dailyEntry", () => ({
        date: new Date().toISOString().split('T')[0],
        controls: [],
        selectedControl: null,
        tests: [],
        loading: false,
        saving: false,
        resultsData: {},
        commentsData: {},
        deletedResults: [],
        deptId: null,
        departments: null,

        init() {
            this.fetchDepartments();
            this.fetchControls();
            this.setupKeyboard();
        },

        async fetchDepartments() {
            try {
                const response = await fetch(`${BASEURL}api/master/depts`, {
                    method: "GET",
                    headers: { "Content-Type": "application/json" }
                });
                if (!response.ok) throw new Error("Failed to load departments");
                const json = await response.json();
                this.departments = json.data || [];
            } catch (e) {
                console.error('Failed to fetch departments:', e);
            }
        },

        get today() {
            return new Date().toISOString().split('T')[0];
        },

        
        setDeptId(id) {
            this.deptId = id;
            this.selectedControl = null;
            this.controls = [];
            this.tests = [];
            this.fetchControls();
        },

        async fetchControls() {
            try {
                const params = new URLSearchParams({ date: this.date });
                if (this.deptId) {
                    params.set('dept_id', this.deptId);
                }
                const response = await fetch(`${BASEURL}api/entry/controls?${params}`);
                const json = await response.json();
                this.controls = json.data || [];
                // Reset selected control if it's no longer in the list
                if (this.selectedControl && !this.controls.find(c => c.id === this.selectedControl)) {
                    this.selectedControl = null;
                    this.tests = [];
                }
            } catch (e) {
                console.error('Failed to fetch controls:', e);
            }
        },

        async fetchTests() {
            if (!this.selectedControl) {
                this.tests = [];
                this.resultsData = {};
                this.commentsData = {};
                return;
            }

            this.loading = true;
            try {
                const params = new URLSearchParams({
                    date: this.date,
                    control_id: this.selectedControl
                });
                const response = await fetch(`${BASEURL}api/entry/daily?${params}`);
                const json = await response.json();
                this.tests = json.data || [];

                // Initialize resultsData, commentsData, and deletedResults
                this.resultsData = {};
                this.commentsData = {};
                this.deletedResults = [];
                for (const test of this.tests) {
                    if (test.existingResult && test.existingResult.resValue !== null) {
                        this.resultsData[test.testId] = test.existingResult.resValue;
                    }
                    // Get comment from either the new comment field or existing result
                    const comment = test.comment || (test.existingResult && test.existingResult.resComment);
                    if (comment) {
                        this.commentsData[test.testId] = comment;
                    }
                }
            } catch (e) {
                console.error('Failed to fetch tests:', e);
                this.$dispatch('notify', { type: 'error', message: 'Failed to load tests' });
            } finally {
                this.loading = false;
            }
        },

        async saveResults() {
            if (!this.canSave) return;

            this.saving = true;
            try {
                const results = [];
                const deletedIds = [];

                for (const test of this.tests) {
                    // Check if this test is marked for deletion
                    if (this.deletedResults.includes(test.testId)) {
                        if (test.existingResult && test.existingResult.resultId) {
                            deletedIds.push(test.existingResult.resultId);
                        }
                        continue;
                    }

                    const value = this.resultsData[test.testId];
                    if (value !== undefined && value !== '') {
                        results.push({
                            controlId: test.controlId,
                            testId: test.testId,
                            value: parseFloat(value)
                        });
                    }
                }

                const response = await fetch(`${BASEURL}api/entry/daily`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        date: this.date,
                        results: results,
                        deletedIds: deletedIds
                    })
                });

                const json = await response.json();
                if (json.status === 'success') {
                    // Save comments for non-deleted tests
                    const savedIds = json.data.savedIds || [];
                    for (const item of savedIds) {
                        // Skip if this test is marked for deletion
                        if (this.deletedResults.includes(item.testId)) {
                            continue;
                        }
                        const comment = this.commentsData[item.testId];
                        if (comment) {
                            await this.saveComment(item.testId, this.date, comment);
                        }
                    }

                    // Show success notification
                    this.$dispatch('notify', { type: 'success', message: json.message });
                    // Refresh data
                    this.resultsData = {};
                    this.commentsData = {};
                    this.deletedResults = [];
                    await this.fetchTests();
                } else {
                    this.$dispatch('notify', { type: 'error', message: json.message || 'Failed to save' });
                }
            } catch (e) {
                console.error('Failed to save:', e);
                this.$dispatch('notify', { type: 'error', message: 'Failed to save results' });
            } finally {
                this.saving = false;
            }
        },

        async saveComment(testId, date, commentText) {
            try {
                const response = await fetch(`${BASEURL}api/entry/comment`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        testId: testId,
                        date: date,
                        comment: commentText
                    })
                });
                return response.json();
            } catch (e) {
                console.error('Failed to save comment:', e);
                return { status: 'error', message: e.message };
            }
        },

        getResultValue(testId) {
            // If marked for deletion, show empty
            if (this.deletedResults.includes(testId)) {
                return '';
            }
            // Return from resultsData if changed
            if (testId in this.resultsData) {
                return this.resultsData[testId];
            }
            // Return existing result from database
            const test = this.tests.find(t => t.testId === testId);
            if (test && test.existingResult && test.existingResult.resValue !== null) {
                return test.existingResult.resValue;
            }
            return '';
        },

        updateResult(testId, value) {
            if (value === '') {
                delete this.resultsData[testId];
            } else {
                this.resultsData[testId] = value;
            }
            // Remove from deletedResults if user enters a value
            if (value !== '' && this.deletedResults.includes(testId)) {
                this.deletedResults = this.deletedResults.filter(id => id !== testId);
            }
        },

        toggleDelete(testId) {
            const test = this.tests.find(t => t.testId === testId);
            const hasExistingResult = test && test.existingResult && test.existingResult.resValue !== null;
            const hasChanges = testId in this.resultsData || testId in this.commentsData;

            if (this.deletedResults.includes(testId)) {
                // Restore - remove from deleted list
                this.deletedResults = this.deletedResults.filter(id => id !== testId);
            } else {
                // Mark for deletion
                if (hasExistingResult || hasChanges) {
                    this.deletedResults.push(testId);
                    // Clear any pending changes for this test
                    delete this.resultsData[testId];
                }
            }
        },

        updateComment(testId, value) {
            if (value.trim() === '') {
                delete this.commentsData[testId];
            } else {
                this.commentsData[testId] = value;
            }
        },

        getComment(testId) {
            return this.commentsData[testId] || '';
        },

        getExpectedRange(mean, sd) {
            if (mean === null || sd === null) return 'N/A';
            const min = (mean - 2 * sd).toFixed(2);
            const max = (mean + 2 * sd).toFixed(2);
            return `${min} - ${max}`;
        },

        getValueClass(test, value) {
            if (test.mean === null || test.sd === null) return '';
            const num = parseFloat(value);
            const lower = test.mean - 2 * test.sd;
            const upper = test.mean + 2 * test.sd;
            if (num >= lower && num <= upper) return 'text-success';
            return 'text-error';
        },

        getInputClass(test, value) {
            if (value === '' || test.mean === null || test.sd === null) return '';
            const num = parseFloat(value);
            const lower = test.mean - 2 * test.sd;
            const upper = test.mean + 2 * test.sd;
            if (num >= lower && num <= upper) return 'input-success';
            return 'input-error';
        },

        get hasChanges() {
            return Object.keys(this.resultsData).length > 0 ||
                   Object.keys(this.commentsData).length > 0;
        },

        get changedCount() {
            return Object.keys(this.resultsData).length + Object.keys(this.commentsData).length;
        },

        get canSave() {
            return this.selectedControl && (
                Object.keys(this.resultsData).length > 0 ||
                Object.keys(this.commentsData).length > 0 ||
                this.deletedResults.length > 0
            ) && !this.saving;
        },

        setToday() {
            this.date = new Date().toISOString().split('T')[0];
        },

        setYesterday() {
            const yesterday = new Date();
            yesterday.setDate(yesterday.getDate() - 1);
            this.date = yesterday.toISOString().split('T')[0];
        },

        setupKeyboard() {
            document.addEventListener('keydown', (e) => {
                if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                    e.preventDefault();
                    if (this.canSave) {
                        this.saveResults();
                    }
                }
            });
        }
    }));
});
</script>
<?= $this->endSection(); ?>
