<?php
session_start();
include "../db.php";
include "include/php-functions.php"; 

if (isset($_POST['start'])) {
    $start = mysqli_real_escape_string($con, $_POST['start']);
    $UserType = $_POST['UserType'];
    $UserId = $_POST['UserId'];

    // Initialize the conditions array
    $conditions = [];

    // Check UserType and apply corresponding filter
    if ($UserType == 'Employee' && !empty($UserId)) {
        $emp_id = mysqli_real_escape_string($con, $UserId);
        $conditions[] = "pEmployee = '" . $emp_id . "'";
    } elseif ($UserType == 'Associate' && !empty($UserId)) {
        $fran_id = mysqli_real_escape_string($con, $UserId);
        $conditions[] = "pFranchiee = '" . $fran_id . "'";
    }

    if (!empty($_POST['FirstFilterValue'])) {
        $fran_sql = mysqli_query($con, "SELECT uid FROM users WHERE uname = '{$_POST['FirstFilterValue']}' AND utype = 'Associate' ");
        if($fran_row = mysqli_fetch_assoc($fran_sql)){
            $fran_id = $fran_row["uid"];
        }
        $conditions[] = "pFranchiee = '" . $fran_id . "'";
    }
    
    
    if (!empty($_POST['SecondFilterValue'])) {
        $emp_sql = mysqli_query($con, "SELECT uid FROM users WHERE uname = '{$_POST['SecondFilterValue']}' AND utype = 'Sub Associate' ");
        if($emp_row = mysqli_fetch_assoc($emp_sql)){
            $emp_id = $emp_row["uid"];
        }
        $conditions[] = "pSubFranchiee = '" . $emp_id . "'";
    }
    
    if (!empty($_POST['college'])) {
        $clg_id = $_POST['college'];
        $conditions[] = "pCollege = '" . $clg_id . "'";
    }
    
    if (!empty($_POST['course'])) {
        $course_id = $_POST['course'];
        $conditions[] = "product = '" . $course_id. "'";
    }

    if (!empty($_POST['StatusValue'])) {
        $conditions[] = "pStatus = '" . mysqli_real_escape_string($con, $_POST['StatusValue']) . "'";
    }

    // Date range filters
    if (!empty($_POST['StartDate']) && !empty($_POST['EndDate'])) {
        $startDate = mysqli_real_escape_string($con, $_POST['StartDate']);
        $endDate = mysqli_real_escape_string($con, $_POST['EndDate']);
        $conditions[] = "pCreateDate BETWEEN '$startDate' AND '$endDate'";  
    } elseif (!empty($_POST['StartDate'])) {
        $startDate = mysqli_real_escape_string($con, $_POST['StartDate']);
        $conditions[] = "pCreateDate >= '$startDate'"; 
    } elseif (!empty($_POST['EndDate'])) {
        $endDate = mysqli_real_escape_string($con, $_POST['EndDate']);
        $conditions[] = "pCreateDate <= '$endDate'";  
    }

    // Build the WHERE clause if there are conditions
    $AndWhere = count($conditions) > 0 ? 'WHERE ' . implode(' AND ', $conditions) : '';

    $sql = "SELECT * FROM product $AndWhere ORDER BY pid DESC LIMIT $start, 10";

    $res = mysqli_query($con, $sql);

    if ($total_rows = mysqli_num_rows($res) > 0) {
        $c = $start + 1;

        while ($rows = mysqli_fetch_assoc($res)) {
            $client_name = fetchUserName($con, $rows['pClient']);
            $fran_name = fetchUserName($con, $rows['pFranchiee']);
            $subFran_name = fetchUserName($con, $rows['pSubFranchiee']);
            $employee_name = !empty($rows['pEmployee']) && $rows['pEmployee'] != 0 ? fetchUserName($con, $rows['pEmployee']) : '';

            $clg_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '{$rows["pCollege"]}'");
            if($clg_row = mysqli_fetch_assoc($clg_sql)){
                $clg_name = $clg_row["uname"];
            }

            $course_sql = mysqli_query($con, "SELECT * FROM clg_course WHERE sl_no = '{$rows["product"]}' ");
            while($course_row = mysqli_fetch_assoc($course_sql)){
                $course_name = $course_row["course_name"];
            }
            $cat_sql = mysqli_query($con, "SELECT * FROM clg_course_cat WHERE sl_no = '{$rows["pCat"]}' ");
            while($cat_row = mysqli_fetch_assoc($cat_sql)){
                $pCat = $cat_row["cat_name"];
            }

            $pStatus = $rows["pStatus"];
            $statusName = '';

            if ($pStatus == 0) {
                $statusName = 'Pending';
            } elseif ($pStatus == 1) {
                $statusName = 'Ongoing';
            } elseif ($pStatus == 2) {
                $statusName = 'Completed';
            } elseif ($pStatus == 3) {
                $statusName = 'Postponed';
            } elseif ($pStatus == 4) {
                $statusName = 'Rejected';
            }
            
?>

<li class='clearfix' style='float: none;' id="<?php echo $rows['pid']; ?>">
    <div class="single-dis-admin mb-2">
        <div class='row align-items-center'>
            <div class='col-md-9 col-12 mb-2'>
                <div class="row">
                    <div class="col-md-12 col-12">
                        <a style='color:orange;font-size:17px;cursor:pointer;text-decoration:none;'
                            data-product='<?php echo $course_name;?>' data-cat='<?php echo $pCat;?>'
                            data-fran='<?php echo $fran_name;?>' data-subFran='<?php echo $subFran_name;?>'
                            data-employee='<?php echo $employee_name;?>' data-date='<?php echo $rows["pCreateDate"];?>'
                            data-status='<?php echo $statusName;?>'>
                            <i class='fa fa-chalkboard' aria-hidden='true'></i> <b><?php echo $course_name;?></b>
                        </a>
                        <br>
                        <b><i class='fa fa-shapes' style="color:orange;"></i>
                        </b><?php echo $pCat . ' [<i class="fa fa-school" style="color:orange;"></i>' . $clg_name . ']';?>
                        &nbsp; &nbsp;&nbsp;
                        <b><i class='fa fa-clock' style="color:orange;"></i> </b><?php echo $rows["pCreateDate"];?>
                        <br>
                        <i class="fa fa-user" style="color:orange;"></i> <?php echo $client_name;?>
                        <br>
                        <b><i class="fa fa-network-wired" style="color:orange;"></i> <?php echo $fran_name;?></b>
                        <?php if($subFran_name != ""){
                            ?>
                        <b>|| <i class="fa fa-timeline" style="color:orange;"></i> <?php echo $subFran_name;?></b>
                        <?php }?>
                    </div>
                </div>
            </div>

            <div class='col-md-3 col-12'>
                <form action="" mehod="POST">
                    <div class="mb-2 d-flex">
                        <select name="status" class="form-control form-control-sm" id="pststus"
                            onchange="updateStatus(<?php echo $rows['pid']; ?>, this.value)">
                            <option value="<?php echo $pStatus;?>"><?php echo $statusName;?></option>
                            <option value="0" <?php if($pStatus == 0) echo 'disabled'; ?>>Pending</option>
                            <option value="1" <?php if($pStatus == 1) echo 'disabled'; ?>>Ongoing</option>
                            <option value="2" <?php if($pStatus == 2) echo 'disabled'; ?>>Completed</option>
                            <option value="3" <?php if($pStatus == 3) echo 'disabled'; ?>>Postponed</option>
                            <option value="4" <?php if($pStatus == 4) echo 'disabled'; ?>>Rejected</option>
                        </select>
                    </div>
                    <div class="d-flex justify-content-between">
                        <button type="button" class="btn btn-primary btn-sm" data-id="<?php echo $rows['pid']; ?>"
                            onclick="loadFinalDocumentModal(<?php echo $rows['pid']; ?>)">
                            Final Document
                        </button>

                        <button type="button" class="btn btn-secondary btn-sm" data-id="<?php echo $rows['pid']; ?>"
                            onclick="loadViewProductModal(<?php echo $rows['pid']; ?>)">
                            <i class='fa fa-eye' aria-hidden='true'></i> View Course
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</li>

<?php
            $c++;
        }
        mysqli_close($con);
    }
}
?>


<script>
$('#finalDocumentModal').on('hidden.bs.modal', function() {
    $(this).removeData('bs.modal').find('.modal-body').empty();
});

$('#viewProductModal').on('hidden.bs.modal', function() {
    $(this).removeData('bs.modal').find('.modal-body').empty();
});

// Load Final Document Modal
function loadFinalDocumentModal(pid) {
    $.ajax({
        url: 'get-final-document.php',
        type: 'POST',
        data: {
            pid: pid
        },
        dataType: 'json',
        success: function(response) {
            $('#finalDocumentModal .modal-body').html(response.html);
            $('#finalDocumentModal').modal('show');
        },
        error: function() {
            alert('Error loading document.');
        }
    });
}

// Load View Product Modal
function loadViewProductModal(pid) {
    $.ajax({
        url: 'get-view-product.php',
        type: 'POST',
        data: {
            pid: pid
        },
        dataType: 'json',
        success: function(response) {
            $('#viewProductModal .modal-body').html(response.html);
            $('#viewProductModal').modal('show');
        },
        error: function() {
            alert('Error loading product details.');
        }
    });
}
</script>

<script>
function updateStatus(productId, statusValue) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "updateStatus.php", true); // This is the PHP file that will update the database
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            // Optionally show success message
            console.log(xhr.responseText);
        }
    };
    xhr.send("product_id=" + productId + "&status=" + statusValue);
}

function updateEmployee(productId, employeeValue) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "updateEmployee.php", true); // This is the PHP file that will update the employee
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            // Optionally show success message
            console.log(xhr.responseText);
        }
    };
    xhr.send("product_id=" + productId + "&employee=" + employeeValue);
}
</script>