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

if (isset($_GET['ref_no'])) {
    $ref_no = $_GET['ref_no'];
    
    // Fetch stock transfer details
    $sql = "SELECT st.*, p.name AS product_name 
            FROM stocktransfer st
            JOIN products p ON st.product_id = p.id 
            WHERE st.ref_no = ? AND p.business_id = 3"; // Filter by business_id
    $stmt = $conn->prepare($sql);
    $stmt->execute([$ref_no]);
    
    $total_amount = 0;
    $total_shipping = 0;
    
    if ($stmt->rowCount() > 0) {
        // Fetch FromBranch and ToBranch from the first record
        $first_record = $stmt->fetch();
        $fromBranch = htmlspecialchars($first_record['FromBranch']);
        $toBranch = htmlspecialchars($first_record['ToBranch']);
        
        // Reset the cursor to the start
        $stmt->execute([$ref_no]);

        echo '<table class="table">';
        
        // Separate header for From Branch and To Branch
        echo '<thead>
                <tr>
                    <th colspan="2"><strong>From Branch: </strong> ' .  $fromBranch .'</th>
                    <th colspan="2"><strong>To Branch: </strong> ' . $toBranch . '</th>
                </tr>
                <tr>
                    <th>Product Name</th>
                    <th>Quantity Transferred</th>
                    <th>Purchase Price</th>
                    <th>Amount</th>
                </tr>
              </thead>';
        echo '<tbody>';
        
        while ($detail = $stmt->fetch()) {
            $amount = $detail['QuantityTransferred'] * $detail['purchase_price'];
            $total_amount += $amount;
            $total_shipping = $detail['shipping_charges']; // Assuming shipping charge is same for the whole transfer
            
            echo '<tr>';

            echo '<td>' . htmlspecialchars($detail['product_name']) . '</td>';
            echo '<td>' . htmlspecialchars($detail['QuantityTransferred']) . '</td>';
            echo '<td>' . number_format($detail['purchase_price'], 2) . '</td>';
            echo '<td>' . number_format($amount, 2) . '</td>';
            echo '</tr>';
        }
        
        echo '</tbody>';
        echo '</table>';

        // Show total amounts and shipping charges
        echo '<div class="total-summary">';
        echo '<p><strong>Total Amount: </strong>' . number_format($total_amount, 2) . '</p>';
        echo '<p><strong>Shipping Charges: </strong>' . number_format($total_shipping, 2) . '</p>';
        echo '<p><strong>Grand Total: </strong>' . number_format($total_amount + $total_shipping, 2) . '</p>';
        echo '</div>';
        
    } else {
        echo '<p>No details found for this reference number.</p>';
    }
}
?>
