<?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">Stock In</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="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">
                                <!-- Date Input -->
                                <div class="col-3 mb-3">
                                    <label for="date" class="form-labe">Date</label>
                                    <input type="text" class="flatpickr form-control" id="date" required>
                                </div>

                                <!-- Store Dropdown -->
                                <div class="col-3 mb-3">
                                    <label for="store" class="form-labe">Store</label>
                                    <select class="form-select" id="store" name="store" required>
                                        <option value="" disabled selected>Select a store</option>
                                    </select>
                                </div>
                                <div class="col-2 mb-3"></div>
                                <!-- Quantity and Price -->
                                <div class="col-2 mb-3">
                                    <label class="form-labe">Quantity</label>
                                    <div class="d-flex">
                                        <input type="number" id="quantity" class="form-control me-2" value="1" min="1" oninput="validateInput(this)" required>
                                    </div>
                                </div>

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

                                <!-- Add Button -->
          
                            </div>
                            <div class="row">
                                <div class="col text-end">
                                    <button type="button" id="btnAdd" class="btn btn-outline-success" onclick="addItem()">Stock In</button>
                                </div>
                            </div>
                        </div>
                    </form>


                    <!-- Sales Table -->
                                                <!-- <div class="col-3 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>
                <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>#</th>
                                <th>Date</th>
                                <th>Store</th>
                                <th>Item Code</th>
                                <th>Item Name</th>
                                <th class="text-end">Quantity</th>
                                <th class="text-end">Capital Price</th>
                                <th class="w-1"></th>
                            </tr>
                        </thead>
                        <tbody class="stay-grid">
                        </tbody>
                    </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, ''); 
    });
    getStoreList();
    getAll();
    flatpickr("#date", {
        dateFormat: "Y-m-d", 
        defaultDate: today,  
        maxDate: today,      
    });
    getStockList();

});

function getStoreList(){
    $.ajax({
        url: APP_URL + "api/store/get_store_list.php"
    }).done(function(data) {
        $("#store").find("option").remove();
        $("#store").append("<option value = '' data-id = ''>Select a store</option>");
        $.each(data.records, function(i, v) {
            console.log(v);
            $("#store").append("<option value= '" + v.store + "' data-id = '"+ v.id +"' >" + v.store + "</option>");
        });
    });
}

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) {
            $("#price").val(selectedRowData[7]);
        }
    });
}

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

    var stock_in_date = $("#date").val();
    var voucher_no = "";
    var store = $("#store").val();
    let item_code = selectedRowData[5];
    let item_name = selectedRowData[6];
    var quantity = $("#quantity").val();
    var price = $("#price").val();

    if (store == null || store=="") {
        showAlert("Select a store.", "warning");
        return;
    }

    if (isNaN(quantity) || quantity <= 0) {
        showAlert("Please enter a valid quantity.", "warning");
        return;
    }

    $.ajax({
        type: "POST",
        url: APP_URL + "api/stock/in/create.php",
        data: JSON.stringify({ stock_in_date: stock_in_date, voucher_no: voucher_no, store: store, item_code: item_code, item_name: item_name, quantity: quantity, price: price}),
        success: function(data){
            console.log(data);
            if(data=="created"){
                getStockList();
                showAlert("Stock in created", "success");
                // $("#frmEntry")[0].reset();
                // $("#date").val(today);
            }else if(data=="updated"){
                showAlert("Stock in updated", "success");
                // $("#frmEntry")[0].reset();
            }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.store + "</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;'>" + parseInt(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>
