<?php
    // session_start();
    include "../db.php";
    require '../auth.php';
    restrictAccess(['Student']);
    date_default_timezone_set('Asia/Kolkata');
    $currentTime = date('M j, Y g:i a');

    if ( !isset($_SESSION['uid']) && !isset($_SESSION['uref']) && !isset($_SESSION['uref_code']) && !isset($_SESSION['uname']) && !isset($_SESSION['utype']) ) {
        header("Location: logout.php");
        exit();
    }
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php include "include/meta.php"; ?>
    <?php include "include/css.php"; ?>
    <?php include "include/php-functions.php"; ?>
    <script src="https://cdn.ckeditor.com/4.6.2/standard-all/ckeditor.js"></script>
</head>

<body>
    <!--  Header -->
    <?php include "include/header.php"; ?>
    <!-- #header -->

    <section id="inner-body">
        <div class="body-content">
            <div class="container-fluid">
                <div class="card mt-3 mb-3">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <div class="col-md-12 col-12 mt-2 mb-2">
                                <div class="row justify-content-between align-items-center">
                                    <div class="col-md-8 col-9 mb-2">
                                        <h4 class="text-gray-800 m-0">All Billing History</h4>
                                    </div>
                                    <div class="col-md-4 col-3 text-end">
                                        <a href="index.php" class="btn btn-warning text-white btn-sm"><i
                                                class="fa fa-arrow-left"></i> Back</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php
                            // Pagination setup
                            $limit = 10;
                            $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
                            $offset = ($page - 1) * $limit;

                            // Get filter values
                            $invoice_search = isset($_GET['invoice_search']) ? trim($_GET['invoice_search']) : '';
                            $student_search = isset($_GET['student_search']) ? trim($_GET['student_search']) : '';

                            $where = "WHERE (sb_type = 'Bill' OR sb_type = '') AND sb_for = '$_SESSION[uid]'";

                            // Filter by invoice
                            if (!empty($invoice_search)) {
                                $invoice_search_safe = mysqli_real_escape_string($con, $invoice_search);
                                $where .= " AND sb_invoice LIKE '%$invoice_search_safe%'";
                            }

                            // Filter by student name → get corresponding uid
                            if (!empty($student_search)) {
                                $student_search_safe = mysqli_real_escape_string($con, $student_search);
                                $uid_q = mysqli_query($con, "SELECT uid FROM users WHERE uname = '$student_search_safe'");
                                if ($uid_row = mysqli_fetch_assoc($uid_q)) {
                                    $student_uid = $uid_row['uid'];
                                    $where .= " AND sb_for = '$student_uid'";
                                } else {
                                    $where .= " AND 1=0"; // No match found
                                }
                            }

                            // Fetch filtered data
                            $sql = "SELECT * FROM student_bill $where ORDER BY sb_id DESC LIMIT $offset, $limit";
                            $result = mysqli_query($con, $sql);

                            // Total records for pagination
                            $total_sql = "SELECT COUNT(*) FROM student_bill $where";
                            $total_result = mysqli_query($con, $total_sql);
                            $total_row = mysqli_fetch_row($total_result);
                            $total_records = $total_row[0];
                            $total_pages = ceil($total_records / $limit);
                            ?>

                        <div class="row">
                            <!-- Search Form -->
                            <div class="col-md-12 mb-3">
                                <form method="get" action="all-bill.php">
                                    <div class="row g-2">
                                        <!-- Invoice Search -->
                                        <div class="col-md-10">
                                            <input type="text" list="FirstNo" name="invoice_search"
                                                class="form-control form-control-sm"
                                                placeholder="Search by Invoice Number"
                                                value="<?= htmlspecialchars($invoice_search) ?>">
                                            <datalist id="FirstNo">
                                                <?php
                                                $res = mysqli_query($con, "SELECT DISTINCT sb_invoice FROM student_bill WHERE sb_for = '$_SESSION[uid]' AND (sb_type = 'Bill' OR sb_type = '') ORDER BY sb_id ASC");
                                                while ($row = mysqli_fetch_assoc($res)) {
                                                    echo '<option value="' . $row['sb_invoice'] . '">';
                                                }
                                                ?>
                                            </datalist>
                                        </div>

                                        <!-- Submit -->
                                        <div class="col-md-2 d-flex">
                                            <button type="submit" class="btn btn-primary btn-sm w-100">Search</button>
                                            <a href="all-bill.php" class="btn btn-secondary btn-sm w-100">Reset</a>
                                        </div>
                                    </div>
                                </form>
                            </div>

                            <!-- Table -->
                            <?php if(mysqli_num_rows($result)>0){ ?>
                            <div class="col-md-12 table-responsive">
                                <table class="table table-bordered">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>Invoice</th>
                                            <th>Student Name</th>
                                            <th>Course</th>
                                            <th>Student</th>
                                            <th>Amount</th>
                                            <th>Date</th>
                                            <th>Bill By</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                            $i = $offset + 1;
                                            while ($row = mysqli_fetch_assoc($result)) {
                                                $client_id = $row['sb_for'];
                                                $student_name = '';
                                                $course = '';
                                                $college = '';
                                                $department = '';

                                                // Get student name
                                                $client_sql = mysqli_query($con, "SELECT uname FROM users WHERE uid = '$client_id'");
                                                if ($client_row = mysqli_fetch_assoc($client_sql)) {
                                                    $student_name = $client_row["uname"];
                                                }

                                                // Get course
                                                $product_sql = mysqli_query($con, "SELECT * FROM product WHERE pid = '{$row['sb_course']}'");
                                                if ($product_row = mysqli_fetch_assoc($product_sql)) {
                                                    $course_q = mysqli_query($con, "SELECT course_name FROM clg_course WHERE sl_no = '{$product_row["product"]}'");
                                                    if ($cr = mysqli_fetch_assoc($course_q)) {
                                                        $course = $cr['course_name'];
                                                    }
                                                }

                                                // Get college
                                                $college_sql = mysqli_query($con, "SELECT uname FROM users WHERE uid = '{$row['sb_college']}'");
                                                if ($college_row = mysqli_fetch_assoc($college_sql)) {
                                                    $college = $college_row['uname'];
                                                }

                                                // Get department
                                                $dept_sql = mysqli_query($con, "SELECT cat_name FROM clg_course_cat WHERE sl_no = '{$row['sb_dept']}'");
                                                if ($dept_row = mysqli_fetch_assoc($dept_sql)) {
                                                    $department = $dept_row['cat_name'];
                                                }

                                                // Get Bill By
                                                $sb_by = $row['sb_by'];
                                                if ($sb_by == 1) {
                                                    $bill_by = "Master Admin";
                                                } else {
                                                    $by_sql = mysqli_query($con, "SELECT uname, utype FROM users WHERE uid = '$sb_by'");
                                                    if ($by_row = mysqli_fetch_assoc($by_sql)) {
                                                        $bill_by = $by_row['uname'] . " (" . $by_row['utype'] . ")";
                                                    } else {
                                                        $bill_by = "Unknown";
                                                    }
                                                }
                                                
                                                // Get batch name
                                                $batch = "";
                                                $batch_sql = mysqli_query($con, "SELECT batch_title FROM branch WHERE b_id = '{$row['sb_batch']}'");
                                                if (mysqli_num_rows($batch_sql) > 0) {
                                                    $batch_row = mysqli_fetch_assoc($batch_sql);
                                                    $batch = $batch_row['batch_title'];
                                                }
                                            ?>
                                        <tr>
                                            <td><?= $i++ ?></td>
                                            <td><?= $row['sb_invoice'] ?></td>
                                            <td><?= $student_name ?></td>
                                            <td><?= $course . ' ( ' . $department . ' ) [ Batch: ' . $batch . ']' ?>
                                            </td>
                                            <td><?= $college ?></td>
                                            <td>₹<?= number_format($row['sb_amount'], 2) ?></td>
                                            <td><?= $row['sb_date'] ?></td>
                                            <td><?= $bill_by ?></td>
                                            <td>
                                                <?php if($row["sb_recycle"] != 0){?>
                                                <a href="print-bill.php?id=<?= $row['sb_id'] ?>"
                                                    class="btn btn-sm btn-success" target="_blank">
                                                    <i class="fa fa-print"></i> Print
                                                </a>
                                                <?php } else {?>
                                                <p class="btn btn-sm btn-warning my-2 disabled" disable>
                                                    Verification
                                                    Pending</p>
                                                <?php }?>
                                            </td>
                                        </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>

                                <!-- Pagination -->
                                <?php if ($total_pages > 1): ?>
                                <nav>
                                    <ul class="pagination">
                                        <?php for ($p = 1; $p <= $total_pages; $p++): ?>
                                        <li class="page-item <?= ($p == $page) ? 'active' : '' ?>">
                                            <a class="page-link"
                                                href="?page=<?= $p ?>&invoice_search=<?= urlencode($invoice_search) ?>&student_search=<?= urlencode($student_search) ?>">
                                                <?= $p ?>
                                            </a>
                                        </li>
                                        <?php endfor; ?>
                                    </ul>
                                </nav>
                                <?php endif; ?>
                            </div>
                            <?php } else{ echo "<div class='text-center'>No Data Found.</div>";}?>
                        </div>
                    </div>

                </div>
            </div>
        </div>

        <?php include "include/footer.php"; ?>
    </section>

    <!-- JavaScript Libraries -->

    <?php include "include/js.php"; ?>


</body>

</html>