<?php
include 'includes/config.php';

if (isset($_GET['bill_id'])) {
    $bill_id = $_GET['bill_id'];

    $sql_bill_data = "SELECT p.id, p.amount, p.note, p.date, c.name as supplier_name, b.bank_name
        FROM bank_debit_amount p
        JOIN contacts c ON p.supplier_id = c.id
        JOIN banks b ON p.bank_id = b.id
        WHERE p.id = :bill_id
    ";

    $stmt = $conn->prepare($sql_bill_data);
    $stmt->bindParam(':bill_id', $bill_id);
    $stmt->execute();
    $bill = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($bill) {
        $supplier_name = $bill['supplier_name'];
        $amount = $bill['amount'];
        $note = $bill['note'];
        $date = $bill['date'];
        $bank_name = $bill['bank_name'];
    } else {
        // If no bill found
        echo "No payment found with that ID.";
        exit;
    }
} else {
    echo "Bill ID is required.";
    exit;
}

$stmt = $conn->query("SELECT * FROM companies ORDER BY id DESC LIMIT 1");
$company = $stmt->fetch(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bill Voucher</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        .bill-container {
            max-width: 400px;
            margin: 0 auto;
            border: 1px solid #000;
            padding: 20px;
            text-align: center;
        }
        .bill-container h1 {
            margin-bottom: 20px;
        }
        .bill-container p {
            font-size: 16px;
            line-height: 1.5;
        }
        .company-details {
            text-align: center;
            margin-bottom: 20px;
        }
        .company-details h2 {
            margin: 0;
        }
        .company-details p {
            margin: 2px;
        }
    </style>
</head>
<body>

<div class="company-details">
        <?php if (!empty($company['name'])): ?>
            <span><?= htmlspecialchars($company['name']) ?></span>
        <?php endif; ?>
    <p><!---Address: Lodhi Arcade 42 Ferozpur Road, Lahore--></p>
    <p></p>
</div>

<div class="bill-container">
    <h1>Payment Receipt</h1>
    <p><strong>Supplier:</strong> <?= htmlspecialchars($supplier_name) ?></p>
    <p><strong>Amount Paid:</strong> <?= number_format($amount, 2) ?> RS</p>
    <p><strong>Payment Date:</strong> <?= $date ?></p>
    <p><strong>Bank:</strong> <?= htmlspecialchars($bank_name) ?></p>
    <p><strong>Note:</strong> <?= htmlspecialchars($note) ?></p>
</div>

<script>
    window.onload = function() {
        window.print();
        setTimeout(function() {
            window.close(); 
        }, 1000); 
    };
</script>

</body>
</html>
