<?php
    // session_start();
    include "../db.php";
    require '../auth.php';
    restrictAccess(['master_admin']);
    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();
    }
    // echo $_SESSION["otp"];
    // echo $_SESSION["uref_code"];
    if(isset($_GET["client_id"])){}
?>

<!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 -->
    <?php if(isset($_GET["client_id"])){
        $client_id = $_GET["client_id"];
        $client_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '$client_id' ");
        if($client_row = mysqli_fetch_assoc($client_sql))
            $client_name = $client_row["uname"];
        ?>

    <section id="inner-body">
        <div class="body-content">
            <div class="container-fluid">
                <?php if(isset($_GET["edit_id"])){
                    $edit_id = mysqli_real_escape_string($con, $_GET['edit_id']);
                    $fetch = mysqli_query($con, "SELECT * FROM student_bill WHERE sb_id = '$edit_id'");
                    if (mysqli_num_rows($fetch) > 0) 
                        $edit_data = mysqli_fetch_assoc($fetch);
                        // Get College
                        $college = "";
                        $college_sql = mysqli_query($con, "SELECT uname FROM users WHERE uid = '{$edit_data['sb_college']}'");

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

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

                        // Get batch
                        $batch = "";
                        $batch_sql = mysqli_query($con, "SELECT batch_title FROM branch WHERE b_id = '{$edit_data['sb_batch']}'");
                        if (mysqli_num_rows($batch_sql) > 0) {
                            $batch_row = mysqli_fetch_assoc($batch_sql);
                            $batchGet = $batch_row['batch_title'];
                        }
                    ?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Edit Billing Details if <span
                            style="color:#293061;"><?= $client_name;?></span>
                    </h5>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <input type="hidden" name="sb_id" value="<?= $edit_data['sb_id'] ?? '' ?>">

                            <div class="row">
                                <!-- Course -->
                                <div class="col-md-4 mb-2">
                                    <label for="course">Select Course</label>
                                    <select name="course" class="form-control" id="course">
                                        <option value="">Select From The List</option>
                                        <?php 
                                            $product_sql = mysqli_query($con, "SELECT * FROM product WHERE pClient = '{$client_id}' ORDER BY pid DESC");
                                            while($product_row = mysqli_fetch_assoc($product_sql)){
                                                $college_sql = mysqli_query($con, "SELECT uid, uname FROM users WHERE uid = '{$product_row["pCollege"]}'");
                                                $college = mysqli_fetch_assoc($college_sql);

                                                $course_sql = mysqli_query($con, "SELECT course_name FROM clg_course WHERE sl_no = '{$product_row["product"]}'");
                                                $course_row = mysqli_fetch_assoc($course_sql);

                                                $cat_sql = mysqli_query($con, "SELECT sl_no, cat_name FROM clg_course_cat WHERE sl_no = '{$product_row["pCat"]}'");
                                                $cat_row = mysqli_fetch_assoc($cat_sql);

                                                // Get Associate
                                                $associate_id = ''; 
                                                $associate_name = '';
                                                $associate_sql = mysqli_query($con, "SELECT uid, uname FROM users WHERE uid = '{$product_row["pFranchiee"]}'");
                                                if($associate_row = mysqli_fetch_assoc($associate_sql)){
                                                    $associate_id = $associate_row["uid"];
                                                    $associate_name = $associate_row["uname"];
                                                }
                                                
                                                // Get Batch
                                                $batch_name = ''; $batch_id = '';
                                                $batch_sql = mysqli_query($con, "SELECT b_id, batch_title FROM branch WHERE b_id = '{$product_row["pBatch"]}'");
                                                if($batch_row = mysqli_fetch_assoc($batch_sql)){
                                                    $batch_id = $batch_row["b_id"];
                                                    $batch_name = $batch_row["batch_title"];
                                                }

                                                if (!empty($course_row['course_name'])) {
                                                    $selected = ($edit_data['sb_course'] ?? '') == $product_row['pid'] ? 'selected' : '';
                                        ?>
                                        <option value="<?= $product_row['pid']; ?>" <?= $selected ?>
                                            data-batch-id="<?= $batch_id ?>"
                                            data-batch-name="<?= htmlspecialchars($batch_name) ?>"
                                            data-college-id="<?= $college['uid'] ?>"
                                            data-college-name="<?= htmlspecialchars($college['uname']) ?>"
                                            data-category-id="<?= $cat_row['sl_no'] ?>"
                                            data-category-name="<?= htmlspecialchars($cat_row['cat_name']) ?>"
                                            data-associate-id="<?= $product_row['pFranchiee'] ?>"
                                            data-associate-name="<?= htmlspecialchars($associate_name) ?>">
                                            <?= htmlspecialchars($course_row['course_name']); ?>
                                        </option>
                                        <?php }} ?>
                                    </select>
                                </div>

                                <!-- Batch -->
                                <div class="col-md-4 mb-2">
                                    <label for="batch">Select Batch</label>
                                    <select name="batch" class="form-control" id="batch">
                                        <?php if (!empty($edit_data['sb_batch'])) { ?>
                                        <option value="<?= $edit_data['sb_batch'] ?>" selected>
                                            <?= $batchGet ?></option>
                                        <?php } else { ?>
                                        <option value="">Select Course First</option>
                                        <?php } ?>
                                    </select>
                                </div>

                                <!-- Department -->
                                <div class="col-md-4 mb-2">
                                    <label for="department">Select Department</label>
                                    <select name="department" class="form-control" id="department">
                                        <?php if (!empty($edit_data['sb_dept'])) { ?>
                                        <option value="<?= $edit_data['sb_dept'] ?>" selected>
                                            <?= $department ?></option>
                                        <?php } else { ?>
                                        <option value="">Select Course First</option>
                                        <?php } ?>
                                    </select>
                                </div>

                                <!-- College -->
                                <div class="col-md-4 mb-2">
                                    <label for="college">Select College</label>
                                    <select name="college" class="form-control" id="college">
                                        <?php if (!empty($edit_data['sb_college'])) { ?>
                                        <option value="<?= $edit_data['sb_college'] ?>" selected>
                                            <?php echo $collegeGet ?></option>
                                        <?php } else { ?>
                                        <option value="">Select Course First</option>
                                        <?php } ?>
                                    </select>
                                </div>
                                <!-- Associate -->
                                <div class="col-md-4 mb-2">
                                    <label for="associate">Select Associate</label>
                                    <select name="associate" class="form-control" id="associate">
                                        <?php if (!empty($edit_data['sb_associate'])) {
                                        $associateRow = mysqli_fetch_assoc(mysqli_query($con, "SELECT uname FROM users WHERE uid = '{$edit_data['sb_associate']}'")); ?>
                                        <option value="<?= $edit_data['sb_associate'] ?>" selected>
                                            <?= $associateRow['uname'] ?>
                                        </option>
                                        <?php } else { ?>
                                        <option value="">Select Course First</option>
                                        <?php } ?>
                                    </select>
                                </div>


                                <!-- Amount -->
                                <div class="col-md-4 mb-2">
                                    <label for="amount">Pay Out Amount</label>
                                    <input type="number" name="amount" class="form-control"
                                        value="<?= $edit_data['sb_amount'] ?? '' ?>">
                                </div>

                                <!-- Description -->
                                <div class="col-md-12 mb-3">
                                    <label for="content">Description</label>
                                    <textarea class="form-control" name="content"
                                        rows="3"><?= $edit_data['sb_description'] ?? '' ?></textarea>
                                </div>

                                <?php if(isset($_GET["kallol"])){?>
                                <!-- Payment Mode -->
                                <div class="col-md-4">
                                    <label for="payment_mode">Select Payment Mode</label>
                                    <select name="payment_mode" id="payment_mode" class="form-control"
                                        onchange="togglePaymentFields()">
                                        <option value="">Select Mode</option>
                                        <option value="Cash"
                                            <?= ($edit_data['sb_mode'] ?? '') == 'Cash' ? 'selected' : '' ?>>Cash
                                        </option>
                                        <option value="UPI"
                                            <?= ($edit_data['sb_mode'] ?? '') == 'UPI' ? 'selected' : '' ?>>UPI</option>
                                        <option value="Cheque/DD"
                                            <?= ($edit_data['sb_mode'] ?? '') == 'Cheque/DD' ? 'selected' : '' ?>>
                                            Cheque/DD</option>
                                    </select>
                                </div>

                                <!-- Cash Remark -->
                                <div class="col-md-8 mb-2" id="cash_remark" style="display:none;">
                                    <label>Cash Remark</label>
                                    <input type="text" name="cash_remark" class="form-control"
                                        value="<?= $edit_data['sb_remark'] ?? '' ?>">
                                </div>

                                <!-- UPI TXN -->
                                <div class="col-md-4 mb-2" id="upi_txn" style="display:none;">
                                    <label>Transaction ID (UPI)</label>
                                    <input type="text" name="upi_txn_id" class="form-control"
                                        value="<?= $edit_data['sb_remark'] ?? '' ?>">
                                </div>

                                <!-- Cheque/DD Number -->
                                <div class="col-md-4 mb-2" id="cheque_number" style="display:none;">
                                    <label>Cheque/DD Number</label>
                                    <input type="text" name="cheque_dd_number" class="form-control"
                                        value="<?= $edit_data['sb_remark'] ?? '' ?>">
                                </div>

                                <!-- Upload Image -->
                                <div class="col-md-4 mb-2" id="upi_cheque_image" style="display:none;">
                                    <label>Upload Image (UPI/Cheque/DD)</label>
                                    <input type="file" name="payment_image" class="form-control">
                                    <?php if (!empty($edit_data['sb_file'])): ?>
                                    <a href="../upload/payout/<?= $edit_data['sb_file'] ?>" target="_blank">View
                                        Existing File</a>
                                    <?php endif; ?>
                                </div>
                                <?php }?>
                            </div>

                            <!-- Submit -->
                            <div>
                                <button type="submit" name="edit_submit" class="btn btn-success btn-user my-2">
                                    <i class="fa fa-save"></i> Update Pay Out
                                </button>
                                <a href="student-payout.php?client_id=<?= $client_id ?>"
                                    class="btn btn-warning btn-user m-2">
                                    <i class="fa fa-ban"></i> Cancel
                                </a>
                            </div>
                        </form>
                    </div>
                </div>

                <script>
                // document.getElementById('course').addEventListener('change', function() {
                //     const selected = this.options[this.selectedIndex];

                //     const deptName = selected.getAttribute('data-category-name') || '';
                //     const deptId = selected.getAttribute('data-category-id') || '';

                //     const collegeName = selected.getAttribute('data-college-name') || '';
                //     const collegeId = selected.getAttribute('data-college-id') || '';

                //     const associateName = selected.getAttribute('data-associate-name') || '';
                //     const associateId = selected.getAttribute('data-associate-id') || '';

                //     const deptSelect = document.getElementById('department');
                //     const collegeSelect = document.getElementById('college');
                //     const associateSelect = document.getElementById('associate');

                //     // Populate Department
                //     deptSelect.innerHTML = '';
                //     if (deptId && deptName) {
                //         let opt = document.createElement('option');
                //         opt.value = deptId;
                //         opt.textContent = deptName;
                //         deptSelect.appendChild(opt);
                //     } else {
                //         deptSelect.innerHTML = '<option value="">Not Found</option>';
                //     }

                //     // Populate College
                //     collegeSelect.innerHTML = '';
                //     if (collegeId && collegeName) {
                //         let opt = document.createElement('option');
                //         opt.value = collegeId;
                //         opt.textContent = collegeName;
                //         collegeSelect.appendChild(opt);
                //     } else {
                //         collegeSelect.innerHTML = '<option value="">Not Found</option>';
                //     }

                //     // Populate Associate
                //     associateSelect.innerHTML = '';
                //     if (associateId && associateName) {
                //         let opt = document.createElement('option');
                //         opt.value = associateId;
                //         opt.textContent = associateName;
                //         associateSelect.appendChild(opt);
                //     } else {
                //         associateSelect.innerHTML = '<option value="">Not Found</option>';
                //     }
                // });
                </script>

                <?php } elseif(isset($_GET["add_id"])){?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Add Pay Out Details For
                        <span style="color:orange;"><?php echo $client_name;?></span>
                    </h5>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-4 mb-2">
                                    <label for="course">Select Course <span class="text-danger">*</span></label>
                                    <select name="course" class="form-control" id="course" required>
                                        <option value="">Select From The List</option>
                                        <?php 
                                            $product_sql = mysqli_query($con, "SELECT * FROM product WHERE pClient = '{$client_id}' ORDER BY pid DESC");
                                            while($product_row = mysqli_fetch_assoc($product_sql)){

                                                // Get College
                                                $college_name = ''; $college_id = '';
                                                $college_sql = mysqli_query($con, "SELECT uid, uname FROM users WHERE uid = '{$product_row["pCollege"]}'");
                                                if($college_row = mysqli_fetch_assoc($college_sql)){
                                                    $college_id = $college_row["uid"];
                                                    $college_name = $college_row["uname"];
                                                }

                                                // Get Batch
                                                $batch_name = ''; $batch_id = '';
                                                $batch_sql = mysqli_query($con, "SELECT b_id, batch_title FROM branch WHERE b_id = '{$product_row["pBatch"]}'");
                                                if($batch_row = mysqli_fetch_assoc($batch_sql)){
                                                    $batch_id = $batch_row["b_id"];
                                                    $batch_name = $batch_row["batch_title"];
                                                }

                                                // Get Course
                                                $course_name = '';
                                                $course_sql = mysqli_query($con, "SELECT course_name FROM clg_course WHERE sl_no = '{$product_row["product"]}'");
                                                if($course_row = mysqli_fetch_assoc($course_sql)){
                                                    $course_name = $course_row["course_name"];
                                                }

                                                // Get Category (Department)
                                                $category_id = ''; $category_name = '';
                                                $cat_sql = mysqli_query($con, "SELECT sl_no, cat_name FROM clg_course_cat WHERE sl_no = '{$product_row["pCat"]}'");
                                                if($cat_row = mysqli_fetch_assoc($cat_sql)){
                                                    $category_id = $cat_row["sl_no"];
                                                    $category_name = $cat_row["cat_name"];
                                                }

                                                // Get Associate
                                                $associate_id = ''; 
                                                $associate_name = '';
                                                $associate_sql = mysqli_query($con, "SELECT uid, uname FROM users WHERE uid = '{$product_row["pFranchiee"]}'");
                                                if($associate_row = mysqli_fetch_assoc($associate_sql)){
                                                    $associate_id = $associate_row["uid"];
                                                    $associate_name = $associate_row["uname"];
                                                }

                                                if (!empty($course_name)) {
                                        ?>
                                        <option value="<?php echo $product_row["pid"]; ?>"
                                            data-batch-id="<?php echo $batch_id; ?>"
                                            data-batch-name="<?php echo htmlspecialchars($batch_name); ?>"
                                            data-college-id="<?php echo $college_id; ?>"
                                            data-college-name="<?php echo htmlspecialchars($college_name); ?>"
                                            data-associate-id="<?php echo $associate_id; ?>"
                                            data-associate-name="<?php echo htmlspecialchars($associate_name); ?>"
                                            data-category-id="<?php echo $category_id; ?>"
                                            data-category-name="<?php echo htmlspecialchars($category_name); ?>">
                                            <?php echo htmlspecialchars($course_name); ?>
                                        </option>
                                        <?php }} ?>
                                    </select>
                                </div>

                                <div class="col-md-4 mb-2">
                                    <label for="batch">Select Batch</label>
                                    <select name="batch" class="form-control" id="batch">
                                        <option value="">Select Course First</option>
                                    </select>
                                </div>

                                <div class="col-md-4 mb-2">
                                    <label for="department">Select Department</label>
                                    <select name="department" class="form-control" id="department">
                                        <option value="">Select Course First</option>
                                    </select>
                                </div>

                                <div class="col-md-4 mb-2">
                                    <label for="college">Select College</label>
                                    <select name="college" class="form-control" id="college">
                                        <option value="">Select Course First</option>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="associate">Select Associate</label>
                                    <select name="associate" class="form-control" id="associate">
                                        <option value="">Select Course First</option>
                                    </select>
                                </div>

                                <div class="col-md-4 mb-2">
                                    <label for="studentName">Pay Out Amount <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" name="amount" placeholder="Enter Amount"
                                        required>
                                    <input type="hidden" class="form-control" name="uname"
                                        value="<?php echo $client_id;?>">
                                </div>

                                <div class="col-md-12 mb-3">
                                    <label for="content" class="form-label">Description</label>
                                    <textarea class="form-control" name="content" rows="3"></textarea>
                                </div>

                                <?php if(isset($_GET["kallol"])){?>
                                <div class="col-md-4">
                                    <label for="payment_mode">Select Payment Mode <span
                                            class="text-danger">*</span></label>
                                    <select name="payment_mode" id="payment_mode" class="form-control"
                                        onchange="togglePaymentFields()" required>
                                        <option value="">Select Mode</option>
                                        <option value="Cash">Cash</option>
                                        <option value="UPI">UPI</option>
                                        <option value="Cheque/DD">Cheque/DD</option>
                                    </select>
                                </div>
                                <!-- Cash Remark -->
                                <div class="col-md-8 mb-2 d-none" id="cash_remark">
                                    <label for="cash_remark_input">Cash Remark</label>
                                    <input type="text" name="cash_remark" class="form-control"
                                        placeholder="Enter remark">
                                </div>

                                <!-- UPI Transaction ID -->
                                <div class="col-md-4 mb-2 d-none" id="upi_txn">
                                    <label for="upi_txn_id">Transaction ID (UPI)</label>
                                    <input type="text" name="upi_txn_id" class="form-control"
                                        placeholder="Enter UPI Transaction ID">
                                </div>

                                <!-- Cheque/DD Number -->
                                <div class="col-md-4 mb-2 d-none" id="cheque_number">
                                    <label for="cheque_dd_number">Cheque/DD Number</label>
                                    <input type="text" name="cheque_dd_number" class="form-control"
                                        placeholder="Enter Cheque or DD Number">
                                </div>

                                <!-- Image Upload for UPI or Cheque/DD -->
                                <div class="col-md-4 mb-2 d-none" id="upi_cheque_image">
                                    <label for="payment_image">Upload Image (UPI/Cheque/DD)</label>
                                    <input type="file" name="payment_image" class="form-control">
                                </div>
                                <?php }?>
                            </div>
                            <div>
                                <button type="submit" class="btn btn-success btn-user my-2" name="submit"><i
                                        class="fa fa-plus"></i> Add Pay Out
                                </button>
                                <a href="student-payout.php?client_id=<?php echo $client_id;?>"
                                    class="btn btn-warning btn-user m-2"> <i class="fa fa-ban"></i> Cancel </a>
                            </div>
                        </form>
                    </div>
                </div>
                <?php
                } else{?>
                <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-12 mb-2">
                                        <h4 class="text-gray-800 m-0">Pay Outs For <span
                                                style="color:orange;"><?php echo $client_name;?></span></h4>
                                    </div>
                                    <div class="col-md-4 col-12 text-end">
                                        <a href="view-client.php" class="btn btn-warning text-white btn-sm"><i
                                                class="fa fa-arrow-left"></i> Back</a>
                                        <a href="student-payout.php?client_id=<?php echo $client_id;?>&add_id"
                                            class="btn btn-primary btn-sm m-0"><i class="fa fa-plus"></i>&nbsp;
                                            Pay Out</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;

                        // 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_course IN (SELECT pid FROM product WHERE product IN (SELECT sl_no FROM clg_course WHERE course_name LIKE '%$search%')))";
                        }

                        // Fetch bills with optional search
                        $sql = "SELECT * FROM student_bill WHERE sb_for = '$client_id' AND sb_type = 'Pay Out' $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_for = '$client_id' AND sb_type = 'Pay Out' $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="student-payout.php">
                                    <input type="hidden" name="client_id" value="<?= $client_id ?>">
                                    <div class="input-group">
                                        <input type="text" name="search" class="form-control"
                                            placeholder="Search by Course" value="<?= htmlspecialchars($search) ?>">
                                        <button type="submit" class="btn btn-primary">Search</button>
                                    </div>
                                </form>
                            </div>
                            <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>Associate</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); // ✅ fetch the row
                                                $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 College
                                            $associate = "";
                                            $associate_sql = mysqli_query($con, "SELECT uname FROM users WHERE uid = '{$row['sb_associate']}'");

                                            if (mysqli_num_rows($associate_sql) > 0) {
                                                $associate_row = mysqli_fetch_assoc($associate_sql);
                                                $associate = $associate_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'];
                                            }

                                            // 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><?= $course . '( ' . $department . ' ) [ Batch: ' . $batch . ']' ?></td>
                                            <td><?= $college ?></td>
                                            <td><?= $associate ?></td>
                                            <td>₹<?= number_format($row['sb_amount'], 2) ?></td>
                                            <td><?= $row['sb_date'] ?></td>
                                            <td>
                                                <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>

                                                <?php if(isset($_GET["kallol"])){?>
                                                <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 ?>&client_id=<?= $client_id ?>&search=<?= urlencode($search) ?>"><?= $p ?></a>
                                        </li>
                                        <?php endfor; ?>
                                    </ul>
                                </nav>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                <?php }?>
            </div>
        </div>

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

    <?php  }?>

    <!-- JavaScript Libraries -->

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

    <script>
    document.getElementById('course').addEventListener('change', function() {
        var selected = this.options[this.selectedIndex];

        var batchId = selected.getAttribute('data-batch-id');
        var batchName = selected.getAttribute('data-batch-name');

        var deptId = selected.getAttribute('data-category-id');
        var deptName = selected.getAttribute('data-category-name');

        var associateId = selected.getAttribute('data-associate-id');
        var associateName = selected.getAttribute('data-associate-name');

        var collegeId = selected.getAttribute('data-college-id');
        var collegeName = selected.getAttribute('data-college-name');

        // Update Batch
        var batchSelect = document.getElementById('batch');
        batchSelect.innerHTML = '';
        if (batchId && batchName) {
            var option = document.createElement('option');
            option.value = batchId;
            option.text = batchName;
            batchSelect.appendChild(option);
        } else {
            batchSelect.innerHTML = '<option value="">Not Found</option>';
        }

        // Update Department (Category)
        var deptSelect = document.getElementById('department');
        deptSelect.innerHTML = '';
        if (deptId && deptName) {
            var option = document.createElement('option');
            option.value = deptId;
            option.text = deptName;
            deptSelect.appendChild(option);
        } else {
            deptSelect.innerHTML = '<option value="">Not Found</option>';
        }

        // Update College
        var collegeSelect = document.getElementById('college');
        collegeSelect.innerHTML = '';
        if (collegeId && collegeName) {
            var option = document.createElement('option');
            option.value = collegeId;
            option.text = collegeName;
            collegeSelect.appendChild(option);
        } else {
            collegeSelect.innerHTML = '<option value="">Not Found</option>';
        }

        // Update Associate
        var associateSelect = document.getElementById('associate');
        associateSelect.innerHTML = '';
        if (associateId && associateName) {
            var option = document.createElement('option');
            option.value = associateId;
            option.text = associateName;
            associateSelect.appendChild(option);
        } else {
            associateSelect.innerHTML = '<option value="">Not Found</option>';
        }
    });
    </script>

    <script>
    function togglePaymentFields() {
        const mode = document.getElementById("payment_mode").value;

        // Hide all fields first
        document.getElementById("cash_remark").classList.add("d-none");
        document.getElementById("upi_txn").classList.add("d-none");
        document.getElementById("cheque_number").classList.add("d-none");
        document.getElementById("upi_cheque_image").classList.add("d-none");

        if (mode === "Cash") {
            document.getElementById("cash_remark").classList.remove("d-none");
        } else if (mode === "UPI") {
            document.getElementById("upi_txn").classList.remove("d-none");
            document.getElementById("upi_cheque_image").classList.remove("d-none");
        } else if (mode === "Cheque/DD") {
            document.getElementById("cheque_number").classList.remove("d-none");
            document.getElementById("upi_cheque_image").classList.remove("d-none");
        }
    }
    </script>


</body>

</html>


<?php
if (isset($_POST['submit'])) {
    $uname = mysqli_real_escape_string($con, $_POST['uname']);
    $course = mysqli_real_escape_string($con, $_POST['course']);
    $batch = mysqli_real_escape_string($con, $_POST['batch']);
    $department = mysqli_real_escape_string($con, $_POST['department']);
    $college = mysqli_real_escape_string($con, $_POST['college']);
    $content = mysqli_real_escape_string($con, $_POST['content']);
    $purpuse = mysqli_real_escape_string($con, $_POST['purpuse']);
    $amount = mysqli_real_escape_string($con, $_POST['amount']);
    $payment_mode = mysqli_real_escape_string($con, $_POST['payment_mode']);
    $associate = mysqli_real_escape_string($con, $_POST['associate']);
    
    $sb_type = "Pay Out";
    $remark = '';

    if (!empty($_POST['cash_remark'])) {
        $remark = mysqli_real_escape_string($con, $_POST['cash_remark']);
    } elseif (!empty($_POST['upi_txn_id'])) {
        $remark = mysqli_real_escape_string($con, $_POST['upi_txn_id']);
    } elseif (!empty($_POST['cheque_dd_number'])) {
        $remark = mysqli_real_escape_string($con, $_POST['cheque_dd_number']);
    }
    
    $sb_file = "";
    if (isset($_FILES['payment_image']) && $_FILES['payment_image']['error'] == 0) {
        $target_dir = "../upload/payout/";
        $filename = time() . "_" . basename($_FILES["payment_image"]["name"]);
        $target_file = $target_dir . $filename;

        // Optional: Validate image type
        $file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'pdf'];
        if (in_array($file_type, $allowed_types)) {
            if (move_uploaded_file($_FILES["payment_image"]["tmp_name"], $target_file)) {
                $sb_file = $filename;
            }
        }
    }

    $sb_by = $_SESSION['uid'];

    
    function generateUniqueInvoice($con) {
        do {
            // Generate 3 random uppercase alphabets
            $alphabets = '';
            for ($i = 0; $i < 3; $i++) {
                $alphabets .= chr(rand(65, 90)); // ASCII A–Z
            }

            // Generate 5 random digits and shuffle them
            $digits = range(0, 9);
            shuffle($digits);
            $random_digits = array_slice($digits, 0, 5);
            $shuffled_digits = implode('', $random_digits);

            // Combine with prefix
            $invoice = 'POT-' . $alphabets . $shuffled_digits;

            // Check if it already exists in the database
            $check = mysqli_query($con, "SELECT sb_invoice FROM student_bill WHERE sb_invoice = '$invoice'");
        } while (mysqli_num_rows($check) > 0);

        return $invoice;
    }

    $invoice_number = generateUniqueInvoice($con);


    $insert = mysqli_query($con, "INSERT INTO student_bill 
        (sb_for, sb_course, sb_dept, sb_college, sb_associate, sb_subAsso, sb_amount, sb_description, sb_purpus, sb_file, sb_date, sb_recycle, sb_by, sb_mode, sb_remark, sb_invoice, sb_type, sb_batch) 
        VALUES 
        ('$uname', '$course', '$department', '$college', '$associate', '', '$amount', '$content', '$purpuse', '$sb_file', '$currentTime', 1, '$sb_by', '$payment_mode', '$remark', '$invoice_number', '$sb_type', '$batch')
    ");


    if ($insert) {
        echo "<script>alert('Pay Out Payment Added Successfully'); location.href='student-payout.php?client_id=$uname';</script>";
    } else {
        echo "<script>alert('Error inserting Pay Out.');</script>";
    }
}

?>

<?php
if (isset($_POST['edit_submit'])) {
    $sb_id = mysqli_real_escape_string($con, $_POST['sb_id']);
    $amount = mysqli_real_escape_string($con, $_POST['amount']);
    $content = mysqli_real_escape_string($con, $_POST['content']);
    $purpuse = mysqli_real_escape_string($con, $_POST['purpuse']);
    $course = mysqli_real_escape_string($con, $_POST['course']);
    $batch = mysqli_real_escape_string($con, $_POST['batch']);
    $dept = mysqli_real_escape_string($con, $_POST['department']);
    $college = mysqli_real_escape_string($con, $_POST['college']);
    $associate = mysqli_real_escape_string($con, $_POST['associate']);
    $mode = $_POST['payment_mode'];

    if (!empty($_POST['cash_remark'])) {
        $remark = mysqli_real_escape_string($con, $_POST['cash_remark']);
    } elseif (!empty($_POST['upi_txn_id'])) {
        $remark = mysqli_real_escape_string($con, $_POST['upi_txn_id']);
    } elseif (!empty($_POST['cheque_dd_number'])) {
        $remark = mysqli_real_escape_string($con, $_POST['cheque_dd_number']);
    }

    $imgName = '';
    $getOld = mysqli_query($con, "SELECT sb_file, sb_mode FROM student_bill WHERE sb_id = '$sb_id'");
    $oldData = mysqli_fetch_assoc($getOld);
    $oldFile = $oldData['sb_file'];
    $oldMode = $oldData['sb_mode'];

    // Unlink if file exists and (mode changes to Cash OR new file uploaded)
    if (($mode === 'Cash' && $oldFile) || !empty($_FILES['payment_image']['name'])) {
        $path = "../upload/payout/" . $oldFile;
        if (file_exists($path)) unlink($path);
    }

    // Handle new file
    if (!empty($_FILES['payment_image']['name'])) {
        $img = $_FILES['payment_image']['name'];
        $tmp = $_FILES['payment_image']['tmp_name'];
        $imgName = time() . '_' . basename($img);
        move_uploaded_file($tmp, "../upload/payout/$imgName");
    } else {
        // Keep existing file if new not uploaded and mode is not Cash
        $imgName = ($mode !== 'Cash') ? $oldFile : '';
    }

    $update = mysqli_query($con, "UPDATE student_bill SET 
        sb_course = '$course',
        sb_batch = '$batch',
        sb_dept = '$dept',
        sb_college = '$college',
        sb_amount = '$amount',
        sb_description = '$content',
        sb_purpus = '$purpuse',
        sb_mode = '$mode',
        sb_remark = '$remark',
        sb_associate = '$associate',
        sb_file = '$imgName',
        sb_by = '{$_SESSION['uid']}'
        WHERE sb_id = '$sb_id'
    ");

    if ($update) {
        echo "<script>alert('Updated Successfully');location.href='student-payout.php?client_id=$client_id';</script>";
    } else {
        echo "<script>alert('Update Failed');</script>";
    }
}

?>

<?php
if (isset($_GET['del_id'])) {
    $del_id = mysqli_real_escape_string($con, $_GET['del_id']);

    // Step 1: Fetch image filename if any
    $fetch = mysqli_query($con, "SELECT sb_file FROM student_bill WHERE sb_id = '$del_id'");
    if ($fetch && mysqli_num_rows($fetch) > 0) {
        $row = mysqli_fetch_assoc($fetch);
        $file = $row['sb_file'];

        // Step 2: Delete the file from the server
        if (!empty($file)) {
            $filePath = "../upload/payout/" . $file;
            if (file_exists($filePath)) {
                unlink($filePath);
            }
        }

        // Step 3: Delete the record from the database
        $delete = mysqli_query($con, "DELETE FROM student_bill WHERE sb_id = '$del_id'");

        if ($delete) {
            echo "<script>alert('Pay Out deleted successfully');location.href='student-payout.php?client_id={$client_id}';</script>";
        } else {
            echo "<script>alert('Failed to delete Pay Out .');</script>";
        }
    } else {
        echo "<script>alert('Record not found');</script>";
    }
}
?>