
<?php
/* Advance delete feature patch
   Add this logic inside advances.php
*/

if(isset($_POST['delete_advance'])){

    $advanceId = (int)$_POST['advance_id'];

    // check settlements
    $check = $pdo->prepare("
        SELECT COUNT(*)
        FROM advance_settlements
        WHERE advance_id=?
    ");
    $check->execute([$advanceId]);

    if($check->fetchColumn() > 0){

        $err = "لا يمكن حذف العهدة لأنه تم تسجيل تسويات عليها";

    }else{

        $del = $pdo->prepare("
            DELETE FROM advances
            WHERE id=? AND company_id=?
        ");

        $del->execute([$advanceId,$cid]);

        $msg = "تم حذف العهدة بنجاح";

    }
}
?>

<!-- Button inside advances table -->

<button class="btn btn-sm btn-danger delete-advance"
        data-id="<?= $row['id'] ?>">
حذف
</button>


<!-- Delete Modal -->

<div class="modal fade" id="deleteAdvanceModal">
<div class="modal-dialog">
<div class="modal-content">

<div class="modal-header">
<h5 class="modal-title">حذف العهدة</h5>
</div>

<div class="modal-body">
هل أنت متأكد من حذف هذه العهدة؟
</div>

<div class="modal-footer">
<button class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>

<form method="post">
<input type="hidden" name="advance_id" id="deleteAdvanceId">
<button class="btn btn-danger" name="delete_advance">
حذف
</button>
</form>

</div>

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


<script>

document.querySelectorAll(".delete-advance").forEach(btn => {

btn.addEventListener("click", function(){

document.getElementById("deleteAdvanceId").value = this.dataset.id;

new bootstrap.Modal(
document.getElementById("deleteAdvanceModal")
).show();

});

});

</script>
