<?php
require('classes/fpdf.php');
require('classes/db.class.php');

$db = new db();
$db_2 = new db('fuel');

$where_data = str_replace('|', "'", $_POST['where_data']);

$total = 0;
$tot_odo = 0;
$tot_liters = 0;

$tot_consumption = 0;

$pdf = new FPDF();
$pdf->AliasNbPages();

$pdf->AddPage('p');

$pdf->Image('images/logo_1.png', 170, 5, 40);
// Arial bold 15
$pdf->SetFont('Arial', 'B', 8);
// Move to the right
$pdf->Cell(20);
$pdf->Cell(60, -4, '', 0, 1, 'C');
$pdf->Cell(-3);

$table_top = [50, 28, 16, 65, 30, 55, 30, 20, 25, 20, 20, 10];
// Title
$pdf->SetFont('Arial', 'B', 22);
$pdf->Cell($table_top[0], 30, 'CONSUMPTION REPORT', 0, 1, 'L');
$pdf->SetFont('Arial', 'B', 8);

$pdf->Cell(-2);
$pdf->Cell($table_top[3], 5, "ASSET", "LBR", 0, 'L');
$pdf->Cell($table_top[8], 5, "LITERS", "LBR", 0, 'L');
$pdf->Cell($table_top[7], 5, "ODO", "LBR", 0, 'l');
$pdf->Cell($table_top[8], 5, "CONSUMPTION", "LBR", 1, 'l');

$unq_data = $db_2->query('SELECT DISTINCT asset_id FROM fuel_movement WHERE ' . $where_data . ' ORDER BY asset_id DESC');

while ($row = $unq_data->fetch_assoc()) {

    $asset_id = $row['asset_id'];
    $asset_id = str_replace("1_", "", $asset_id);
    $asset_res = $db->exec_query('assets', ['*'], '', '', '', '', "record_id = $asset_id");
    $asset = $asset_res->fetch_assoc();

    if($asset['description'] == '') {
        $asset_desc = "MANUAL OVERRIDE";
    }else{
        $asset_desc = $asset['description'];
    }
    

    $amount_res = $db_2->query("SELECT SUM(amount) as total_amount FROM fuel_movement WHERE asset_id = '1_$asset_id' ");
    $amount = $amount_res->fetch_assoc();
    $liters_1 = $amount['total_amount'] / 1000;

    // LAST ODO
    $last_odo_res = $db_2->query("SELECT odo FROM fuel_movement WHERE asset_id = '1_$asset_id' ORDER BY record_id DESC LIMIT 1");
    $last_odo = $last_odo_res->fetch_assoc();
    $odo = $last_odo['odo'];

    // FIRST ODO 
    $first_odo_res = $db_2->query("SELECT odo FROM fuel_movement WHERE asset_id = '1_$asset_id' ORDER BY record_id ASC LIMIT 1");
    $first_odo = $first_odo_res->fetch_assoc();
    $first_odo = $first_odo['odo'];

    $odo = $odo - $first_odo;

    // NET ODO 
    if ($odo > 1 && $first_odo > 1) {
        $consumption = round($liters_1 / $odo,2);

    } else {
        $odo = 0;
        $consumption = 0;
    }

    $pdf->Cell(-2);
    $pdf->Cell($table_top[3], 6, $asset_desc, "LBR", 0, 'L');
    $pdf->Cell($table_top[8], 6, $liters_1 . " L", "LBR", 0, 'l');
    $pdf->Cell($table_top[7], 6, $odo, "LBR", 0, 'l');
    $pdf->Cell($table_top[8], 6, $consumption, "LB", 1, 'l');

}

$pdf->Output("I");