<?php include '../header.php'; ?> 
<?php include '../sidemenu.php'; ?> 

<style>
    #myTable tbody tr:hover {
        background-color: #f1f1f1;
        cursor: pointer;
    }
</style>

<div class="page-header d-print-none">
    <div class="container-xl">
        <div class="row g-2 align-items-center">
            <div class="col d-flex justify-content-between">
                <h2 class="page-title">Purchase</h2>
            </div>
        </div>
    </div>
</div>

<div class="page-body">
    <div class="container-xl">
        <div class="row row-cards">
            <div class="col-12">


                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-4 mb-3 row">
                                <label class="col-4 col-form-label text-end">Date</label>
                                <div class="col">
                                    <input type="text" class="flatpickr flatpickr-input active form-control" id="date" required>
                                </div>
                            </div>
                            <div class="col-4 mb-3 row">
                                <label class="col-4 col-form-label text-end">Voucher No.</label>
                                <div class="col">
                                    <input type="text" id="voucherNo" class="form-control" placeholder="Enter voucher number" >
                                </div>
                            </div>
                            <div class="col-4 mb-3 row">
                                <label class="col-4 col-form-label text-end">Supplier</label>
                                <div class="col">
                                    <input type="text" id="supplier" class="form-control" placeholder="Enter supplier" >
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="myTable" class="table card-table table-vcenter text-nowrap datatable">
                                <thead>
                                    <tr>
                                        <th>Category</th>
                                        <th>Type</th>
                                        <th>Item Code</th>
                                        <th>Item Name</th>
                                        <th>Capital Price</th>
                                        <th class="w-1"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Item Selection Form -->
                    <form id="frmEntry">
                    <div class="container">
                        <div class="row">
                            <!-- Item Code -->
                            <div class="col-3 mb-3">
                                <label for="itemCode" class="form-label">Item Code</label>
                                <input type="text" id="itemCode" class="form-control" placeholder="Enter item code" disabled>
                            </div>

                            <!-- Item Name -->
                            <div class="col-3 mb-3">
                                <label for="itemName" class="form-label">Item Name</label>
                                <input type="text" id="itemName" class="form-control" placeholder="Enter item name" disabled>
                            </div>
                            <div class="col-1 mb-3"></div>
                            <!-- Quantity -->
                            <div class="col-2 mb-3">
                                <label for="quantity" class="form-label">Quantity</label>
                                <input type="number" id="quantity" class="form-control" value="1" min="1" oninput="validateInput(this)" required>
                            </div>

                            <!-- Price -->
                            <div class="col-2 mb-3">
                                <label for="price" class="form-label">Price</label>
                                <input type="text" id="price" class="form-control" placeholder="Enter price" oninput="validateInput(this)" required>
                            </div>

                            <!-- Add Button -->
                            <div class="col-1 mb-3">
                                <div class="col text-end">
                                    <label for="" class="form-label">&nbsp;</label>
                                    <button type="button" id="btnAdd" class="btn btn-outline-success" onclick="addItem()">Add</button>
                                </div>
                            </div>
                        </div>
                        <!-- <div class="row">
                            <div class="col text-end">
                                <button type="button" id="btnAdd" class="btn btn-outline-success" onclick="addItem()">Add</button>
                            </div>
                        </div> -->
                    </div>


                        <div class="mb-3 mt-3 table-responsive" style="max-height: 400px; overflow-y: auto;">
                            <table class="table table-vcenter card-table" id="stockTable">
                                <thead style="position: sticky; top: 0; z-index: 10;">
                                    <tr>
                                        <th>Category</th>
                                        <th>Type</th>
                                        <th>Item Code</th>
                                        <th>Item Name</th>
                                        <th class="text-end">Quantity</th>
                                        <th class="text-end">Capital Price</th>
                                        <th class="text-end">Amount</th>
                                        <th class="w-1"></th>
                                    </tr>
                                </thead>
                                <tbody class="stay-grid">
                                </tbody>
                            </table>
                        </div>
                        <div class="row">
                            <div class="col-4 mb-3 row offset-8">
                                <label class="col-4 col-form-label text-end">Total</label>
                                <div class="col">
                                    <input type="text" id="txtTotalAmount" class="form-control text-end" placeholder="Enter total " disabled>
                                </div>
                            </div>
                            <div class="col-2 mb-3 row offset-10">
                                <label class="col-4 col-form-label text-end"></label>
                                <div class="col d-flex justify-content-end">
                                    <button type="button" id="btnAdd" class="btn btn-outline-success" onclick="purchase()">Purchase</button>
                                </div>
                            </div>
                        </div>
                    </form>

                    <!-- Sales Table -->
                    


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

<?php include '../footer.php'; ?>

<script>
let selectedRowData = null;

var today = new Date().toISOString().split('T')[0];

$(function() {
    $("input[type='number']").on("input", function() {
        this.value = this.value.replace(/[^0-9]/g, ''); 
    });
    getAll();
    flatpickr("#date", {
        dateFormat: "Y-m-d", 
        defaultDate: today,  
        maxDate: today,      
    });
    getStockList();

});

function getAll() {
    $('#myTable').DataTable().destroy();
    let table = $('#myTable').DataTable({
        ajax: {
            url: APP_URL + "api/item/get_all_rows_datatable.php",
            method: "GET",
            dataType: "json",
            dataSrc: 'records' 
        },
        columns: [
            { data: 2 }, 
            { data: 4 },
            { data: 5 }, 
            { data: 6 }, 
            { data: 7 }, 
            { 
                data: null, 
                render: function(data, type, row) {
                    return "";
                }
            }
        ],
        paging: true,
        language: {
            emptyTable: "No records found",
            info: "Showing _START_ to _END_ of _TOTAL_ entries",
            lengthMenu: "Show _MENU_ entries",
            search: "Search:",
            zeroRecords: "No records found"
        }
    });

    $('#myTable tbody').on('click', 'tr', function() {
        $('#myTable tbody tr').removeClass('selected');
        $(this).addClass('selected');
        var table = $('#myTable').DataTable();
        selectedRowData = table.row(this).data();

        if (selectedRowData) {
            $("#itemCode").val(selectedRowData[4]);
            $("#itemName").val(selectedRowData[5]);
            $("#price").val(selectedRowData[7]);

        }
    });
}

function addItem (){
    if (!selectedRowData) {
        showAlert("Please select an item from the table before adding.", "warning");
        return;
    }
    var quantity = $("#quantity").val();
    var price = $("#price").val();
    $("#stockTable").find("tbody")
    .append($('<tr>')
        .append("<td>" + selectedRowData[2] + "</td>")
        .append("<td>" + selectedRowData[4] + "</td>")
        .append("<td>" + selectedRowData[5] + "</td>")
        .append("<td>" + selectedRowData[6] + "</td>")
        .append("<td style='text-align:right;'>" + quantity + "</td>")
        .append("<td style='text-align:right;'>" + price + "</td>")
        .append("<td style='text-align:right;padding-right:20px;'>" + quantity * parseFloat(price).toLocaleString() + "</td>")
        .append("<td><button type='button' class='btn btn-outline-danger btn-sm'  onclick='$(this).parent().parent().remove();calculate();order();'>Remove</button></td>")
    );
    calculate();
}

function calculate() {
    var total_amount = 0;
    $("#stockTable tbody tr").each(function () {
        var amount = $(this).find("td").eq(6).text();
        if (amount) {
            total_amount += parseFloat(amount.replace(/,/g, ''));
        }
    });
    $("#txtTotalAmount").val(total_amount.toLocaleString());

    if ($("#stockTable tbody tr").length === 0) {
        $("#txtTotalAmount").val("0");
    }
}

function purchase(){

    var purchase_details = [];
    $("#stockTable tbody tr").each(function (){
        var purchase_detail = {
            "item_code" : ($(this).find("td").eq(2).text()),
            "item_name" : ($(this).find("td").eq(3).text()),
            "quantity" : ($(this).find("td").eq(4).text()),
            "price" : $(this).find("td").eq(5).text().replace(/,/g, '')
        }
        purchase_details.push(purchase_detail);
    });
    var purchase = {
        "date":$("#date").val(),
        "voucher_no":$("#voucherNo").val(),
        "supplier":$("#supplier").val(),
        "purchase_details":purchase_details
    };
    if($("#date").val() == "" || $("#voucherNo").val() == ""){
        showAlert("Please fill voucher no.","warning");
    }else if( $("#myTable tbody tr").length==0){
        showAlert("Please fill Purchase Details.","warning");
    }else{

        if (!selectedRowData) {
            showAlert("Please select an item from the table before adding.", "warning");
            return;
        }

        $.ajax({
            url: APP_URL + "api/purchase/create.php",
            type: "POST",
            data: JSON.stringify(purchase)
        }).done(function(data) {
            console.log(data);
            if(data.message=="created"){
                showAlert("Purchase Complete.","success");
                $("#txtVoucher").val('');
                $("#supplier").val('');
                $("#txtTotalAmount").val('');
                $("#stockTable tbody tr").remove();
            }else if(data.message=="duplicate"){
                showAlert("Voucher No. is duplicate.","warning");
            }else{
                showAlert("Error on server side.","warning");
            }
        });
    }

}

// $('#date').on('change',function(){
//     getStockList();
// });

// function getStockList(){
// 		var stock_in_date = $("#date").val();
// 		$.ajax({
// 			url: APP_URL + "api/stock/in/get_all_rows.php",
// 			type: "POST",
// 			data: JSON.stringify({ stock_in_date: stock_in_date })
// 		}).done(function(data){
// 			$("#stockTable").find("tbody").find("tr").remove();
// 			if(data.records){$("#total_records").text(" - " + data.records.length + " record(s) found.");}else{$("#total_records").text(0 + " record(s) found.");}
// 			$.each(data.records, function(i, v) {
// 				console.log(v);
// 				$("#stockTable").find("tbody")
// 				.append($('<tr>')
// 					.append("<td style='width: 10px' class='order'>" + (i+1) + "</td>")
// 					.append("<td>" + v.stock_in_date + "</td>")
// 					.append("<td>" + v.voucher_no + "</td>")
// 					.append("<td>" + v.item_code + "</td>")
// 					.append("<td>" + v.item_name + "</td>")
// 					.append("<td style='text-align:right;'>" + v.quantity + "</td>")
// 					.append("<td style='text-align:right;'>" + parseFloat(v.price).toLocaleString() + "</td>")
// 					.append("<td><button type='button' class='btn btn-outline-danger btn-sm' onclick='del(" + v.id + ",this)' >Delete</button></td>")
// 				)
// 			});
//         });
// 	}

//     function del(id, obj) {
// 		Swal.fire({
// 			title: 'Are you sure?',
// 			text: 'Do you really want to delete this item?',
// 			icon: 'warning',
// 			showCancelButton: true,
// 			confirmButtonText: 'Yes, delete it!',
// 			cancelButtonText: 'No, keep it',
// 			customClass: {
// 				confirmButton: 'btn-danger',
// 				cancelButton: 'btn-primary'
// 			},
// 			reverseButtons: true
// 		}).then((result) => {
// 			if (result.isConfirmed) {
// 				$.ajax({
// 					type: "POST",
// 					url: APP_URL + "api/stock/in/delete.php",
// 					data: JSON.stringify({ id: id }),
// 					success: function(data) {
// 						if (data == "deleted") {
// 							getStockList();
// 						} else {
// 							Swal.fire('Error!', 'Error on server side.', 'error');
// 						}
// 					}
// 				});
// 			}
// 		});
// 	}

function showAlert(message, type) {
      Swal.fire({
          title: type === 'success' ? 'Success' : 'Error',
          text: message,
          icon: type
      });
  }

    </script>
