<?php
session_start();
if (!isset($_SESSION['username'])) {
    echo "<script>window.top.location.href='index.php';</script>"; // Redirect parent window to login page
    exit();
}

require('fpdf/fpdf.php');

// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "prodb";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Fetch sell_id from POST
$sell_id = isset($_POST['sell_id']) ? intval($_POST['sell_id']) : 0;

// Fetch data for the PDF
$sql = "
    SELECT 
        customer_table.cust_name, 
        customer_table.cust_company, 
        customer_table.cust_mobile, 
        customer_table.cust_email, 
        sell.pr_Name, 
        sell.quantity_sold, 
        sell.total_amount, 
        sell.payment_method, 
        sell.paid_amount, 
        (sell.total_amount - sell.paid_amount) AS outstanding_balance 
    FROM 
        customer_table 
    INNER JOIN 
        sell 
    ON 
        customer_table.customer_id = sell.customer_id 
    WHERE 
        sell.sell_id = $sell_id";

$result = $conn->query($sql);
$row = $result->fetch_assoc();

if (!$row) {
    die("No record found for sell_id: $sell_id");
}

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

// Header
$pdf->Cell(0, 10, 'Sales Record Details', 0, 1, 'C');
$pdf->Ln(10);

// Table Data
$pdf->SetFont('Arial', '', 12);
foreach ($row as $key => $value) {
    $pdf->Cell(50, 10, ucfirst(str_replace('_', ' ', $key)) . ':', 1);
    $pdf->Cell(100, 10, $value, 1);
    $pdf->Ln();
}

$pdf->Cell(50, 10, 'Date & Time:', 1);
$pdf->Cell(100, 10, date('Y-m-d H:i:s'), 1);

// Output PDF
$pdf->Output();

$conn->close();
?>
