<?php
// Enable error reporting for debugging
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

define('FPDF_FONTPATH','font/');
require('fpdf.php'); 
require('fpdi.php'); 
include('../../config/config.php'); 


if (!isset($_GET['order_id'])) {
    die("Error: Order ID is required.");
}

$op_order_id = intval($_GET['order_id']);


// Define the PDF filename
$pdf_filename = "../report/Batch_Report_" . $op_order_id . ".pdf";

// Check if the PDF file exists
// if (file_exists($pdf_filename)) {
//     // Tell the browser that the content is a PDF
    
//      ob_clean();
//   header('Content-Type: application/pdf');
//     header('Content-Disposition: inline; filename="' . basename($pdf_filename) . '"');
//     header('Content-Length: ' . filesize($pdf_filename));
//     readfile($pdf_filename);
// } else {
    // File does not exist, so generate the PDF (assuming you have the generation code here)
    // Generate the PDF in memory and output it to the browser


// function distributeMaterialWeight($base_value, $num_rows, $run_row,$running_total) {
    
//     $total_material_value=$base_value*$num_rows;
    
//      $variation_limit = $base_value * ( 1/100);
//     // if ($num_rows == $run_row) {
//     //     return ($total_material_value - $running_total); // Last row gets remaining balance
//     // }

//     // Generate a random variation within allowed limit
//     $variation = rand(-$variation_limit, +$variation_limit);
//     $row_value = max(0, $base_value + $variation);
    
//     $final_weight=$row_value+$running_total;
    
//     if( $final_weight > $total_material_value && $num_rows==($run_row+1) )
//     {
//         $adj=$final_weight-$total_material_value;
//         $row_value=$row_value-$adj;
        
//     } elseif( $final_weight < $total_material_value && $num_rows==($run_row+1))
//     {
//         $adj=$total_material_value - $final_weight;
//         $row_value=$row_value+$adj;
//     }

    

 
//     return $row_value;
// }


//Check if the PDF file exists
if (file_exists($pdf_filename)) {
//     // Tell the browser that the content is a PDF
    
   ob_clean();
header('Content-Type: application/pdf');
  header('Content-Disposition: inline; filename="' . basename($pdf_filename) . '"');
  header('Content-Length: ' . filesize($pdf_filename));
   readfile($pdf_filename);
}
else{

function distributeMaterialWeight($base_value, $percent_variation = 1, $precision = 2) {
    
    
    // Convert percentage to float variation range
    if ($variation_limi > 100)
    {
    $variation_limit = $base_value * ($percent_variation / 100);
    }
    else
    {
       $variation_limit = $base_value * (5/100); 
    }

    // Use scaling to preserve decimals
    $scale = pow(10, $precision);

    // Apply variation as integer scaled values
    $min = ($base_value - $variation_limit) * $scale;
    $max = ($base_value + $variation_limit) * $scale;

    // Make sure we work with integers for mt_rand
    $random_scaled = mt_rand((int)$min, (int)$max);
    

    // Convert back to float
    return number_format($random_scaled / $scale, $precision);

}

// Fetch batch details
$stmt = $conn->prepare("SELECT r.id AS recipe_id,op.batch_date, op.batch_start_time, op.batch_end_time, op.batch_number, o.order_no, op.order_id,c.customer_name, o.site_name, r.recipe_name, v.reg_no AS truck_no,op.production_quantity,op.ordered_quantity, d.name AS driver_name, op.production_quantity, o.order_quantity_m3 FROM order_processing op JOIN orders o ON op.order_id = o.id JOIN customers c ON o.customer_id = c.id JOIN vehicles v ON op.truck_id = v.id JOIN drivers d ON op.driver_id = d.id JOIN recipes r ON op.recipe_id = r.id WHERE op.id = ?;");

if (!$stmt) {
    die("Error: SQL preparation failed. " . $conn->error);
}

$stmt->bind_param("i", $op_order_id);
$stmt->execute();
$result = $stmt->get_result();
$order = $result->fetch_assoc();
$stmt->close();

$order_id=$order['order_id'];

// Debugging Output
if (!$order) {
    echo "<pre>";
    echo "Debugging SQL Issue:\n";
    echo "Order ID: " . $order_id . "\n";

    // Check if order exists in `orders` table
    $result_orders = $conn->query("SELECT * FROM orders WHERE id = " . $order_id);
    if ($result_orders->num_rows == 0) {
        echo "ERROR: Order ID " . $order_id . " does not exist in the 'orders' table.\n";
    } else {
        echo "Order found in 'orders' table.\n";
    }

    // Check if order exists in `order_processing` table
    $result_processing = $conn->query("SELECT * FROM order_processing WHERE order_id = " . $order_id);
    if ($result_processing->num_rows == 0) {
        echo "ERROR: Order ID " . $order_id . " does not exist in the 'order_processing' table.\n";
    } else {
        echo "Order processing data found.\n";
    }

    die("\nError: Order ID " . $order_id . " not found in the database. Please check.");
}



$process_quantity = $order['production_quantity'];
$num_rows = ceil($process_quantity * 2); 

// Twice the processing quantity

// Fetch material values from the order table
$material_query = "SELECT `aggregate_12m_kg`, `aggregate_sand_kg`, `aggregate_20mm_1_kg`, 
                          `aggregate_20mm_2_kg`, `cement_cem1_kg`, `cement_cem2_kg`, 
                          `water_kg`, `admixture_admix1_kg`, `admixture_admix2_kg`,`process_qty`
                   FROM orders WHERE id = ?";
$stmt = $conn->prepare($material_query);
$stmt->bind_param("i", $order_id);
$stmt->execute();
$result_materials = $stmt->get_result();
$materials = $result_materials->fetch_assoc();
$stmt->close();


$b_date=$order['batch_date'];
$date = strtotime($b_date);
$b_date= date('d-M-Y', $date);


// Load Existing PDF Template
$pdf = new FPDI();
$pdf->AddPage();
$pdf->setSourceFile('../report/REPORT.pdf');
$template_id = $pdf->importPage(1);
$pdf->useTemplate($template_id, 0, 0, 210);

$pdf->Line(5, 125, 200, 125);

// Set Font (Same as REPORT.pdf)
$pdf->SetFont('Times', '', 11);

// Overlay Order Data on Template
$pdf->SetXY(35, 38);
$pdf->Cell(40, 10, $b_date);

$pdf->SetXY(35, 42);
$pdf->Cell(40, 10, date ('h:i A',strtotime($order['batch_start_time'])));

$pdf->SetXY(35, 46);
$pdf->Cell(40, 10, date ('h:i A',strtotime($order['batch_end_time'])));

$pdf->SetXY(58, 53);
$pdf->Cell(40, 10, $order['batch_number']);

$pdf->SetXY(58, 58);
$pdf->Cell(40, 10, strtoupper($order['customer_name']));

$pdf->SetXY(58, 63);
$pdf->Cell(40, 10, strtoupper($order['site_name']));

$pdf->SetXY(58, 68);
$pdf->Cell(40, 10, $order['recipe_id']);

$pdf->SetXY(58, 73);
$pdf->Cell(40, 10, $order['recipe_name']);

$pdf->SetXY(58, 79);
$pdf->Cell(40, 10, strtoupper($order['truck_no']));

$pdf->SetXY(58, 85);
$pdf->Cell(40, 10,  strtoupper($order['driver_name']));

$pdf->SetXY(58, 91);
$pdf->Cell(40, 10,  $order['order_no']);

$pdf->SetXY(58, 96);
$pdf->Cell(40, 10,  "Stetter");

$pdf->SetXY(180, 53);
$pdf->Cell(40, 10, $order['ordered_quantity']);


$pdf->SetXY(180, 58);
$pdf->Cell(40, 10, $order['production_quantity']);

$pdf->SetXY(180, 63);
$pdf->Cell(40, 10, "0.00");


$pdf->SetXY(180, 69);
$pdf->Cell(40, 10, $materials['process_qty']);

$pdf->SetXY(180, 74);
$pdf->Cell(40, 10, "0.50");


$pdf->SetXY(180, 79);
$pdf->Cell(40, 10, "0.50");


$pdf->Ln(5);

$t_aggregate_12m_kg=0;
$t_aggregate_sand_kg=0;
$t_aggregate_1m_kg=0;
$t_aggregate_2m_kg=0;
$t_cement_cem1_kg=0;
$t_cement_cem2_kg=0;
$t_water_kg=0;
$t_admixture_admix1_kg=0;
$t_admixture_admix2_kg=0;

$pdf->SetFont('Times', '', 10.5);

// Set initial Y position for writing material values
$YPos = 116;  // Adjust based on template positioning

 $pdf->SetXY(5, $YPos);
$pdf->Cell(40, 10,round( $materials['aggregate_12m_kg']));

$pdf->SetXY(15,$YPos);
$pdf->Cell(40, 10, round($materials['aggregate_sand_kg']));



$pdf->SetXY(35,$YPos);
$pdf->Cell(40, 10, round($materials['aggregate_20mm_1_kg']));

$pdf->SetXY(50,$YPos);
$pdf->Cell(40, 10, round( $materials['aggregate_20mm_2_kg']));

$pdf->SetXY(62,$YPos);
$pdf->Cell(40, 10,"0");

$pdf->SetXY(75,$YPos);
$pdf->Cell(40, 10, round($materials['cement_cem1_kg']));

$pdf->SetXY(90,$YPos);
$pdf->Cell(40, 10, round($materials['cement_cem2_kg']));

$pdf->SetXY(105,$YPos);
$pdf->Cell(40, 10, "0");

$pdf->SetXY(120,$YPos);
$pdf->Cell(40, 10, round($materials['water_kg']));




$pdf->SetXY(160,$YPos);
$pdf->Cell(40, 10,"0");



$pdf->SetXY(170,$YPos);
$pdf->Cell(40, 10, $materials['admixture_admix1_kg']);

$pdf->SetXY(185,$YPos);
$pdf->Cell(40, 10, $materials['admixture_admix2_kg']);

  $YPos =$YPos+15;


// Write material values in a single row, repeat rows based on process quantity
for ($i = 0; $i < $num_rows; $i++) 

{
    
 
// Calculate distributed material weights and other values
$aggregate12mWeight = round(distributeMaterialWeight($materials['aggregate_12m_kg']));
$aggregateSandWeight = round(distributeMaterialWeight($materials['aggregate_sand_kg']));
$aggregate20mm1Weight = round(distributeMaterialWeight($materials['aggregate_20mm_1_kg']));
$aggregate20mm2Weight = round(distributeMaterialWeight($materials['aggregate_20mm_2_kg']));
$cementCem1Weight = round(distributeMaterialWeight($materials['cement_cem1_kg']));
$cementCem2Weight = round(distributeMaterialWeight($materials['cement_cem2_kg']));
$waterKgWeight = round(distributeMaterialWeight($materials['water_kg']));
$admixtureAdmix1Weight = distributeMaterialWeight($materials['admixture_admix1_kg']);
$admixtureAdmix2Weight = distributeMaterialWeight($materials['admixture_admix2_kg']);


   $value = rand(-3, 3);
    
    if ($value > 0) {
        $display = '+' . $value;
    } elseif ($value < 0) {
        $display = ''.(string)$value;
    } else {
        $display = ' ' . $value; // Add space for alignment
    }


// Set X and Y positions and display values in cells
$pdf->SetXY(5, $YPos);
$pdf->Cell(40, 10, $aggregate12mWeight);

$pdf->SetXY(15, $YPos);
$pdf->Cell(40, 10, $aggregateSandWeight);

$pdf->SetXY(35, $YPos);
$pdf->Cell(40, 10, $aggregate20mm1Weight);

$pdf->SetXY(50, $YPos);
$pdf->Cell(40, 10, $aggregate20mm2Weight);

$pdf->SetXY(62, $YPos);
$pdf->Cell(40, 10, "0");

$pdf->SetXY(75, $YPos);
$pdf->Cell(40, 10, $cementCem1Weight);

$pdf->SetXY(90, $YPos);
$pdf->Cell(40, 10, $cementCem2Weight);

$pdf->SetXY(105, $YPos);
$pdf->Cell(40, 10, "0");

$pdf->SetXY(120, $YPos);
$pdf->Cell(40, 10, $waterKgWeight);

$pdf->SetXY(130, $YPos);
$pdf->Cell(40, 10, $display);

$pdf->SetXY(25, $YPos);
$pdf->Cell(40, 10, "0.0");

$pdf->SetXY(145, $YPos);
$pdf->Cell(40, 10, "0");

$pdf->SetXY(160, $YPos);
$pdf->Cell(40, 10, "0");

$pdf->SetXY(170, $YPos);
$pdf->Cell(40, 10, $admixtureAdmix1Weight);

$pdf->SetXY(185, $YPos);
$pdf->Cell(40, 10, $admixtureAdmix2Weight);



$YPos =$YPos+5;

$display="";
$t_aggregate_12m_kg=$t_aggregate_12m_kg+$aggregate12mWeight;
$t_aggregate_sand_kg=$t_aggregate_sand_kg+$aggregateSandWeight;
$t_aggregate_1m_kg=$t_aggregate_1m_kg+$aggregate20mm1Weight;
$t_aggregate_2m_kg=$t_aggregate_2m_kg+$aggregate20mm2Weight;
$t_cement_cem1_kg=$t_cement_cem1_kg+$cementCem1Weight;
$t_cement_cem2_kg=$t_cement_cem2_kg+$cementCem2Weight;
$t_water_kg=$t_water_kg+$waterKgWeight;
$t_admixture_admix1_kg=number_format($t_admixture_admix1_kg+$admixtureAdmix1Weight,2);
$t_admixture_admix2_kg=number_format($t_admixture_admix2_kg+$admixtureAdmix2Weight,2);
}

$pdf->Line();

$YPos =$YPos+5;


$pdf->Line(5, $YPos, 200, $YPos);

$pdf->SetXY(4,$YPos);
$pdf->Cell(40, 10, "Total Set Weight in Kgs:");

$YPos=$YPos+5;

  $pdf->SetXY(4, $YPos);
$pdf->Cell(40, 10,round($materials['aggregate_12m_kg']*$num_rows));

$pdf->SetXY(15,$YPos);
$pdf->Cell(40, 10, round($materials['aggregate_sand_kg']*$num_rows));



$pdf->SetXY(30,$YPos);
$pdf->Cell(40, 10, round($materials['aggregate_20mm_1_kg']*$num_rows));

$pdf->SetXY(45,$YPos);
$pdf->Cell(40, 10, round( $materials['aggregate_20mm_2_kg']*$num_rows));

$pdf->SetXY(62,$YPos);
$pdf->Cell(40, 10,"0");

$pdf->SetXY(75,$YPos);
$pdf->Cell(40, 10, round($materials['cement_cem1_kg']*$num_rows));

$pdf->SetXY(90,$YPos);
$pdf->Cell(40, 10, round($materials['cement_cem2_kg']*$num_rows));

$pdf->SetXY(105,$YPos);
$pdf->Cell(40, 10, "0");

$pdf->SetXY(120,$YPos);
$pdf->Cell(40, 10, round($materials['water_kg']*$num_rows));





$pdf->SetXY(160,$YPos);
$pdf->Cell(40, 10,"0");



$pdf->SetXY(170,$YPos);
$pdf->Cell(40, 10, number_format($materials['admixture_admix1_kg']*$num_rows),2);

$pdf->SetXY(185,$YPos);
$pdf->Cell(40, 10,number_format($materials['admixture_admix2_kg']*$num_rows),2);

//------------------------------------------------------------------------Actual---------


$YPos=$YPos+8;

$pdf->SetXY(4,$YPos);
$pdf->Cell(40, 10, "Total Actual in Kgs:");

$YPos=$YPos+5;

  $pdf->SetXY(4, $YPos);
$pdf->Cell(40, 10,round($t_aggregate_12m_kg));

$pdf->SetXY(15,$YPos);
$pdf->Cell(40, 10, round($t_aggregate_sand_kg));



$pdf->SetXY(30,$YPos);
$pdf->Cell(40, 10, round($t_aggregate_1m_kg));

$pdf->SetXY(45,$YPos);
$pdf->Cell(40, 10, round( $t_aggregate_2m_kg));

$pdf->SetXY(62,$YPos);
$pdf->Cell(40, 10,"0");

$pdf->SetXY(75,$YPos);
$pdf->Cell(40, 10, round($t_cement_cem1_kg));

$pdf->SetXY(90,$YPos);
$pdf->Cell(40, 10, round($t_cement_cem2_kg));

$pdf->SetXY(105,$YPos);
$pdf->Cell(40, 10, "0");

$pdf->SetXY(120,$YPos);
$pdf->Cell(40, 10, round($t_water_kg));






$pdf->SetXY(145,$YPos);
$pdf->Cell(40, 10,"0");



$pdf->SetXY(160,$YPos);
$pdf->Cell(40, 10,"0");



$pdf->SetXY(170,$YPos);
$pdf->Cell(40, 10, $t_admixture_admix1_kg);

$pdf->SetXY(185,$YPos);
$pdf->Cell(40, 10,$t_admixture_admix2_kg);


$YPos=$YPos+8;


$pdf->Line(5, $YPos, 200, $YPos);



// Save the generated PDF
$pdf_filename = "../report/Batch_Report_" . $op_order_id . ".pdf";
$pdf->Output($pdf_filename, "F");
 ob_clean();
 header('Content-Type: application/pdf');
     header('Content-Disposition: inline; filename="' . basename($pdf_filename) . '"');
    header('Content-Length: ' . filesize($pdf_filename));
    readfile($pdf_filename);
//}
// End output buffering and send output to the browser
ob_end_flush();
// Provide download link
//echo "Report generated successfully. <a href='$pdf_filename' download>Download Report</a>";
}
?>
