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

if (isset($_POST['ref_no'])) {
    $refNo = $_POST['ref_no'];

    // Query to get purchase details with color and size
    $query = "SELECT 
                p.product_id,
                pr.name AS ProductName,
                p.quantity,
                p.pp_without_discount,
                p.discount_percent,
                p.purchase_price,
                p.sell_price,
                p.Profit_margin,
                p.purchase_date,
                p.ref_no,
                p.fair_price,
                p.purchase_status,
                p.discount_amount,
                p.shipping_detail,
                p.shipping_charges,
                p.note,
                c.name AS SupplierName,
                c.city AS SupplierAddress,
                c.mobile AS SupplierMobile,
                p.discount_type,
                col.product_color AS ColorName,
                sz.product_size AS SizeName
              FROM purchase_lines p
              LEFT JOIN contacts c ON p.supplier_id = c.id
              LEFT JOIN products pr ON p.product_id = pr.id
              LEFT JOIN colors col ON p.color_id = col.id
              LEFT JOIN sizes sz ON p.size_id = sz.id
              WHERE p.ref_no = :ref_no";

    $stmt = $conn->prepare($query);
    $stmt->bindParam(':ref_no', $refNo);
    $stmt->execute();
    $details = $stmt->fetchAll();

    if (empty($details)) {
        echo 'No purchase details found for Reference No: ' . htmlspecialchars($refNo);
        exit;
    }

    // Payment details
    $paymentQuery = "SELECT 
                        bda.bank_id,
                        bda.date AS PaymentDate,
                        bda.amount AS PaymentAmount,
                        b.bank_name
                     FROM bank_debit_amount bda
                     LEFT JOIN banks b ON b.id = bda.bank_id
                     WHERE bda.ref_no = :ref_no";
    $paymentStmt = $conn->prepare($paymentQuery);
    $paymentStmt->bindValue(':ref_no', $refNo);
    $paymentStmt->execute();
    $payments = $paymentStmt->fetchAll();

    $subtotalBeforeTax = 0;
    $totalAfterTax = 0;
    $subtotal = 0;

    // Output purchase details
    $output = '<h5>Reference No: ' . htmlspecialchars($details[0]['ref_no']) . '</h5>';
    $output .= '<p>Date: ' . htmlspecialchars($details[0]['purchase_date']) . '</p>';
    $output .= '<p>Supplier: ' . htmlspecialchars($details[0]['SupplierName']) . '</p>';
    $output .= '<p>Address: ' . htmlspecialchars($details[0]['SupplierAddress']) . '</p>';
    $output .= '<p>Mobile: ' . htmlspecialchars($details[0]['SupplierMobile']) . '</p>';

    $output .= '<table class="table table-bordered">';
    $output .= '<thead>
                    <tr>
                        <th>#</th>
                        <th>Product Name</th>
                        <th>Color</th>
                        <th>Size</th>
                        <th>Purchase Quantity</th>
                        <th>Purchase Price</th>
                        <th>Shipping Cost</th>
                        <th>Profit Margin</th>
                        <th>Unit Selling Price</th>
                        <th>Subtotal</th>
                    </tr>
                </thead>';
    $output .= '<tbody>';

    foreach ($details as $index => $row) {
        $lineSubtotal = $row['purchase_price'] * $row['quantity'];
        $subtotal += $lineSubtotal;
        $output .= '<tr>';
        $output .= '<td>' . ($index + 1) . '</td>';
        $output .= '<td>' . (isset($row['ProductName']) ? htmlspecialchars($row['ProductName']) : 'No Name Found') . '</td>';
        $output .= '<td>' . (!empty($row['ColorName']) ? htmlspecialchars($row['ColorName']) : '-') . '</td>';
        $output .= '<td>' . (!empty($row['SizeName']) ? htmlspecialchars($row['SizeName']) : '-') . '</td>';
        $output .= '<td>' . number_format($row['quantity'], 2) . '</td>';
        $output .= '<td>' . number_format($row['pp_without_discount'], 2) . '</td>';
        $output .= '<td>' . number_format($row['fair_price'], 2) . '</td>';
        $output .= '<td>' . number_format($row['Profit_margin'], 2) . ' %</td>';
        $output .= '<td>' . number_format($row['sell_price'], 2) . '</td>';
        $output .= '<td>' . number_format($lineSubtotal, 2) . '</td>';
        $output .= '</tr>';

        $subtotalBeforeTax += $lineSubtotal;
        $totalAfterTax += $lineSubtotal;
    }

    // Discount
    $discountAmount = $details[0]['discount_amount'];
    $discountType = $details[0]['discount_type'];

    if ($discountType == 'Percentage') {
        $discountValue = ($subtotalBeforeTax * $discountAmount) / 100;
    } else {
        $discountValue = $discountAmount;
    }

    $totalAfterDiscount = $subtotalBeforeTax - $discountValue;
    $shippingCharges = $details[0]['shipping_charges'];
    $grandTotal = $totalAfterDiscount + $shippingCharges;

    $output .= '</tbody></table>';
    $output .= '<p><strong>Subtotal (Before Tax): </strong>' . number_format($subtotalBeforeTax, 2) . '</p>';
    $output .= '<p><strong>Discount (' . htmlspecialchars($discountType) . '): </strong>' . number_format($discountValue, 2) . '</p>';
    $output .= '<p><strong>Total After Discount: </strong>' . number_format($totalAfterDiscount, 2) . '</p>';
    $output .= '<p><strong>Shipping Charges: </strong>' . number_format($shippingCharges, 2) . '</p>';
    $output .= '<p><strong>Grand Total: </strong>' . number_format($grandTotal, 2) . '</p>';

    echo $output;
}
?>
