<?php 
include "top.php"; 
?>

<!DOCTYPE html>
<html>
<head>
    <?php include('include/head.php'); ?>
    <title>Generate Bills for Unpaid Customers</title>
    <link rel="stylesheet" type="text/css" href="https://sarmac.b-cdn.net/plugins/datatables/media/css/jquery.dataTables.css">
    <link rel="stylesheet" type="text/css" href="https://sarmac.b-cdn.net/plugins/datatables/media/css/dataTables.bootstrap4.css">
    <link rel="stylesheet" type="text/css" href="https://sarmac.b-cdn.net/plugins/datatables/media/css/responsive.dataTables.css">
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
</head>
<body>
    <?php include('include/header.php'); ?>
    <?php include('include/sidebar.php'); ?>

    <?php
    $action = $_REQUEST['action'] ?? '';
    $msg = '';
    
    if($action == 'generate') {
        $area_id = $_POST['area_id'];
        $mnth = $_POST['mnth'];
        $yrs = $_POST['yrs'];
        
        // Insert into tbl_server_bill to trigger batch processing
        $chk = f(q("SELECT * FROM tbl_server_bill WHERE m_month='$mnth' AND m_year='$yrs' AND m_area='$area_id'"));
        
        if($chk['m_month'] == '') {
            $setbill = mysqli_query($con,"INSERT INTO tbl_server_bill SET m_month='$mnth', m_year='$yrs', m_area='$area_id'");
            $msg = "<div class='alert alert-success'>Bill generation request received. Processing will complete shortly.</div>";
        } else {
            $msg = "<div class='alert alert-warning'>Bill generation request already received for this lineman and period.</div>";
        }
    }
    ?>

    <div class="main-container">
        <div class="pd-ltr-20 customscroll customscroll-10-p height-100-p xs-pd-20-10">
            <div class="min-height-200px">
                <div class="page-header">
                    <div class="row">
                        <div class="col-md-6 col-sm-12">
                            <div class="title">
                                <h4>Generate Bills for Unpaid Customers</h4>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="pd-20 bg-white border-radius-4 box-shadow mb-30">
                    <?php echo $msg; ?>
                    <form action="<?=$_SERVER['PHP_SELF']?>?action=generate" method="POST">
                        <div class="form-group row">
                            <div class="col-sm-12 col-md-4">
                                <label class="col-sm-12 col-md-12 col-form-label">Lineman</label>
                                <select name="area_id" class="form-control" required>
                                    <option value="">Select Lineman</option>
                                    <?php
                                    $sql = mysqli_query($con,"SELECT * FROM tbl_login WHERE l_type=2");
                                    while($row = mysqli_fetch_array($sql)) {
                                        echo "<option value='{$row['l_id']}'>{$row['l_name']}</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                            
                            <div class="col-sm-12 col-md-3">
                                <label class="col-sm-12 col-md-12 col-form-label">Month</label>
                                <select class="form-control" name="mnth" required>
                                   <option value="Jan" <? if(date('m')=='1'){?> selected <? } ?>>Jan</option>	
									<option value="Feb" <? if(date('m')=='2'){?> selected <? } ?>>Feb</option>	
									<option value="Mar" <? if(date('m')=='3'){?> selected <? } ?>>Mar</option>	
									<option value="Apr" <? if(date('m')=='4'){?> selected <? } ?>>Apr</option>	
									<option value="May" <? if(date('m')=='5'){?> selected <? } ?>>May</option>	
									<option value="Jun" <? if(date('m')=='6'){?> selected <? } ?>>Jun</option>	
									<option value="Jul" <? if(date('m')=='7'){?> selected <? } ?>>Jul</option>	
									<option value="Aug" <? if(date('m')=='8'){?> selected <? } ?>>Aug</option>	
									<option value="Sep" <? if(date('m')=='9'){?> selected <? } ?>>Sep</option>	
									<option value="Oct" <? if(date('m')=='10'){?> selected <? } ?>>Oct</option>	
									<option value="Nov" <? if(date('m')=='11'){?> selected <? } ?>>Nov</option>	
									<option value="Dec" <? if(date('m')=='12'){?> selected <? } ?>>Dec</option>	
                                </select>
                            </div>

                            <div class="col-sm-12 col-md-2">
                                <label class="col-sm-12 col-md-12 col-form-label">Year</label>
                                <select class="form-control" name="yrs" required>
                                    <?php
                                    for($i=2020; $i<=2030; $i++) {
                                        $selected = (date('Y') == $i) ? 'selected' : '';
                                        echo "<option value='$i' $selected>$i</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                            
                            <div class="col-sm-12 col-md-3">
                                <label class="col-sm-12 col-md-12 col-form-label">&nbsp;</label>
                                <button type="submit" class="btn btn-primary btn-block">Show Unpaid Customers</button>
                            </div>
                        </div>
                    </form>
                </div>

                <?php
                if(isset($_POST['area_id']) && isset($_POST['mnth']) && isset($_POST['yrs'])) {
                    $area_id = $_POST['area_id'];
                    $mnth = $_POST['mnth'];
                    $yrs = $_POST['yrs'];
                    
                    // Get customers without bills for this period
                    $query = "SELECT a.* 
                              FROM `adduser` a
                              LEFT JOIN `cbill` b ON a.id = b.bl_cid 
                                  AND b.bl_month = '$mnth' 
                                  AND b.bl_year = '$yrs'
                              WHERE b.bl_cid IS NULL
                              AND a.actv = 1
                              AND a.line_ids = '$area_id'";
                    
                    $customers = mysqli_query($con, $query);
                    $count = mysqli_num_rows($customers);
                ?>
                
                <div class="pd-20 bg-white border-radius-4 box-shadow mb-30">
                    <h5 class="mb-20">Unpaid Customers for <?php echo "$mnth $yrs"; ?></h5>
                    <p>Total Unpaid Customers: <?php echo $count; ?></p>
                    
                    <?php if($count > 0) { ?>
                    <form action="generate_bill_batch.php" method="POST" target="_blank">
                        <input type="hidden" name="area_id" value="<?php echo $area_id; ?>">
                        <input type="hidden" name="mnth" value="<?php echo $mnth; ?>">
                        <input type="hidden" name="yrs" value="<?php echo $yrs; ?>">
                        
                        <div class="table-responsive">
                            <table class="data-table table stripe hover nowrap">
                                <thead>
                                    <tr>
                                        <th>Customer ID</th>
                                        <th>Name</th>
                                        <th>Phone</th>
                                        <th>Address</th>
                                        <th>Package</th>
                                        <th>Price</th>
                                        <th>Previous Due</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    while($customer = mysqli_fetch_array($customers)) {
                                        $prevdue = $customer['prevdue'];
                                        $price = $customer['price'];
                                        $gst = round(floatval($price) * 0.18, 2);
                                        $total = round(floatval($price) + $gst, 2);
                                        
                                        echo "<tr>
                                            <td>{$customer['custid']}</td>
                                            <td>{$customer['name']}</td>
                                            <td>{$customer['phone']}</td>
                                            <td>{$customer['address']}</td>
                                            <td>{$customer['packname']}</td>
                                            <td>₹$total</td>
                                            <td>₹$prevdue</td>
                                        </tr>";
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <div class="text-right mt-3">
                            <button type="submit" class="btn btn-success">Generate Bills for All</button>
                        </div>
                    </form>
                    <?php } else { ?>
                    <div class="alert alert-info">No unpaid customers found for the selected criteria.</div>
                    <?php } ?>
                </div>
                <?php } ?>
            </div>
            <?php include('include/footer.php'); ?>
        </div>
    </div>

    <?php include('include/script.php'); ?>
    <script src="src/plugins/datatables/media/js/jquery.dataTables.min.js"></script>
    <script src="src/plugins/datatables/media/js/dataTables.bootstrap4.js"></script>
    <script src="src/plugins/datatables/media/js/dataTables.responsive.js"></script>
    <script src="src/plugins/datatables/media/js/responsive.bootstrap4.js"></script>
    
    <script>
        $('document').ready(function(){
            $('.data-table').DataTable({
                scrollCollapse: true,
                autoWidth: false,
                responsive: true,
                "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
                "language": {
                    "info": "_START_-_END_ of _TOTAL_ entries",
                    searchPlaceholder: "Search"
                },
            });
        });
    </script>
</body>
</html>