<?php
include('top.php');

if (!isset($_GET['bill_id'])) {
    header("Location: index.php");
    exit();
}

$bill_id = mysqli_real_escape_string($con, $_GET['bill_id']);
$lineman_id = getLinemanId();

// Get bill details - modified to match the cbill table structure
$sql = "SELECT b.*,c.id as customerserial, c.name as customer_name, c.phone as customer_mobile, c.address, 
               c.houseno, c.custid as username, c.packname as package_name,c.landmark,
               c.packpr as package_charge, c.packpr_id as package_id,c.vc as customervc,
               c.pexpiry as expiry_date, c.packpr as package_price
        FROM cbill b
        JOIN adduser c ON b.bl_cid = c.id
        WHERE b.blid = $bill_id";

if ($lineman_id) {
   // $sql .= " AND b.bl_line = $lineman_id";
}

$result = mysqli_query($con, $sql);
$bill = mysqli_fetch_assoc($result);

// if (!$bill) {
//     $_SESSION['error'] = "Bill not found or you don't have permission to view it";
//     header("Location: list_bills.php");
//     exit();
// }

// Calculate GST (assuming 18% total - 9% CGST and 9% SGST)
$gst_rate = 0.09; // 9%


// Check if package_price from adduser is not set or is 0
// Check if package_price from adduser is not set or is 0
$package_price_value = trim($bill['package_price']);
//echo $package_price_value; 
if (empty($package_price_value) || $package_price_value == '0' || $package_price_value == '0.00' || (float)$package_price_value == 0.00) {
    // Extract base price from cbill.bill_amt (which includes 18% GST)
    $bill_amt = (float)$bill['bl_amt'];
    $package_charge = round($bill_amt / 1.18); // Extract base price by removing 18% GST
} else {
    $package_charge = (float)$bill['package_price'];
}

//echo $package_charge; exit;

$cgst = $package_charge * $gst_rate;
$sgst = $package_charge * $gst_rate;
$total_amount = $package_charge + $cgst + $sgst + (float)$bill['bl_prevdue'];

// Get company details - you'll need to create a company table or adjust this

//$company=f(q("SELECT * FROM tbl_company WHERE c_id='53'"));
$company = $_SESSION['company'];

?>

<!DOCTYPE html>
<html>
<head>
    <title>Tax Invoice - <?php echo $bill['bl_no']; ?></title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            font-size: 12px;
        }
        .container {
            width: 100%;
            max-width: 700px;
            margin: 0 auto;
            padding: 10px;
        }
        .header {
            text-align: center;
            margin-bottom: 5px;
        }
        .header h1 {
            font-size: 18px;
            margin: 2px 0;
            text-transform: uppercase;
        }
        .header p {
            margin: 1px 0;
            font-size: 12px;
        }
        .company-info {
            text-align: left;
            margin-bottom: 2px;
            line-height: 1;
        }
        .customer-info {
            margin-bottom: 2px;
        }
        .customer-info strong {
            display: block;
            font-size: 15px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 7px;
        }
        table th, table td {
            border: 1px solid #000;
            padding: 5px;
            text-align: left;
        }
        table th {
            background-color: #f0f0f0;
        }
        .text-right {
            text-align: right;
        }
        .total-row {
            font-weight: bold;
        }
        .payment-info {
            margin-top: 1px;
        }
        .payment-info table {
            margin-top: 2px;
        }
        .footer {
            margin-top: 20px;
            font-size: 12px;
            text-align: center;
        }
        .signature {
            margin-top: 30px;
            text-align: right;
            padding-right: 50px;
        }
        @media print {
            .no-print {
                display: none;
            }
            body {
                padding: 0;
                font-size: 11px;
            }
             td{
            font-size:11px;
            }
            .container {
                padding: 5px;
            }
        }
       
    </style>
    <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DynaPuff:wght@400..700&display=swap" rel="stylesheet">
<style>

.dynapuff-midbold {
  font-family: "DynaPuff", system-ui;
  font-optical-sizing: auto;
  font-weight: 700;
  font-style: normal;
  font-variation-settings:
    "wdth" 100;
}

</style>
</head>
<body>
    <div class="container">
        <div class="no-print" style="text-align: right; margin-bottom: 10px;">
            <button onclick="window.print()" style="padding: 5px 10px; cursor: pointer;">Print Bill</button>
        </div>

        <div class="header">
            <h1>TAX INVOICE</h1>
           
        </div>

        <div class="company-info">
            <!-- <img src="billlogo.jpg" style="width:200px;" /> -->
             <h1 class="dynapuff-midbold" style="font-size: 20px; margin: 0;text-transform:capitalize; "><?php echo $company['c_name']; ?></h1>
             <!-- <p>[ Digital Cable & High Speed Broadband Service Provider ]</p> -->
            <!-- <?php echo $company['c_name']; ?><br> -->
            <?php echo $company['c_address']; ?>, Mobile No : <?php echo $company['c_mobile']; ?><br>
<!-- if emailalt has value then print gstn -->
            <?php if (!empty($company['c_emailalt']) &&  ($company['c_emailalt'])): ?>
                <strong>GSTIN:</strong> <?php echo $company['c_emailalt']; ?><br>
            <?php endif; ?>
            
        </div>
        <table>
            <tr>
                <td>
                    <div class="customer-info">
                        <strong><?php echo $bill['customer_name']; ?></strong>
                        <?php echo $bill['houseno'] . ', ' . $bill['address']; ?><br>
                        Mobile No. <?php echo $bill['customer_mobile']; ?><br>
                        Customer ID: <?php echo $bill['username']; ?><br>
                        VC No: <?php echo $bill['customervc']; ?><br>
                    </div>
                </td>
                <td>
                    <strong>Invoice No : <?php echo $bill['bl_no']; ?></strong><br>
                    
                    <strong>Billing Period:</strong> <?php echo date('d-m-Y', strtotime($bill['bl_stdt'])); ?> to <?php echo date('d-m-Y', strtotime($bill['bl_expiry'])); ?><br>
                    <strong>Bill Date:</strong> <?php echo date('d-m-Y', strtotime($bill['bl_dt'])); ?><br>
                    <strong>Landmark:</strong> <?php echo $bill['landmark']; ?>
                </td>
            </tr>
        </table>
        <table>
            <tr>
                <td style="width:45%;">
                        <div>
                            <strong>Your account Summary</strong>
                            <table>
                                <tr>
                                    <td>Package Charge</td>
                                    <td class="text-right"><?php echo number_format($package_charge, 2); ?></td>
                                </tr>
                                <tr>
                                    <td>REBATE /DISCOUNT</td>
                                    <td class="text-right">0.00</td>
                                </tr>
                                <tr>
                                    <td>CGST @ 9 %</td>
                                    <td class="text-right"><?php echo number_format($cgst, 2); ?></td>
                                </tr>
                                <tr>
                                    <td>SGST @ 9 %</td>
                                    <td class="text-right"><?php echo number_format($sgst, 2); ?></td>
                                </tr>
                                <tr>
                                    <td>PREVIOUS DUES/ ADVANCES</td>
                                    <td class="text-right"><?php echo number_format($bill['bl_prevdue'], 2); ?></td>
                                </tr>
                                <tr class="total-row">
                                    <td><strong>TOTAL CHARGES (Rounded Off)</strong></td>
                                    <td class="text-right"><strong><?php echo number_format(round($total_amount), 2); ?></strong></td>
                                </tr>
                            </table>
                        </div>
                </td>
                <td  style="width:45%;vertical-align: top;">
                    <?php 
                            $fetchpack=mysqli_query($con,"SELECT * FROM tbl_change_package_details WHERE customer_id='$bill[customerserial]'");
                            while($packarr=mysqli_fetch_array($fetchpack)){

                                $getpack=f(q("SELECT * FROM tbl_pack WHERE pid='$packarr[pac_id]'"));
                                echo $getpack['pname'].' / ';

                            }
                    
                    ?>
                    <?php 
                    // Show a note if package price was calculated from bill_amt
                    if (empty($bill['package_price']) || (float)$bill['package_price'] == 0): 
                    ?>
                        <div style="font-size: 10px; margin-top: 10px; color: #666;">
                            * Package charge calculated from bill amount (incl. GST)
                        </div>
                    <?php endif; ?>
                </td>
            </tr>
        </table>
        

        <?php if ($bill['bl_stat'] == 1): ?>
        <div class="payment-info">
            <table>
                <tr>
                    <td>PAY DATE</td>
                    <td><?php echo date('d-M-y', strtotime($bill['bl_paydt'])); ?></td>
                    <td>AMOUNT PAID</td>
                    <td class="text-right"><?php echo number_format($bill['bl_payamt'], 2); ?></td>
                    <td>DISCOUNT</td>
                    <td class="text-right">0</td>
                    <td>DUE</td>
                    <td class="text-right"><?php echo number_format($bill['bl_due'], 2); ?></td>
                </tr>
            </table>
        </div>
        <?php endif; ?>
        <table>
            <tr>
                <td style="text-align:left;">
                    WORKING HOURS Friday to Wednesday 9 am to 1.30 pm & 4 pm to<br>
            7.30 pm, Thursday full close.
                </td>
                <td style="text-align:right;"><br><br><br>
                    Signature _______________________
                </td>
            </tr>
        </table>    
        <div class="footer">
            
        </div>

        <div class="signature" style="text-align:right;">
            
        </div>
    </div>
</body>
</html>