<?php
// Ensure no output is sent before headers
ob_start();
require('../lib/fpdf/fpdf.php'); // Ensure FPDF is installed and available

// Suppress warnings and notices
error_reporting(E_ERROR | E_PARSE);
ini_set('display_errors', 0);

// Retrieve POST data
$csv_file_name = $_POST['csv_file_name'];
$total = $_POST['total'];
$valid = $_POST['valid'];
$invalid = $_POST['invalid'];
$catchall = $_POST['catchall'];
$unknown = $_POST['unknown'];
$skipped = $_POST['skipped'];
$syntax_error = $_POST['syntax_error'];
$disposable = $_POST['disposable'];
$free_account = $_POST['free_account'];
$role_account = $_POST['role_account'];
$completed_time = $_POST['completed_time'];
$site_title = $_POST['site_title']; // Added
$footer_url = $_POST['s_url']; // Added

// Site details
$copyright = "© " . date("Y") . " $site_title";

// Create PDF
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 16);

// Title
$pdf->Cell(0, 10, "CSV Validation Report", 0, 1, 'C');
$pdf->Ln(5);

// File Details
$pdf->SetFont('Arial', '', 12);
$pdf->Cell(0, 10, "CSV File Name: $csv_file_name", 0, 1);
$pdf->Cell(0, 10, "Completion Time: $completed_time", 0, 1);
$pdf->Ln(5);

// Results Table
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(60, 10, "Category", 1);
$pdf->Cell(60, 10, "Count", 1);
$pdf->Cell(60, 10, "Percentage", 1);
$pdf->Ln();

$pdf->SetFont('Arial', '', 12);
$categories = [
    "Total" => $total,
    "Valid" => $valid,
    "Invalid" => $invalid,
    "Catch All" => $catchall,
    "Unknown" => $unknown,
    "Skipped" => $skipped,
    "Syntax Error" => $syntax_error,
    "Disposable" => $disposable,
    "Free Account" => $free_account,
    "Role Account" => $role_account,
];

$excludePercentage = ["Syntax Error", "Disposable", "Free Account", "Role Account"];

foreach ($categories as $category => $count) {
    $percentage = (!in_array($category, $excludePercentage) && $total > 0) ? round(($count / $total) * 100, 2) . "%" : "-";
    $pdf->Cell(60, 10, $category, 1);
    $pdf->Cell(60, 10, $count, 1);
    $pdf->Cell(60, 10, $percentage, 1);
    $pdf->Ln();
}

// Generate Pie Chart Dynamically
function generatePieChart($valid, $invalid, $catchall, $unknown, $skipped) {
    $total = $valid + $invalid + $catchall + $unknown + $skipped;
    $data = [
        'Valid' => $valid,
        'Invalid' => $invalid,
        'Catch All' => $catchall,
        'Unknown' => $unknown,
        'Skipped' => $skipped,
    ];

    $width = 300;
    $height = 300;
    $image = imagecreate($width, $height);
    $background = imagecolorallocate($image, 255, 255, 255); // White background

    // Predefine colors
    $colors = [
        'Valid' => imagecolorallocate($image, 198, 227, 119), // Light Green
        'Invalid' => imagecolorallocate($image, 241, 111, 111), // Red
        'Catch All' => imagecolorallocate($image, 117, 202, 195), // Teal
        'Unknown' => imagecolorallocate($image, 192, 192, 192), // Gray
        'Skipped' => imagecolorallocate($image, 255, 204, 102), // Orange
    ];

    $textColor = imagecolorallocate($image, 0, 0, 0); // Black for text
    $startAngle = 0;

    foreach ($data as $label => $value) {
        if ($value > 0) {
            $percentage = $total > 0 ? ($value / $total) * 360 : 0;
            $endAngle = $startAngle + $percentage;

            // Draw the pie segment
            imagefilledarc($image, $width / 2, $height / 2, $width - 20, $height - 20, $startAngle, $endAngle, $colors[$label], IMG_ARC_PIE);

            // Calculate label position
            $midAngle = deg2rad(($startAngle + $endAngle) / 2);
            $labelX = ($width / 2) + cos($midAngle) * ($width / 4);
            $labelY = ($height / 2) + sin($midAngle) * ($height / 4);

            // Add label
            $percentageText = round(($value / $total) * 100, 1) . '%';
            imagestring($image, 3, $labelX - 10, $labelY - 5, $percentageText, $textColor);

            $startAngle = $endAngle;
        }
    }

    $filePath = '../tmp/pie_chart.png';
    imagepng($image, $filePath);
    imagedestroy($image);

    return $filePath;
}

// Generate the pie chart and get the file path
$pieChartPath = generatePieChart($valid, $invalid, $catchall, $unknown, $skipped);

// Add the dynamically generated pie chart to the PDF
$pdf->Ln(10);
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(0, 10, "Pie Chart", 0, 1, 'C');
$pdf->Image($pieChartPath, 60, $pdf->GetY(), 90);

// Footer
$pdf->SetY(-30);
$pdf->SetFont('Arial', 'I', 10);
$pdf->Cell(0, 10, $footer_url, 0, 1, 'C');
$pdf->Cell(0, 10, $copyright, 0, 1, 'C');

// Output PDF as binary response
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="Validation_Report.pdf"');
ob_clean(); // Clear any output buffer to prevent corrupting the PDF
flush();    // Flush the system output buffer
$pdf->Output('I', 'Validation_Report.pdf');
exit; // Ensure no further output is sent
?>
