<?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;
    }

    /* ... (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)); ?> To
                <?php echo date("M j, H:i", strtotime($to_date)); ?>
            </small>
        </div>
        <div class="no-pdf">
            <a href="jev.elegantwork.co.za/temp/report.php?from=<?php echo $from_date; ?>&to=<?php echo $to_date; ?>&intervals=<?php echo $interval_min; ?>&tanks=<?php echo implode(",", $tank_ids); ?>"
                style="margin-left:10px; text-decoration:none; color:var(--apple-blue); font-weight:600;">OPEN REPORT</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/Current (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>
    </div>
</div>