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

    if ( !isset($_SESSION['uid']) && !isset($_SESSION['uref']) && !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"; ?>
</head>
<style>
#ck-img-preview img {
    max-width: 100%;
    height: auto;
}
</style>

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

    <section id="inner-body">
        <div class="body-content">
            <div class="container-fluid">
                <?php if(isset($_GET["view_id"])){
                    $view_id = $_GET["view_id"];
                    $view_run = mysqli_query($con, "SELECT * FROM student_bill WHERE sb_type = 'Pay Out' AND sb_associate = '$_SESSION[uid]' AND sb_id = '$_GET[view_id]'");
                    
                    if($view_row = mysqli_fetch_assoc($view_run)){
                        // Get course name
                        $course = "";
                        $product_sql = mysqli_query($con, "SELECT * FROM product WHERE pid = '{$view_row['sb_course']}'");

                        if(mysqli_num_rows($product_sql) > 0){
                            $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 = "";
                        $college_sql = mysqli_query($con, "SELECT uname FROM users WHERE uid = '{$view_row['sb_college']}'");

                        if (mysqli_num_rows($college_sql) > 0) {
                            $college_row = mysqli_fetch_assoc($college_sql);
                            $college = $college_row['uname'];
                        }

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

                        // Get Student
                        $student = "";
                        $student_sql = mysqli_query($con, "SELECT uname FROM users WHERE uid = '{$view_row['sb_associate']}'");

                        if (mysqli_num_rows($student_sql) > 0) {
                            $student_row = mysqli_fetch_assoc($student_sql);
                            $student = $student_row['uname'];
                        }
                    ?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">
                        Detailed Payout of <?php echo $view_row["sb_date"];?></h5>
                    <div class="card-body">
                        <div class="notice-preiew">
                            <p class="m-0"><strong>Student Name:</strong> <?= $student;?></p>
                            <p class="m-0"><strong>Payout Amount : </strong><?php echo $view_row["sb_amount"];?> <i
                                    class="fa fa-inr"></i></p>
                            <p class="m-0"><strong>Payout Slip : </strong><?php echo $view_row["sb_invoice"];?></p>
                            <p class="m-0"><strong>College: </strong> <?= $college?></p>
                            <p class="m-0"><strong>Course: </strong> <?= $course?></p>
                            <p class="m-0"><strong>Department: </strong> <?= $department?></p>
                            <div id="ck-img-preview"><strong>Payout Details :
                                </strong><?php echo $view_row["sb_description"];?>
                            </div>
                            <p><strong>Payout Date : </strong><?php echo $view_row["sb_date"];?></p>
                        </div>

                        <a href="payout-history.php" class="btn btn-warning btn-sm text-white"> <i
                                class="fa fa-arrow-left"></i>
                            Back
                        </a>
                    </div>
                </div>
                <?php }
                }  else{?>
                <div class="card mt-3 mb-3">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <h4 class="text-gray-800">Payment History</h4>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php if(isset($_GET["kallol"])){?>
                        <ul class="mt-3" style="list-style:none;padding:0;">
                            <?php
                                $payment_sql = "SELECT * FROM payment_history WHERE ph_for = '{$_SESSION["uid"]}' AND ph_recycle = '1' ORDER BY phid DESC";
                                $payment_run = mysqli_query($con, $payment_sql);

                                if ($payment_run) {
                                    if (mysqli_num_rows($payment_run) > 0) {
                                        while ($payment_rows = mysqli_fetch_assoc($payment_run)) {
                            ?>
                            <li class="mb-2">
                                <a href="payout-history.php?view_id=<?php echo $payment_rows['phid']; ?>"
                                    style="text-decoration:none;">
                                    <div class="blog-preview">
                                        <h4 class="m-0">
                                            <i class="fa fa-inr"></i> <?php echo $payment_rows['ph_amount']; ?>
                                        </h4>
                                        <p class="m-0">
                                            <i class="fa fa-calendar"></i> <?php echo $payment_rows['ph_upDate']; ?>
                                        </p>
                                        <p class="m-0">
                                            <?php echo $payment_rows['ph_des']; ?>
                                        </p>
                                    </div>
                                </a>
                            </li>
                            <?php
                                        }
                                    } else {
                                        echo "<li>No payments Yet.</li>";
                                    }
                                } else {
                                    echo "<li>Error fetching payments.</li>";
                                }
                            ?>
                        </ul>
                        <?php }?>
                        <?php
                        // Pagination setup
                        $limit = 10;
                        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
                        $offset = ($page - 1) * $limit;

                        // Search filter
                        $search = isset($_GET['search']) ? mysqli_real_escape_string($con, $_GET['search']) : '';

                        $where = "";
                        if (!empty($search)) {
                            $search = mysqli_real_escape_string($con, $search);
                            $where = "AND (sb_invoice LIKE '%$search%' OR sb_course IN (
                                SELECT sl_no FROM clg_course WHERE course_name LIKE '%$search%'
                            ))";
                        }

                        // Fetch bills with optional search
                        $sql = "SELECT * FROM student_bill WHERE sb_type = 'Pay Out' AND sb_associate = '$_SESSION[uid]' $where ORDER BY sb_id DESC LIMIT $offset, $limit";
                        $result = mysqli_query($con, $sql);

                        // Total count for pagination
                        $total_sql = "SELECT COUNT(*) FROM student_bill WHERE sb_type = 'Pay Out' AND sb_associate = '$_SESSION[uid]' $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">
                            <div class="col-md-12 mb-3">
                                <form method="get" action="payout-history.php">
                                    <div class="input-group">
                                        <input type="text" name="search" class="form-control"
                                            placeholder="Search by Invoice" value="<?= htmlspecialchars($search) ?>">
                                        <button type="submit" class="btn btn-primary">Search</button>
                                    </div>
                                </form>
                            </div>
                            <?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>Course</th>
                                            <th>College</th>
                                            <th>Student</th>
                                            <th>Amount</th>
                                            <th>Date</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                        $i = $offset + 1;
                                        while ($row = mysqli_fetch_assoc($result)) {
                                            // Get course name
                                            $course = "";
                                            $product_sql = mysqli_query($con, "SELECT * FROM product WHERE pid = '{$row['sb_course']}'");

                                            if(mysqli_num_rows($product_sql) > 0){
                                                $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 = "";
                                            $college_sql = mysqli_query($con, "SELECT uname FROM users WHERE uid = '{$row['sb_college']}'");

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

                                            if (mysqli_num_rows($student_sql) > 0) {
                                                $student_row = mysqli_fetch_assoc($student_sql);
                                                $student = $student_row['uname'];
                                            }

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

                                        ?>
                                        <tr>
                                            <td><?= $i++ ?></td>
                                            <td><?= $row['sb_invoice'] ?></td>
                                            <td><?= $course . '( ' . $department . ' )' ?></td>
                                            <td><?= $college ?></td>
                                            <td><?= $student ?></td>
                                            <td>₹<?= number_format($row['sb_amount'], 2) ?></td>
                                            <td><?= $row['sb_date'] ?></td>
                                            <td>
                                                <a href="payout-history.php?view_id=<?= $row['sb_id'] ?>"
                                                    class="btn btn-sm btn-primary text-white"><i class="fa fa-eye"></i>
                                                    View</a>
                                                <?php if(isset($_GET["kallol"])){?>
                                                <a href="student-payout.php?client_id=<?= $client_id?>&edit_id=<?= $row['sb_id'] ?>"
                                                    class="btn btn-sm btn-warning text-white"><i
                                                        class="fa fa-pencil"></i> Edit</a>
                                                <a href="student-payout.php?client_id=<?= $client_id?>&del_id=<?= $row['sb_id'] ?>"
                                                    class="btn btn-sm btn-danger"
                                                    onclick="return confirm('Delete this bill?')"><i
                                                        class="fa fa-trash"></i> Delete</a>
                                                <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 }?>
                                            </td>
                                        </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                                <?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 ?>&search=<?= urlencode($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>
            <?php }?>
        </div>
        </div>

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

    <!-- JavaScript Libraries -->

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

</body>

</html>