<?php
include "top.php";
session_start();
?>
<!DOCTYPE html>
<html>

<head>
    <?php include('include/head.php'); ?>
    <title>Cable Customer List</title>
    <link rel="stylesheet" type="text/css" href="src/plugins/datatables/media/css/jquery.dataTables.css">
    <link rel="stylesheet" type="text/css" href="src/plugins/datatables/media/css/dataTables.bootstrap4.css">
    <link rel="stylesheet" type="text/css" href="src/plugins/datatables/media/css/responsive.dataTables.css">
    <style>
        th,
        td {
            font-size: 11px;
        }

        .name {
            font-weight: bold;
        }

        .status.active {
            color: white;
            background: green;
            padding: 5px;
            border-radius: 3px;
        }

        .status.inactive {
            color: white;
            background: red;
            padding: 5px;
            border-radius: 3px;
        }

        .action-link.print {
            color: green;
            font-weight: bold;
        }

        .action-link.upload {
            color: red;
            font-weight: bold;
        }

        .bill-status {
            background: bisque;
            font-weight: bold;
        }

        .pagination a {
            color: black;
            padding: 8px 16px;
            text-decoration: none;
            border: 1px solid #000;
            margin: 0 2px;
        }

        .pagination a.active {
            background-color: #4CAF50;
            color: white;
            border: 1px solid #4CAF50;
        }

        .pagination a:hover:not(.active) {
            background-color: #ddd;
        }

        .address-col {
            max-width: 180px;
            width: 180px;
            white-space: normal !important;
            word-break: break-all;
            overflow-wrap: anywhere;
            word-wrap: break-word;
        }

        .expiry-col {
            max-width: 120px;
            width: 120px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    </style>
</head>

<body>
    <?php include('include/header.php'); ?>
    <?php include('include/sidebar.php');

    $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
    $page = isset($_REQUEST['page']) && is_numeric($_REQUEST['page']) ? (int) $_REQUEST['page'] : 1;
    $comid = mysqli_real_escape_string($con, $_SESSION['compids'] ?? '');
    $ltype = $_SESSION['lype'] ?? '';

    $limit = 50;
    $start_limit = ($page - 1) * $limit;

    if ($action === 'search') {
        $userdet = mysqli_real_escape_string($con, $_POST['userdet'] ?? '');
        $like_param = '%' . $userdet . '%';
        $query = "SELECT u.id, u.name, u.phone, u.custid, u.stb, u.vc, u.price, u.lpaydt, u.lpayamt, u.com_id, u.mso, u.area_id, u.actv, u.address, u.houseno,u.father_name,u.landmark,
                         a.arname, l.l_read, m.m_name, c.c_name, b.bl_month, b.bl_year,b.bl_expiry
                  FROM adduser u
                  LEFT JOIN tbl_area a ON a.arid = u.area_id
                  LEFT JOIN tbl_login l ON l.user_id = u.id
                  LEFT JOIN tbl_mso m ON m.m_id = u.mso
                  LEFT JOIN tbl_company c ON c.c_id = u.com_id
                  LEFT JOIN cbill b ON b.blid = (SELECT MAX(blid) FROM cbill WHERE bl_cid = u.id)
                  WHERE u.is_cable=1 AND u.actv=1" .
            ($ltype != '1' && $ltype != '2' ? " AND u.com_id='$comid'" : "") .
            " AND (u.name LIKE '$like_param' OR u.phone='$userdet' OR u.vc LIKE '$like_param' OR u.stb LIKE '$like_param' OR u.custid LIKE '$like_param' OR u.msoacno LIKE '$like_param' OR u.father_name LIKE '$like_param' OR u.landmark LIKE '$like_param')
                  LIMIT 20";
    } else {
        $query = "SELECT u.id, u.name, u.phone, u.custid, u.stb, u.vc, u.price, u.lpaydt, u.lpayamt, u.com_id, u.mso, u.area_id, u.actv, u.address, u.houseno,u.father_name,u.landmark,
                         a.arname, l.l_read, m.m_name, c.c_name, b.bl_month, b.bl_year,b.bl_expiry
                  FROM adduser u
                  LEFT JOIN tbl_area a ON a.arid = u.area_id
                  LEFT JOIN tbl_login l ON l.user_id = u.id
                  LEFT JOIN tbl_mso m ON m.m_id = u.mso
                  LEFT JOIN tbl_company c ON c.c_id = u.com_id
                  LEFT JOIN cbill b ON b.blid = (SELECT MAX(blid) FROM cbill WHERE bl_cid = u.id)
                  WHERE u.is_cable=1 AND u.actv=1" .
            ($ltype != '1' && $ltype != '2' ? " AND u.com_id='$comid'" : "") .
            " ORDER BY u.name LIMIT $start_limit, $limit";
    }
    $result = mysqli_query($con, $query) or die("Query failed: " . mysqli_error($con));
    ?>

    <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>Cable Customer</h4>
                            </div>
                            <nav aria-label="breadcrumb">
                                <ol class="breadcrumb">
                                    <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                                    <li class="breadcrumb-item active">Cable Customer</li>
                                </ol>
                            </nav>
                        </div>
                        <div class="col-md-6 col-sm-12 text-right">
                            <form action="cablecust.php?action=search" method="POST">
                                <div class="row">
                                    <div class="col-9">
                                        <input type="text" class="form-control" placeholder="User Search"
                                            name="userdet">
                                    </div>
                                    <div class="col-3">
                                        <button type="submit" class="btn btn-danger"><i
                                                class="fa fa-search"></i></button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <div class="pd-20 bg-white border-radius-4 box-shadow mb-30" style="overflow-x: auto; padding: 5%;">
                    <div class="clearfix mb-20">
                        <div class="pull-left">
                            <h5 class="text-blue">Cable Customer List</h5>
                        </div>
                        <div class="pull-right">
                            <a href="imexcel_siti.php" class="btn btn-success btn-sm"><i class="fa fa-upload"></i> Import SITI Subscriber</a>
                            <a href="imexcel_total.php" class="btn btn-info btn-sm ml-2"><i class="fa fa-upload"></i> Import Total Subscriber</a>
                            <a href="imexcel_hathway_9146.php" class="btn btn-warning btn-sm ml-2 text-white"><i class="fa fa-upload"></i> Import Hathway 9146</a>
                            <a href="imexcel_hathway_9407.php" class="btn btn-primary btn-sm ml-2"><i class="fa fa-upload"></i> Import Hathway 9407</a>
                        </div>
                    </div>
                    <div class="row">
                        <?php
                        if ($action !== 'search') {
                            if (!isset($_SESSION['total_cable_users'])) {
                                $count_query = "SELECT COUNT(*) AS total FROM adduser WHERE is_cable=1 AND actv=1";
                                $count_result = mysqli_query($con, $count_query) or die("Count query failed: " . mysqli_error($con));
                                $arrc = mysqli_fetch_assoc($count_result);
                                $_SESSION['total_cable_users'] = $arrc['total'];
                                mysqli_free_result($count_result);
                            }
                            $total_pages = ceil($_SESSION['total_cable_users'] / $limit);
                            $max_pages_to_show = 5;
                            $start_page = max(1, $page - floor($max_pages_to_show / 2));
                            $end_page = min($total_pages, $start_page + $max_pages_to_show - 1);
                            ?>
                                <div class="col-md-12 mb-20">
                                    <div class="card">
                                        <div class="card-body">
                                            <p class="pagination">
                                                <a href="cablecust.php?page=<?= $page == 1 ? 1 : $page - 1 ?>">«</a>
                                                <?php for ($i = $start_page; $i <= $end_page; $i++) { ?>
                                                        <a href="cablecust.php?page=<?= $i ?>" <?= $page == $i ? 'class="active"' : '' ?>><?= $i ?></a>
                                                <?php } ?>
                                                <a
                                                    href="cablecust.php?page=<?= $page == $total_pages ? $total_pages : $page + 1 ?>">»</a>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                        <?php } ?>
                        <table class="stripe data-table nowrap">
                            <thead>
                                <tr>
                                    <th class="table-plus datatable-nosort">Name</th>
                                    <!-- <th> Fathers Name</th> -->
                                    <th>Address</th>
                                    <th>Price</th>
                                    <th>Last Pay Dt. & Amt</th>
                                    <th>Expiry Dt</th>
                                    <th>Upload Documents</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($arr = mysqli_fetch_assoc($result)) {
                                    $custid = $arr['id'];
                                    $msoname = $arr['m_name'] ?? '';
                                    $billstat = '';
                                    $printcol = '';

                                    if ($arr['bl_month'] && $arr['bl_year']) {
                                        $checkstr = $arr['bl_month'] . ',' . $arr['bl_year'];
                                        $curstr = date('M') . ',' . date('Y');
                                        if ($curstr == $checkstr) {
                                            $printcol = 'style="background-color:bisque;"';
                                            $billstat = "<b>Bill Generate on $curstr</b>";
                                        }
                                    }

                                    $hnos = explode(" ", ltrim($arr['address']))[0] ?? '';
                                    if ($arr['houseno'] != $hnos) {
                                        $hnos_esc = mysqli_real_escape_string($con, $hnos);
                                        mysqli_query($con, "UPDATE adduser SET houseno='$hnos_esc' WHERE id='$custid'");
                                    }
                                    //calculate price inclusive 18% gst
                                    $nogstprice = $arr['price'];
                                    $gstamt = round($nogstprice * 0.18, 2);
                                    $withgstprice = number_format(round($nogstprice + $gstamt), 2);
                                    ?>
                                        <tr <?= $printcol ?>>
                                            <td class="table-plus">
                                                <span class="name"><?= $arr['name'] ?></span>
                                                <span
                                                    class="status <?= $arr['actv'] ? 'active' : 'inactive' ?>"><?= $arr['actv'] ? 'Active' : 'Deactive' ?></span>
                                                <div>Phone: <?= $arr['phone'] ?></div>
                                                <div>A/C No: <?= $arr['custid'] ?></div>

                                                <div>MSO: <?= $msoname ?></div>
                                                <div><span style="font-weight:bold;">Landmark:
                                                    </span><?php echo $arr['landmark'] ?></div>
                                                <div><span style="font-weight:bold;">Area Name:
                                                    </span><?php echo $arr['arname'] ?></div>
                                                <?= $billstat ? '<div class="bill-status">' . $billstat . '</div>' : '' ?>
                                            </td>
                                            <!-- <td><?php echo $arr['father_name'] ?></td> -->
                                            <td class="address-col"><?php echo $arr['address'] ?></td>
                                            <td><?= $withgstprice ?></td>
                                            <td><?= $arr['lpaydt'] ?> / ₹<?= $arr['lpayamt'] ?></td>
                                            <td class="expiry-col"><?= !empty($arr['bl_expiry']) ? $arr['bl_expiry'] : '-' ?>
                                            </td>
                                            <td>
                                                <a href="printdocs.php?custid=<?= $arr['id'] ?>" class="action-link print"
                                                    target="_blank">Print</a>
                                                <a href="uploaddocs.php?custid=<?= $arr['id'] ?>" class="action-link upload"
                                                    target="_blank">Upload</a>
                                            </td>
                                            <td>
                                                <?php if ($ltype == '1') { ?>
                                                        <a href="addcuser.php?action=edit&cid=<?= $arr['id'] ?>"
                                                            class="btn btn-sm btn-warning">Edit</a>
                                                        <a href="addcuser.php?action=delete&cid=<?= $arr['id'] ?>"
                                                            class="btn btn-sm btn-warning"
                                                            onclick="return confirm('Are you sure?')">Delete</a>
                                                <?php } ?>
                                                <a href="generatebill.php?custid=<?= $arr['id'] ?>"
                                                    class="btn btn-sm btn-primary">Generate Bill</a>
                                                <a href="customerchannels.php?custid=<?= $arr['id'] ?>"
                                                    class="btn btn-sm btn-warning">Add Channel</a>
                                                <a href="otherbills.php?custid=<?= $arr['id'] ?>"
                                                    class="btn btn-sm btn-success">Other Bills</a>
                                                <a href="new-ticket.php?custid=<?= $arr['custid'] ?>"
                                                    class="btn btn-sm btn-success">New Ticket</a>
                                                <a href="datecust.php?custid=<?= $arr['custid'] ?>" class="btn btn-sm btn-success"
                                                    target="_blank">Payment History</a>
                                                <a href="customer-payments.php?custpayid=<?= $arr['custid'] ?>"
                                                    class="btn btn-sm btn-warning" target="_blank">Add Payment</a>
                                                <form action="customer_bill_history_report.php" target="_blank" method="POST"
                                                    style="display:inline;">
                                                    <input type="hidden" name="search"
                                                        value="<?php echo htmlspecialchars($arr['custid']); ?>">
                                                    <button type="submit" class="btn btn-sm btn-danger">Bill History</button>
                                                </form>
                                            </td>
                                        </tr>
                                <?php }
                                mysqli_free_result($result);
                                ?>
                            </tbody>
                        </table><br>
                        <?php
                        if ($action !== 'search') {
                            ?>
                                <div class="col-md-12">
                                    <div class="card">
                                        <div class="card-body">
                                            <p class="pagination">
                                                <a href="cablecust.php?page=<?= $page == 1 ? 1 : $page - 1 ?>">«</a>
                                                <?php for ($i = $start_page; $i <= $end_page; $i++) { ?>
                                                        <a href="cablecust.php?page=<?= $i ?>" <?= $page == $i ? 'class="active"' : '' ?>><?= $i ?></a>
                                                <?php } ?>
                                                <a
                                                    href="cablecust.php?page=<?= $page == $total_pages ? $total_pages : $page + 1 ?>">»</a>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                        <?php } ?>
                    </div>
                </div>
            </div>
            <?php include('include/footer.php'); ?>
        </div>
    </div>
    <?php include('include/script.php'); ?>
    <script defer src="src/plugins/datatables/media/js/jquery.dataTables.min.js"></script>
    <script defer src="src/plugins/datatables/media/js/dataTables.bootstrap4.js"></script>
    <script defer src="src/plugins/datatables/media/js/dataTables.responsive.js"></script>
    <script defer src="src/plugins/datatables/media/js/responsive.bootstrap4.js"></script>
    <script>
        $(document).ready(function () {
            $('.data-table').DataTable({
                scrollCollapse: true,
                autoWidth: false,
                responsive: true,
                deferRender: true,
                paging: false,
                columnDefs: [{ targets: "datatable-nosort", orderable: false }],
                lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
                language: { info: "_START_-_END_ of _TOTAL_ entries", searchPlaceholder: "Search" }
            });
        });
    </script>
</body>

</html>