@extends('user.layout.main')
@section('title', 'PeGas - Master Data')

@section('content')
<div class="container-fluid">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <div>
            <h1 class="h3 mb-0 text-gray-800">Master Data Penjualan</h1>
            <small class="text-muted">Total Data: <strong>{{ $data_penjualan->count() }}</strong> Hari</small>
        </div>
        <div>
            <button class="btn btn-sm btn-danger shadow-sm" onclick="confirmDeleteAll()"><i class="fas fa-trash-alt fa-sm mr-1"></i> Hapus Semua Data</button>
            <button class="btn btn-sm btn-outline-primary shadow-sm ml-2" data-toggle="modal" data-target="#createManualModal"><i class="fas fa-plus fa-sm mr-1"></i> Tambah Manual</button>
            <button class="btn btn-sm btn-success shadow-sm ml-2" data-toggle="modal" data-target="#importModal"><i class="fas fa-file-excel fa-sm mr-1"></i> Import Excel</button>
            <form action="{{ route('user.masterdata.siapkan') }}" method="POST" class="d-inline">
                @csrf
                <button type="submit" class="btn btn-sm btn-primary shadow-sm ml-2"><i class="fas fa-layer-group fa-sm mr-1"></i> Siapkan Prediksi</button>
            </form>
        </div>
    </div>

    @if(session('success'))
        <div id="swal-success" data-message="{{ session('success') }}"></div>
    @endif
    @if(session('error'))
        <div id="swal-error" data-message="{{ session('error') }}"></div>
    @endif

    <div class="card border-left-info shadow mb-4">
        <div class="card-body">
            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Penting:</div>
            <div class="text-gray-800 small">
                Data terbaru di sistem: <span class="badge badge-success px-3">{{ $last_data ? \Carbon\Carbon::parse($last_data->tanggal)->translatedFormat('d F Y') : 'Belum ada data' }}</span>
                <p class="mt-2 mb-1">1. Pastikan data diunggah minimal 1 tahun atau 365 hari</p>
                <p class="mt-2 mb-1">2. Pastikan data diunggah secara berurutan tanpa ada tanggal yang terlewati.</p>
                <p class="mb-1">3. Klik <strong>Siapkan Prediksi</strong> setiap kali Anda selesai memperbarui atau menambah data.</p>
                <p class="mb-0">4. Untuk <strong>Hari Minggu, Hari Libur, atau Hari yang tidak ada penjualan</strong>, harap tetap diisi dengan angka <strong>0</strong> agar urutan data tetap konsisten.</p>
            </div>
        </div>
    </div>

    <div class="card shadow mb-4">
        <div class="card-header py-3 bg-white">
            <h6 class="m-0 font-weight-bold text-primary">Daftar Penjualan Per Bulan</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover" id="dataTable-Master" width="100%" cellspacing="0">
                    <thead class="bg-light">
                        <tr>
                            <th width="50">No</th>
                            <th>Bulan & Tahun</th>
                            <th>Total Penjualan</th>
                            <th>Data Terisi</th>
                            <th class="text-center" width="150">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($data_per_bulan as $row)
                        <tr>
                            <td>{{ $loop->iteration }}</td>
                            <td data-order="{{ str_replace('-', '', $row->bulan_tahun) }}" class="font-weight-bold text-dark">
                                {{ \Carbon\Carbon::parse($row->bulan_tahun)->translatedFormat('F Y') }}
                            </td>
                            <td>{{ number_format($row->total_jumlah, 0, ',', '.') }} Tabung</td>
                            <td><span class="badge badge-info">{{ $row->jumlah_hari }} Hari</span></td>
                            <td class="text-center">
                                <button class="btn btn-info btn-sm btn-circle btn-show-bulan" 
                                    data-bulan="{{ $row->bulan_tahun }}" 
                                    data-nama="{{ \Carbon\Carbon::parse($row->bulan_tahun)->translatedFormat('F Y') }}">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <form action="{{ route('user.masterdata.destroy_bulan', $row->bulan_tahun) }}" method="POST" class="d-inline">
                                    @csrf @method('DELETE')
                                    <button type="button" class="btn btn-danger btn-sm btn-circle btn-delete-bulan"><i class="fas fa-trash"></i></button>
                                </form>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="card shadow mb-4">
        <div class="card-header py-3 bg-white border-0">
            <h6 class="m-0 font-weight-bold text-primary">Visualisasi Tren Penjualan (Data Historis)</h6>
        </div>
        <div class="card-body">
            <div style="position: relative; height: 320px; width: 100%;" id="chartWrapper">
                <canvas id="chartMasterData"></canvas>
            </div>
            <hr>
            <small class="text-muted"><i>Grafik menampilkan tren 30 data harian terakhir.</i></small>
        </div>
    </div>
</div>

<!-- Modal Detail Bulanan -->
<div class="modal fade" id="showBulanModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content rounded-0 border-0 shadow">
            <form id="formUpdateMassal" action="{{ route('user.masterdata.update_massal') }}" method="POST">
                @csrf
                <div class="modal-header bg-info text-white border-0 rounded-0">
                    <h5 class="modal-title" id="modalTitleBulan">Detail Penjualan</h5>
                    <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    <div id="alertUpdate" class="alert alert-warning small d-none">
                        <h6 class="font-weight-bold"><i class="fas fa-info-circle mr-2"></i> Petunjuk Perubahan:</h6>
                        <ul class="mb-0">
                            <li>Ubah angka pada kolom jumlah penjualan.</li>
                            <li>Klik tombol <strong>Update Perubahan</strong> untuk menyimpan.</li>
                        </ul>
                    </div>
                    <div class="row" id="detailContainer" style="max-height: 400px; overflow-y: auto;"></div>
                </div>
                <div class="modal-footer bg-light border-0 rounded-0">
                    <button type="button" class="btn btn-secondary btn-sm px-3" data-dismiss="modal">Kembali</button>
                    <button type="button" class="btn btn-info btn-sm px-3" id="btnEditMode">Edit Data</button>
                    <button type="submit" class="btn btn-primary btn-sm px-3 d-none" id="btnUpdateMassal">Update Perubahan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Tambah Manual -->
<div class="modal fade" id="createManualModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content rounded-0 border-0 shadow">
            <form action="{{ route('user.masterdata.store_bulan') }}" method="POST">
                @csrf
                <div class="modal-header bg-primary text-white border-0 rounded-0">
                    <h5 class="modal-title">Input Data Penjualan</h5>
                    <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group mb-4">
                        <label class="font-weight-bold small text-primary">Pilih Bulan & Tahun</label>
                        <input type="month" id="selectMonthYear" class="form-control rounded-0 shadow-sm" required>
                    </div>
                    <div id="dynamicInputSection" style="display: none;">
                        <div class="alert alert-info small rounded-0"><i class="fas fa-info-circle mr-2"></i> Isi angka 0 jika tidak ada penjualan. Seluruh baris tanggal wajib terisi.</div>
                        <div class="row" id="inputContainer" style="max-height: 400px; overflow-y: auto;"></div>
                    </div>
                </div>
                <!-- Perbaikan: Mengubah d-none menjadi style="display: none;" agar sinkron dengan jQuery .fadeIn() -->
                <div class="modal-footer border-0 rounded-0">
                    <button type="button" class="btn btn-light btn-sm" data-dismiss="modal">Batal</button>
                    <button type="submit" id="btnSubmit" class="btn btn-primary btn-sm px-4" style="display: none;">Simpan Data</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Import Excel -->
<div class="modal fade" id="importModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-0 border-0 shadow">
            <form action="{{ route('user.masterdata.import') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <div class="modal-header bg-success text-white border-0 rounded-0">
                    <h5 class="modal-title font-weight-bold">Import Data Excel</h5>
                    <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-warning small rounded-0 mb-3 shadow-sm">
                        <i class="fas fa-exclamation-triangle mr-2"></i> <strong>Penting:</strong> Pastikan kolom pada excel berisi <strong>tanggal_penjualan</strong> dan <strong>jumlah</strong>.
                    </div>

                    <div class="form-group mb-0">
                        <label class="small font-weight-bold">File Excel (.xlsx, .csv)</label>
                        <input type="file" name="file_excel" class="form-control rounded-0" required>
                    </div>
                </div>
                <div class="modal-footer border-0 rounded-0 bg-light">
                    <button type="button" class="btn btn-light btn-sm" data-dismiss="modal">Tutup</button>
                    <button type="submit" class="btn btn-success btn-sm px-4">Mulai Import</button>
                </div>
            </form>
        </div>
    </div>
</div>

<form id="deleteAllForm" action="{{ route('user.masterdata.deleteAll') }}" method="POST" class="d-none">@csrf @method('DELETE')</form>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    $(document).ready(function() {
        const errorFlashMessage = $('#swal-error').data('message');
        const successFlashMessage = $('#swal-success').data('message');

        if (errorFlashMessage) {
            Swal.fire({
                title: 'Gagal Proses Data!',
                text: errorFlashMessage,
                icon: 'warning',
                confirmButtonColor: '#e74a3b',
                confirmButtonText: 'Periksa Kembali'
            });
        }

        if (successFlashMessage) {
            Swal.fire({
                title: 'Berhasil!',
                text: successFlashMessage,
                icon: 'success',
                confirmButtonColor: '#1cc88a',
                confirmButtonText: 'Oke'
            });
        }

        if ($.fn.DataTable.isDataTable('#dataTable-Master')) {
            $('#dataTable-Master').DataTable().destroy();
        }

        const monthsArray = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"];
        const daysArray = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"];

        $('#dataTable-Master').DataTable({
            "order": [[1, "desc"]],
            "language": {
                "url": "//cdn.datatables.net/plug-ins/1.10.21/i18n/Indonesian.json"
            },
            "columnDefs": [
                { "type": "num", "targets": 1 }
            ]
        });

        let allData = @json($data_penjualan);
        allData.sort((a, b) => new Date(b.tanggal) - new Date(a.tanggal));

        const chartRaw = [...allData].slice(0, 30).reverse();
        const chartWrapper = document.getElementById('chartWrapper');

        if (chartRaw.length === 0) {
            chartWrapper.innerHTML = `
                <div class="d-flex flex-column align-items-center justify-content-center text-muted" style="height: 320px;">
                    <i class="fas fa-chart-line fa-3x mb-3" style="opacity: 0.2;"></i>
                    <p class="mb-1 font-weight-bold">Belum Ada Data</p>
                    <small>Tambahkan data penjualan untuk menampilkan grafik.</small>
                </div>
            `;
        } else {
            const ctx = document.getElementById('chartMasterData').getContext('2d');
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: chartRaw.map(i => {
                        const d = new Date(i.tanggal);
                        return d.getDate() + ' ' + monthsArray[d.getMonth()];
                    }),
                    datasets: [{
                        label: "Jumlah Terjual",
                        lineTension: 0.3,
                        backgroundColor: "rgba(78, 115, 223, 0.05)",
                        borderColor: "rgba(78, 115, 223, 1)",
                        pointRadius: 3,
                        pointBackgroundColor: "rgba(78, 115, 223, 1)",
                        pointBorderColor: "rgba(78, 115, 223, 1)",
                        data: chartRaw.map(i => parseInt(i.jumlah) || 0),
                    }],
                },
                options: {
                    maintainAspectRatio: false,
                    scales: {
                        x: { grid: { display: false } },
                        y: { 
                            beginAtZero: true,
                            ticks: {
                                precision: 0,
                                stepSize: 1,
                                callback: function(value) {
                                    if (Math.floor(value) === value) {
                                        return value + ' Tb';
                                    }
                                }
                            }
                        }
                    },
                    plugins: { legend: { display: false } }
                }
            });
        }

        $('.btn-show-bulan').on('click', function() {
            const bulanKey = $(this).data('bulan'); 
            const namaBulanFull = $(this).data('nama'); 
            
            const filtered = allData.filter(item => item.tanggal.substring(0, 7) === bulanKey);
            filtered.sort((a, b) => new Date(a.tanggal) - new Date(b.tanggal));

            $('#modalTitleBulan').text('Detail: ' + namaBulanFull);
            const container = $('#detailContainer').empty();
            $('#alertUpdate, #btnUpdateMassal').addClass('d-none');
            $('#btnEditMode').removeClass('d-none');

            filtered.forEach(item => {
                const d = new Date(item.tanggal);
                container.append(`
                    <div class="col-md-4 mb-3">
                        <div class="card border-left-info shadow-sm py-2 rounded-0">
                            <div class="card-body py-1 text-xs font-weight-bold text-info text-uppercase">
                                <span class="text-dark">${daysArray[d.getDay()]},</span> ${d.getDate()} ${monthsArray[d.getMonth()]}
                                <input type="hidden" name="ids[]" value="${item.id}">
                                <input type="number" name="jumlah[]" class="form-control form-control-sm mt-1 rounded-0 input-jumlah" 
                                    value="${item.jumlah}" disabled min="0">
                            </div>
                        </div>
                    </div>
                `);
            });
            $('#showBulanModal').modal('show');
        });

        $('#btnEditMode').on('click', function() {
            Swal.fire({
                title: 'Masuk Mode Edit?',
                text: "Anda dapat merubah angka penjualan pada bulan ini.",
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#36b9cc',
                confirmButtonText: 'Ya, Edit'
            }).then((result) => {
                if (result.isConfirmed) {
                    $('.input-jumlah').removeAttr('disabled').first().focus();
                    $('#alertUpdate, #btnUpdateMassal').removeClass('d-none');
                    $('#btnEditMode').addClass('d-none');
                }
            });
        });

        // Perbaikan JavaScript: Menampilkan form dinamis serta memastikan nilai kosong terisi 0
        $('#selectMonthYear').on('change', function() {
            const val = $(this).val(); if (!val) return;
            const splitVal = val.split('-');
            const year = parseInt(splitVal[0]), month = parseInt(splitVal[1]);
            const daysInMonth = new Date(year, month, 0).getDate();
            const container = $('#inputContainer').empty();
            
            // Memunculkan area input beserta tombol simpan secara bersamaan
            $('#dynamicInputSection').fadeIn();
            $('#btnSubmit').fadeIn();

            for (let d = 1; d <= daysInMonth; d++) {
                const dateObj = new Date(year, month - 1, d);
                const hari = daysArray[dateObj.getDay()];
                const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
                
                container.append(`
                    <div class="col-md-4 mb-3">
                        <div class="card border-left-primary shadow-sm py-2 rounded-0">
                            <div class="card-body py-1 text-xs font-weight-bold text-primary text-uppercase">
                                <span class="text-dark">${hari},</span> ${d} ${monthsArray[month-1]}
                                <input type="hidden" name="tanggal[]" value="${dateStr}">
                                <!-- Atribut required dilepas agar input kosong bisa melewati validasi awal HTML untuk diubah menjadi 0 -->
                                <input type="number" name="jumlah[]" class="form-control form-control-sm mt-1 rounded-0 input-manual-jumlah" min="0" value="0" placeholder="0">
                            </div>
                        </div>
                    </div>
                `);
            }
        });

        // Pengaman Sisi Klien: Otomatis mengubah teks kosong menjadi angka 0 saat kursor beralih sel
        $(document).on('blur', '.input-manual-jumlah', function() {
            if ($(this).val() === '' || $(this).val() < 0) {
                $(this).val(0);
            }
        });

        $('.btn-delete-bulan').on('click', function() {
            const form = $(this).closest('form');
            Swal.fire({
                title: 'Hapus data bulan ini?',
                text: "Seluruh data harian di bulan ini akan dihapus.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#e74a3b',
                confirmButtonText: 'Ya, Hapus!'
            }).then((result) => {
                if (result.isConfirmed) form.submit();
            });
        });

        $('#formUpdateMassal').on('submit', function(e) {
            e.preventDefault();
            Swal.fire({
                title: 'Simpan Perubahan?',
                icon: 'info',
                showCancelButton: true,
                confirmButtonColor: '#4e73df',
                confirmButtonText: 'Ya, Simpan'
            }).then((result) => {
                if (result.isConfirmed) this.submit();
            });
        });
    });

    function confirmDeleteAll() {
        Swal.fire({
            title: 'Hapus Semua Data?',
            text: "Seluruh data penjualan akan dihapus permanen.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#e74a3b',
            confirmButtonText: 'Ya, Hapus Semua!'
        }).then((result) => {
            if (result.isConfirmed) document.getElementById('deleteAllForm').submit();
        });
    }
</script>
@endpush
@endsection