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

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

    $emp_id = $_SESSION["uid"];

    // Initialize an array to hold filter conditions
    $conditions = [];
    
    $conditions[] = "pStatus = '" . $_POST['StatusValue'] . "'";

    // $conditions[] = "pEmployee = '" . $emp_id . "'";

    include("include/productListFilter.php");

    // Build the WHERE clause
    if (count($conditions) > 0) {
        $AndWhere = 'WHERE ' . implode(' AND ', $conditions);
    }
    $_SESSION['export_conditions'] = $conditions; // Store conditions for export use
    
    $total_pricing_sum = 0; 
    $total_payment_sum = 0;  
    $total_discount = 0;

    ?>

<?php
    $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']) : '';

            $serviceDetails = fetchServiceDetails($con, $rows["product"]);
            $product = $serviceDetails['product'];
            $pricing = $serviceDetails['pricing'];

            $total_payment = fetchTotalPayment($con, $rows["pid"]);

            $pCat = fetchCategoryName($con, $rows["pCat"]);

            $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-7 col-12">
                        <a style='color:orange;font-size:17px;cursor:pointer;text-decoration:none;'
                            data-product='<?php echo $product;?>' 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='fab fa-product-hunt' aria-hidden='true'></i> <b><?php echo $product;?></b>
                        </a>
                        <br>
                        <b class="small"><i class="fa fa-user" style="color:orange;"></i> <?php echo $client_name;?></b>
                        <br>
                        <b class="small"><i class="fa fa-network-wired" style="color:orange;"></i>
                            <?php echo $fran_name;?></b>
                        <?php if($subFran_name != ""){
                            ?>
                        <b class="small">|| <i class="fa fa-timeline" style="color:orange;"></i>
                            <?php echo $subFran_name;?></b>
                        <?php }?>
                        <br>
                        <b class="small"><i class='fa fa-list-alt' style="color:orange;"></i> </b><?php echo $pCat;?>
                        &nbsp; &nbsp;
                        &nbsp;
                        <b class="small"><i class='fa fa-clock' style="color:orange;"></i>
                        </b><?php echo $rows["pCreateDate"];?>
                    </div>
                    <div class="col-md-5 col-12">
                        <div class="d-flex justify-content-between py-2">
                            <p class="m-0" style="font-size: 12px;"><strong>Charges :</strong> <?php echo $pricing;?>
                            </p>
                            <?php if($rows["pDiscount"] != ""){?>
                            <p class="m-0" style="font-size: 12px;"><strong>Discount :</strong>
                                <?php echo $rows["pDiscount"];?></p>
                            <?php }?>
                            <p class="m-0" style="font-size: 12px;"><strong>Paied :</strong>
                                <?php echo $total_payment;?></p>
                            <?php
                            $pending = floatval($pricing) - floatval($total_payment) - floatval($rows["pDiscount"]);
                            ?>
                            <p class="m-0" style="font-size: 12px;"><strong>Pending :</strong> <?php echo $pending;?>
                            </p>
                        </div>
                        <?php
                        // Ensure all variables are cast to float to avoid type issues
                        $pricing = floatval($pricing);
                        $total_payment = floatval($total_payment);
                        $pDiscount = floatval($rows["pDiscount"]);

                        if ($pricing > $total_payment + $pDiscount) { ?>
                        <div class="mt-0">
                            <label for="discount" class="small">Discount</label>
                            <form action="discount-submit.php" method="POST" class="d-flex">
                                <input type="text" class="form-control form-control-sm" name="discount"
                                    value="<?php echo $rows["pDiscount"]; ?>">
                                <input type="hidden" name="productId" value="<?php echo $rows['pid']; ?>">
                                <button type="submit" class="btn btn-primary btn-sm"
                                    name="discountSubmit">Submit</button>
                            </form>
                        </div>
                        <?php } ?>
                    </div>
                </div>
            </div>

            <div class='col-md-3 col-12'>
                <form action="" mehod="POST">
                    <div class="d-flex justify-content-between mb-2">
                        <div>
                            <label for="status" class="small">Status</label>
                            <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>
                            <label for="employee" class="small">Assigned Employee</label>
                            <select name="employee" class="form-control form-control-sm" id="pemployee"
                                onchange="updateEmployee(<?php echo $rows['pid']; ?>, this.value)">
                                <?php if(!empty($employee_name)){?>
                                <option value="<?php echo $rows['pEmployee'];?>"><?php echo $employee_name;?></option>
                                <?php }else{?>
                                <option value="">Select Employee</option>
                                <?php }?>
                                <?php 
                                    $esql = "SELECT DISTINCT uname, uid FROM users WHERE utype = 'Employee' AND udisplay != 'disable' AND admin_ref = '$_SESSION[uref]' ORDER BY uname ASC";
                                    $eres = mysqli_query($con, $esql);
                                    while ($erow = mysqli_fetch_assoc($eres)) {
                                ?>
                                <option value="<?php echo $erow['uid']; ?>"><?php echo $erow['uname']; ?></option>
                                <?php } ?>
                            </select>
                        </div>
                    </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 Product
                        </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>