<?php
include "classes/app.class.php";
$db = new db();
$func = new functions();

// 1. INPUT PARAMETERS
$from_date = $_GET['from'] ?? date('Y-m-d H:i', strtotime('-22 hours'));
$to_date = $_GET['to'] ?? date('Y-m-d H:i', strtotime('+2 hours'));
$interval_min = (int) ($_GET['intervals'] ?? 60); // Ensure integer

$tank_ids = explode(",", $_GET['tanks']);
$report_data = [];

function calcVol($f, $tank, $dist)
{
    if (!$dist)
        return 0;
    $res = $f->calculate_horizontal_cylinder_volume(
        $tank['radius_mm'],
        ($tank['radius_mm'] * 2) - ($dist + $tank['add_to_distance']),
        $tank['length_mm']
    );
    return $res['fluid_volume_liters'];
}

foreach ($tank_ids as $id) {
    $t_res = $db->query("tanks", "SELECT * FROM tanks WHERE record_id = $id");
    $t = $t_res->fetch_assoc();

    $sql_graph = "SELECT *, 
                  FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(date_time_measured) / ($interval_min * 60)) * ($interval_min * 60)) as interval_time
                  FROM tank_level_log 
                  WHERE tank_id = $id 
                  AND date_time_measured BETWEEN '$from_date' AND '$to_date'
                  GROUP BY interval_time
                  ORDER BY interval_time ASC";

    $g_res = $db->query("tank_level_log", $sql_graph);
    $labels = [];
    $values = [];
    while ($row = $g_res->fetch_assoc()) {
        $labels[] = date("H:i", strtotime($row['interval_time']));
        $values[] = round(calcVol($func, $t, $row['distance']));
    }

    $start_log = $db->query("tank_level_log", "SELECT distance FROM tank_level_log WHERE tank_id=$id AND date_time_measured <= '$from_date' ORDER BY date_time_measured DESC LIMIT 1")->fetch_assoc();
    $end_log = $db->query("tank_level_log", "SELECT distance FROM tank_level_log WHERE tank_id=$id AND date_time_measured <= '$to_date' ORDER BY date_time_measured DESC LIMIT 1")->fetch_assoc();

    $start_v = calcVol($func, $t, $start_log['distance'] ?? null);
    $end_v = calcVol($func, $t, $end_log['distance'] ?? null);

    $report_data[] = [
        'id' => $id,
        'name' => $t['name'],
        'start' => $start_v,
        'end' => $end_v,
        'diff' => $end_v - $start_v,
        'max' => count($values) > 0 ? max($values) : 0,
        'min' => count($values) > 0 ? min($values) : 0,
        'labels' => $labels,
        'values' => $values
    ];
}
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<style>
    :root {
        --apple-blue: #007AFF;
        --apple-bg: #F5F5F7;
        --apple-grey: #8E8E93;
    }

    body {
        overflow: scroll;
        background-color: var(--apple-bg);
    }

    .header {
        background: #fff;
        padding: 20px 15px;
        border-bottom: 1px solid #D1D1D6;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .btn-pdf {
        background: var(--apple-blue);
        color: white;
        border: none;
        padding: 8px 16px;
        border-radius: 8px;
        font-weight: 600;
        cursor: pointer;
    }

    .container {
        padding: 15px;
        max-width: 900px;
        margin: auto;
    }

    .summary-card,
    .tank-card {
        background: #fff;
        border-radius: 20px;
        padding: 20px;
        margin-bottom: 25px;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);

        /* CRITICAL PDF FIX: Prevents card from splitting across pages */
        page-break-inside: avoid !important;
        break-inside: avoid !important;
    }

    .summary-card {
        page-break-after: always !important;
        break-after: always !important;
    }

    .summary-table {
        width: 100%;
        border-collapse: collapse;
    }

    .summary-table th {
        text-align: left;
        font-size: 11px;
        color: var(--apple-grey);
        text-transform: uppercase;
        padding-bottom: 10px;
    }

    .summary-table td {
        padding: 12px 0;
        border-top: 1px solid #F2F2F7;
        font-size: 14px;
        font-weight: 600;
    }

    .tank-card-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 15px;
    }

    .mini-stats {
        display: flex;
        gap: 15px;
        margin-bottom: 15px;
    }

    /* Force every Tank Card to take its own full page */
    .tank-card {
        page-break-after: always !important;
        break-after: always !important;
        page-break-inside: avoid !important;
    }

    /* Optional: Prevent a blank page at the very end */
    .tank-card:last-child {
        page-break-after: auto !important;
        break-after: auto !important;
    }

    .mini-stat-item {
        flex: 1;
        background: #F2F2F7;
        padding: 10px;
        border-radius: 12px;
    }

    .mini-stat-item small {
        display: block;
        font-size: 10px;
        color: var(--apple-grey);
        text-transform: uppercase;
    }

    .chart-box {
        height: 220px;
        width: 100%;
        position: relative;
        overflow: hidden;
    }

    .diff-pos {
        color: #34C759;
    }

    .diff-neg {
        color: #FF3B30;
    }

    CSS
    /* ... (previous root and header styles) ... */

    .summary-card,
    .tank-card {
        background: #fff;
        border-radius: 20px;
        padding: 20px;
        margin-bottom: 25px;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);

        /* REMOVED: page-break-after: always */

        /* KEEP THIS: It prevents the PDF from splitting a single graph in half */
        page-break-inside: avoid !important;
        break-inside: avoid !important;
        display: block;
    }

    .chart-box {
        height: 300px;
        /* Reduced height slightly since they are stacking */
        width: 100%;
        position: relative;
    }
</style>

<div id="report-content">
    <div class="header">
        <div>
            <h1 style="margin:0; font-size: 22px; font-weight:800;">Inventory Report</h1>
            <small style="color:var(--apple-grey)">
                <?php echo date("M j, H:i", strtotime($from_date)); ?> —
                <?php echo date("M j, H:i", strtotime($to_date)); ?>
                (<?php echo $interval_min; ?>m Intervals)
            </small>
        </div>
        <div class="no-pdf">
            <button class="btn-pdf" onclick="downloadPDF()">Download PDF</button>
            <a href="reports.php"
                style="margin-left:10px; text-decoration:none; color:var(--apple-blue); font-weight:600;">Close</a>
        </div>
    </div>

    <div class="container">
        <div class="summary-card">
            <h2 style="margin:0 0 15px 0; font-size: 17px;">Executive Summary</h2>
            <table class="summary-table">
                <thead>
                    <tr>
                        <th>Tank Name</th>
                        <th>Start (L)</th>
                        <th>End (L)</th>
                        <th style="text-align:right;">Net Change</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($report_data as $row):
                        $color = ($row['diff'] >= 0) ? 'diff-pos' : 'diff-neg'; ?>
                        <tr>
                            <td><?php echo $row['name']; ?></td>
                            <td><?php echo number_format($row['start']); ?></td>
                            <td><?php echo number_format($row['end']); ?></td>
                            <td style="text-align:right;" class="<?php echo $color; ?>">
                                <?php echo ($row['diff'] > 0 ? '+' : '') . number_format($row['diff']); ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <?php foreach ($report_data as $row): ?>
            <div class="tank-card">
                <div class="tank-card-header">
                    <h3 style="margin:0;"><?php echo $row['name']; ?></h3>
                    <span class="<?php echo ($row['diff'] >= 0) ? 'diff-pos' : 'diff-neg'; ?>" style="font-weight:700;">
                        <?php echo ($row['diff'] > 0 ? '+' : '') . number_format($row['diff']); ?> L
                    </span>
                </div>
                <div class="mini-stats">
                    <div class="mini-stat-item">
                        <small>Period High</small>
                        <span><?php echo number_format($row['max']); ?> L</span>
                    </div>
                    <div class="mini-stat-item">
                        <small>Period Low</small>
                        <span><?php echo number_format($row['min']); ?> L</span>
                    </div>
                </div>
                <div class="chart-box">
                    <canvas id="chart-<?php echo $row['id']; ?>"></canvas>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<script>
    function downloadPDF() {
        const element = document.getElementById('report-content');

        // Use a standard width for stacking
        element.style.width = "850px";

        const opt = {
            margin: [0.5, 0.5],
            filename: 'Inventory_Report_<?php echo date("Y-m-d"); ?>.pdf',
            image: { type: 'jpeg', quality: 0.98 },
            html2canvas: {
                scale: 2,
                useCORS: true,
                width: 850
            },
            jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' },
            pagebreak: {
                // 'avoid-all' is best for letting elements fall underneath each other
                mode: 'avoid-all'
            }
        };

        const noPdfElements = document.querySelectorAll('.no-pdf');
        noPdfElements.forEach(el => el.style.visibility = 'hidden');

        html2pdf().set(opt).from(element).save().then(() => {
            element.style.width = "";
            noPdfElements.forEach(el => el.style.visibility = 'visible');
        });
    }
    document.addEventListener('DOMContentLoaded', function () {
        const reportData = <?php echo json_encode($report_data); ?>;

        reportData.forEach(tank => {
            const ctx = document.getElementById('chart-' + tank.id).getContext('2d');
            const gradient = ctx.createLinearGradient(0, 0, 0, 200);
            gradient.addColorStop(0, 'rgba(0, 122, 255, 0.2)');
            gradient.addColorStop(1, 'rgba(0, 122, 255, 0)');

            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: tank.labels,
                    datasets: [{
                        data: tank.values,
                        borderColor: '#007AFF',
                        borderWidth: 2.5,
                        pointRadius: 2,
                        tension: 0.3,
                        fill: true,
                        backgroundColor: gradient
                    }]
                },
                options: {
                    responsive: true,
                    animation: false,
                    maintainAspectRatio: false,
                    plugins: { legend: { display: false } },
                    scales: {
                        x: {
                            grid: { display: false },
                            ticks: {
                                color: '#8E8E93',
                                font: { size: 8 },
                                maxRotation: 0,
                                autoSkip: true,
                                maxTicksLimit: 8
                            }
                        }
                    }
                }
            });
        });
    });
</script>