<?php
include "db.php";
include "header.php";
?>

<style>
/* ================= Wrapper ================= */
.charts-wrapper {
    width: calc(100vw - 250px - 30px);
    margin-left: 250px;
    margin-right: 30px;
    padding: 20px;
    position: relative;
    background: #f9f9f9;
}

/* ================= Titles ================= */
h2 {
    text-align: center;
    font-size: 32px;
    margin-bottom: 30px;
}

/* ================= Charts Rows ================= */
.charts-row {
    display: flex;
    gap: 30px;
    flex-wrap: wrap;
    margin-bottom: 40px;
}

/* ================= Chart Boxes ================= */
.chart-box {
    background: #fff;
    padding: 20px;
    border-radius: 15px;
    box-shadow: 0 4px 14px rgba(0,0,0,0.08);
    flex: 1 1 0;
    min-width: 0;
}

.chart-box h3 {
    font-size: 16px;
    margin-bottom: 10px;
    text-align: center;
}

canvas {
    width: 100% !important;
    height: auto !important;
}

/* ================= Tables ================= */
.table-responsive {
    overflow: auto;
}

#recipesTable th,
#recipesTable td,
#ingredientsTable th,
#ingredientsTable td {
    font-size: 14px;
    white-space: nowrap;
}

/* ================= Sidebar ================= */
.sidebar {
    width: 250px;
    flex: 0 0 250px;
    background: #fff;
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh;
    z-index: 1000;
    box-shadow: 2px 0 6px rgba(0,0,0,0.1);
    padding: 15px;
    overflow-y: auto;
}

/* ================= Responsive (χωρίς αλλαγή margins) ================= */
@media (max-width: 900px) {
    .chart-box {
        min-width: 100%;
    }
}

</style>

<div class="charts-wrapper">

    <h2><i class="bi bi-graph-up"></i> Στατιστικά</h2>

    <div class="text-center mb-4">
        <button id="downloadPdfBtn" class="btn btn-warning" disabled>
            <i class="bi bi-arrow-down-circle"></i> Εξαγωγή σε PDF
        </button>
    </div>

    <div id="chartsContainer">

        <!-- Line charts -->
        <div class="charts-row">
            <div class="chart-box">
                <h3>Ιστορικό Τιμών Υλικών</h3>
                <canvas id="ingredientChart" height="420"></canvas>
            </div>

            <div class="chart-box">
                <h3>Ιστορικό Κόστους Προϊόντων</h3>
                <canvas id="productChart" height="420"></canvas>
            </div>
        </div>

        <!-- Pie charts -->
        <div class="charts-row">
            <div class="chart-box">
                <h3>Συνολική Κατανάλωση Υλικών</h3>
                <canvas id="ingredientPie" height="420"></canvas>
            </div>

            <div class="chart-box">
                <h3>Συνολικό Κόστος Προϊόντων</h3>
                <canvas id="productPie" height="420"></canvas>
            </div>
        </div>

        <!-- Recipes table -->
        <div class="chart-box mt-4 recipes-table">
            <h3>Κόστος Συνταγών – Ιστορικό 12 Μηνών</h3>
            <div class="table-responsive">
                <table class="table table-bordered table-sm text-center" id="recipesTable">
                    <thead></thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>

        <!-- Ingredients table -->
        <div class="chart-box mt-4 recipes-table">
            <h3>Υλικά – Ιστορικό 12 Μηνών</h3>
            <div class="table-responsive">
                <table class="table table-bordered table-sm text-center" id="ingredientsTable">
                    <thead></thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>

    </div>
</div>

<!-- Libraries -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

<script>
let charts = {};

async function fetchData() {
    const res = await fetch("charts_data.php");
    const data = await res.json();

    /* ================= LINE CHARTS ================= */
    charts.ingredientChart = new Chart(document.getElementById('ingredientChart'), {
        type: 'line',
        data: {
            labels: data.months_12,
            datasets: data.ingredients.map(i => ({
                label: i.name,
                data: i.prices,
                borderColor: i.color,
                tension: 0.3
            }))
        },
        options: {
            responsive: true,
            plugins: { legend: { position: 'top' } },
            scales: { y: { title: { display: true, text: 'Τιμή (€)' } } }
        }
    });

    charts.productChart = new Chart(document.getElementById('productChart'), {
        type: 'line',
        data: {
            labels: data.months_12,
            datasets: data.products.map(p => ({
                label: p.name,
                data: p.costs,
                borderColor: p.color,
                tension: 0.3
            }))
        },
        options: {
            responsive: true,
            plugins: { legend: { position: 'top' } },
            scales: { y: { title: { display: true, text: 'Κόστος (€)' } } }
        }
    });

    /* ================= PIE CHARTS ================= */
    charts.ingredientPie = new Chart(document.getElementById('ingredientPie'), {
        type: 'pie',
        data: {
            labels: data.ingredients.map(i => i.name),
            datasets: [{
                data: data.ingredients.map(i => i.prices.at(-1) || 0),
                backgroundColor: data.ingredients.map(i => i.color)
            }]
        },
        options: { responsive: true }
    });

    charts.productPie = new Chart(document.getElementById('productPie'), {
        type: 'pie',
        data: {
            labels: data.products.map(p => p.name),
            datasets: [{
                data: data.products.map(p => p.costs.at(-1) || 0),
                backgroundColor: data.products.map(p => p.color)
            }]
        },
        options: { responsive: true }
    });

    /* ================= TABLES ================= */

    // Recipes table
    const recipesTable = document.getElementById('recipesTable');
    const recipesThead = recipesTable.querySelector('thead');
    const recipesTbody = recipesTable.querySelector('tbody');

    let recipesHeadHtml = '<tr><th>Συνταγή</th>';
    data.months_12.forEach(m => {
        const [y, mo] = m.split('-');
        recipesHeadHtml += `<th>${mo}/${y}</th>`;
    });
    recipesHeadHtml += `
        <th>Μ.Ο. 12μ</th>
        <th>Μ.Ο. 6μ</th>
        <th>Μ.Ο. 3μ</th>
        <th>Τελευταίος</th>
    </tr>`;
    recipesThead.innerHTML = recipesHeadHtml;

    let recipesBodyHtml = '';
    data.recipes_12m.forEach(r => {
        recipesBodyHtml += `<tr><td><strong>${r.name}</strong></td>`;
        r.months.forEach(c => {
            recipesBodyHtml += `<td>${c.toFixed(2)} €</td>`;
        });
        recipesBodyHtml += `
            <td class="fw-bold bg-light">${r.avg12.toFixed(2)} €</td>
            <td class="fw-bold bg-light">${r.avg6.toFixed(2)} €</td>
            <td class="fw-bold bg-warning">${r.avg3.toFixed(2)} €</td>
            <td class="fw-bold bg-success text-white">${r.last.toFixed(2)} €</td>
        </tr>`;
    });
    recipesTbody.innerHTML = recipesBodyHtml;

    // Ingredients table with first-value fill-forward
    const ingTable = document.getElementById('ingredientsTable');
    const ingThead = ingTable.querySelector('thead');
    const ingTbody = ingTable.querySelector('tbody');

    let ingHeadHtml = '<tr><th>Υλικό</th>';
    data.months_12.forEach(m => {
        const [y, mo] = m.split('-');
        ingHeadHtml += `<th>${mo}/${y}</th>`;
    });
    ingHeadHtml += `<th>Μ.Ο. 12μ</th><th>Μ.Ο. 6μ</th><th>Μ.Ο. 3μ</th><th>Τελευταίος</th></tr>`;
    ingThead.innerHTML = ingHeadHtml;

    let ingBodyHtml = '';
    data.ingredients.forEach(i => {
        const unitLabel = i.unit_name ? ` (${i.unit_name})` : '';
        ingBodyHtml += `<tr><td><strong>${i.name}${unitLabel}</strong></td>`;

        // Πρώτη μη μηδενική τιμή
        let firstVal = i.prices.find(p => p !== 0) || 0;
        let lastVal = firstVal;

        let filledPrices = i.prices.map(p => {
            if (p !== 0) lastVal = p;
            return lastVal;
        });

        filledPrices.forEach(p => {
            ingBodyHtml += `<td>${p.toFixed(2)} €</td>`;
        });

        const avg12 = filledPrices.reduce((a,b)=>a+b,0)/filledPrices.length;
        const avg6 = filledPrices.slice(-6).reduce((a,b)=>a+b,0)/6;
        const avg3 = filledPrices.slice(-3).reduce((a,b)=>a+b,0)/3;
        const last = filledPrices[filledPrices.length-1] || 0;

        ingBodyHtml += `<td class="fw-bold bg-light">${avg12.toFixed(2)} €</td>`;
        ingBodyHtml += `<td class="fw-bold bg-light">${avg6.toFixed(2)} €</td>`;
        ingBodyHtml += `<td class="fw-bold bg-warning">${avg3.toFixed(2)} €</td>`;
        ingBodyHtml += `<td class="fw-bold bg-success text-white">${last.toFixed(2)} €</td>`;
        ingBodyHtml += '</tr>';
    });
    ingTbody.innerHTML = ingBodyHtml;

    document.getElementById('downloadPdfBtn').disabled = false;
}

fetchData();

/* ================= PDF EXPORT ================= */
document.getElementById('downloadPdfBtn').addEventListener('click', async () => {
    const { jsPDF } = window.jspdf;
    const pdf = new jsPDF('p', 'mm', 'a4');

    pdf.setFontSize(16);
    pdf.text(
        "Cost & Prices Report",
        pdf.internal.pageSize.getWidth() / 2,
        12,
        null,
        null,
        'center'
    );

    const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
    const formattedDate = new Date().toLocaleDateString('en-US', options);

    pdf.setFontSize(11);
    pdf.text(
        `Date: ${formattedDate}`,
        pdf.internal.pageSize.getWidth() / 2,
        18,
        null,
        null,
        'center'
    );

    const container = document.getElementById('chartsContainer');
    const canvas = await html2canvas(container, {
        scale: 3,
        useCORS: true,
        windowWidth: 1900
    });
    const imgData = canvas.toDataURL('image/png');

    const pdfWidth = pdf.internal.pageSize.getWidth() - 20;
    const pdfHeight = (canvas.height * pdfWidth) / canvas.width;

    pdf.addImage(imgData, 'PNG', 10, 25, pdfWidth, pdfHeight);
    pdf.save(`Cost_Report_${formattedDate}.pdf`);
});
</script>

<?php include "footer.php"; ?>
