<?php
session_start();
include 'php/db_connection.php';
require('pdf/fpdf.php');

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Get supplier ID from GET
$supplier_id = isset($_GET['supplier_id']) ? intval($_GET['supplier_id']) : 0;

// Fetch supplier info
$supplier = $con->query("SELECT * FROM suppliers WHERE id='$supplier_id'")->fetch_assoc();
if(!$supplier){
    die("Supplier not found");
}

// Fetch products of this supplier
$products = $con->query("
    SELECT pc.Product_id, p.name AS product_name, pc.purchase_price, p.price, p.Quantity
    FROM product_cat pc
    LEFT JOIN product p ON p.Product_id = pc.Product_id
    WHERE pc.supplier_id='$supplier_id'
");

// Initialize PDF
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(0,10,'Supplier Purchase Report',0,1,'C');
$pdf->Ln(5);

// Supplier Info
$pdf->SetFont('Arial','B',12);
$pdf->Cell(40,8,'Supplier Name: ',0,0);
$pdf->SetFont('Arial','',12);
$pdf->Cell(0,8,$supplier['name'],0,1);

$pdf->SetFont('Arial','B',12);
$pdf->Cell(40,8,'Mobile: ',0,0);
$pdf->SetFont('Arial','',12);
$pdf->Cell(0,8,$supplier['mobile'],0,1);

$pdf->SetFont('Arial','B',12);
$pdf->Cell(40,8,'Email: ',0,0);
$pdf->SetFont('Arial','',12);
$pdf->Cell(0,8,$supplier['email'],0,1);

$pdf->Ln(5);

// Table Header
$pdf->SetFont('Arial','B',12);
$pdf->SetFillColor(200,200,200);
$pdf->Cell(60,10,'Product Name',1,0,'C',true);
$pdf->Cell(30,10,'Quantity',1,0,'C',true);
$pdf->Cell(30,10,'Purchase Price',1,0,'C',true);
$pdf->Cell(30,10,'Sale Price',1,0,'C',true);
$pdf->Cell(40,10,'Total Bill',1,1,'C',true);

// Table Data
$pdf->SetFont('Arial','',12);
$total_bill = 0;

while($row = $products->fetch_assoc()){
    $purchase_total = $row['purchase_price'] * $row['Quantity'];
    $total_bill += $purchase_total;

    $pdf->Cell(60,10,$row['product_name'],1,0);
    $pdf->Cell(30,10,$row['Quantity'],1,0,'C');
    $pdf->Cell(30,10,number_format($row['purchase_price'],2),1,0,'R');
    $pdf->Cell(30,10,number_format($row['price'],2),1,0,'R');
    $pdf->Cell(40,10,number_format($purchase_total,2),1,1,'R');
}

// Total Bill
$pdf->SetFont('Arial','B',12);
$pdf->Cell(150,10,'Total Purchase Amount',1,0,'R',true);
$pdf->Cell(40,10,number_format($total_bill,2),1,1,'R',true);

// Output PDF
$pdf->Output('I','Supplier_'.$supplier['name'].'_Report.pdf');
?>