<?php include '../header.php'; ?> 
<?php include '../sidemenu.php'; ?> 
<style>
.table-responsive {
    overflow: visible !important;
}

.dropdown {
    position: relative !important;
}

</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">Investor</h2>
                <button class="btn btn-outline-success" id="btnCreateNew">New Investor</button>
            </div>
        </div>
    </div>
</div>

<div class="container" id="alertContainer1"></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>Name</th>
                                        <th>Position</th>
                                        <th>Phone</th>
                                        <th>Email</th>
                                        <th>NRC</th>
                                        <th>Address</th>
                                        <th>Total Investment</th>
                                        <th class="w-1"></th>
                                    </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="createEntryModal" tabindex="-1" aria-labelledby="createEntryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createEntryModalLabel">Investor Entry</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="container" id="alertContainer2"></div>
            <div class="modal-body">
                <form id="createEntryForm">
                    <input type="hidden" class="form-control" id="investorId">
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Name</label>
                        <div class="col">
                        <input type="text" id="name" class="form-control" placeholder="Enter name">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Position</label>
                        <div class="col">
                        <input type="text" id="position" class="form-control" placeholder="Enter position">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Phone</label>
                        <div class="col">
                        <input type="text" id="phone" class="form-control" placeholder="Enter phone">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Email</label>
                        <div class="col">
                        <input type="email" id="email" class="form-control" placeholder="Enter email">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">NRC</label>
                        <div class="col">
                        <input type="text" id="nrc" class="form-control" placeholder="Enter nrc">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Address</label>
                        <div class="col">
                        <textarea id="address" class="form-control" placeholder="Enter address" data-bs-toggle="autosize"></textarea>
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" id="btnSave" class="btn btn-outline-success" onclick="validateAndSave()">Create</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="investmentModal" tabindex="-1" aria-labelledby="investmentModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="investmentModalLabel">Investment</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="investmentForm">
                    <div class="mb-3">
                        <label for="date" class="form-label">Date</label>
                        <input type="text" class="form-control" id="date" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                    <div class="mb-3">
                        <label for="amount" class="form-label">Amount</label>
                        <input type="number" class="form-control" id="amount" required>
                    </div>
                </form>
                <div class="mb-5 table-responsive" style="overflow-y: auto;height: 200px;">
                    <table class="table table-vcenter card-table" id="investmentTable">
                        <thead style="position: sticky; top: 0; z-index: 10;">
                            <tr>
                                <th>Date</th>
                                <th>Amount</th>
                                <th class="w-1"></th>
                            </tr>
                        </thead>
                        <tbody class="stay-grid">
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="confirmInvestment">Submit</button>
            </div>
        </div>
    </div>
</div>
 
<?php include '../footer.php'; ?>

<script>
$(function() {
    $("input[type='number']").on("input", function() {
        this.value = this.value.replace(/[^0-9]/g, ''); // Remove non-numeric characters
    });
    getAll();
});


function getAll() {
    $('#myTable').DataTable().destroy();
    let table = $('#myTable').DataTable({
        ajax: {
            url: APP_URL + "api/investor/get_all_rows_datatable.php",
            method: "GET",
            dataType: "json",
            dataSrc: 'records' 
        },
        columns: [
            { data: 1 }, 
            { data: 2 },
            { data: 3 }, 
            { data: 4 }, 
            { data: 5 }, 
            { data: 6 }, 
            { data: 7 }, 
            { 
                data: null, 
                render: function(data, type, row) {
                    return `
                        <div class="btn-group">
                            <button type="button" class="btn btn-outline-primary btn-sm dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                                Actions
                            </button>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item" href="#" onclick="investment('${row[0]}')">Investment</a></li>
                                <li><a class="dropdown-item" href="#" onclick="edit('${row[0]}')">Edit</a></li>
                                <li><a class="dropdown-item text-danger" href="#" onclick="del('${row[0]}', this)">Delete</a></li>
                            </ul>
                        </div>
                    `;
                }
            }

        ],
        paging: true,
        scrollX: true,
        language: {
            emptyTable: "No records found",
            info: "Showing _START_ to _END_ of _TOTAL_ entries",
            lengthMenu: "Show _MENU_ entries",
            search: "Search:",
            zeroRecords: "No records found"
        }
    });
}

$("#btnCreateNew").click(function() {
    // $("#createEntryForm").trigger("reset");
    $("#investorId").val("");
    $("#name").prop("disabled", false);
    $('#createEntryModal').modal('show');
    $("#btnSave").text("Create").removeClass("btn-outline-primary").addClass("btn-outline-success");
});


function validateAndSave() {

    let isValid = true;

    $("#name").removeClass("is-invalid");
    $("#position").removeClass("is-invalid");

    if ($("#name").val() === null || $("#name").val().trim() === "") {
        $("#name").addClass("is-invalid");
        isValid = false; 
    }

    if ($("#position").val() === null || $("#position").val().trim() === "") {
        $("#position").addClass("is-invalid");
        isValid = false;
    }

    if (isValid) {

        // $(this).prop("disabled", true).text("Loading...");

        var room_entry = {
            "id": $("#investorId").val(),
            "name": $("#name").val(),
            "position": $("#position").val(),
            "phone": $("#phone").val(),
            "email": $("#email").val(),
            "nrc": $("#nrc").val(),
            "address": $("#address").val(),
        };

        $.ajax({
            type: "POST",
            url: APP_URL + "api/investor/create_update.php",
            data: JSON.stringify(room_entry),
            success: function(data) {
                if (data.message === "created" || data.message === "updated") {
                    $('#createEntryModal').modal('hide');
                    $("#name").val("");
                    showAlert("Investor " + (data.message === "created" ? "Created" : "Updated") + " Successfully!", "success");
                    getAll();
                } else if (data.message === "duplicate") {
                    showAlert("Name already exists!", "warning");
                } else {
                    showAlert("An error occurred on the server!", "error");
                }
            },
            error: function() {
                showAlert("An error occurred while saving!", "error");
            },
            complete: function() {
                // $("#btnSave").prop("disabled", false).text(button.innerText);
            }
        });
    }
}



function edit(id) {
    $("#createEntryForm").trigger("reset");
    $("#btnSave").text("Update").removeClass("btn-outline-success").addClass("btn-outline-primary");
    $('#createEntryModal').modal('show');
    $("#investorId").val(id);
    $.ajax({
        url: APP_URL + "api/investor/get_one_row.php",
        type: "POST",
        data: JSON.stringify({ id: id })
    }).done(function(data) {
        if (data) {
            $("#name").prop("disabled", true);
            $("#name").val(data.name);
            $("#position").val(data.position); 
            $("#phone").val(data.phone);
            $("#email").val(data.email);
            $("#nrc").val(data.nrc);
            $("#address").val(data.address);
        } else {
            console.log(data);
        }
    });
}

function del(id, obj) {
    $('#modal-delete').modal('show');
    $('#confirm-delete').off('click').on('click', function() {
        // $(this).prop("disabled", true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Deleting...');

        $.ajax({
            type: "POST",
            url: APP_URL + "api/investor/delete.php",
            data: JSON.stringify({ id: id }),
            success: function(data) {
                if (data.message === "deleted") {
                    getAll();
                    // $(obj).closest("tr").remove();
                    showAlert("Investor Deleted Successfully!", "success");
                } else {
                    showAlert("An error occurred on the server!", "error");
                }
            },
            error: function() {
                showAlert("An error occurred while saving!", "error");
            },
            complete: function() {
                $('#modal-delete').modal('hide');
                // $('#confirm-delete').prop("disabled", false).text("Delete");
            }
        });
    });
}

    function investment(id) {
        $('#investorId').val(id);
        getInvestment();
        $('#investmentModal').modal('show');
    }

    $('#confirmInvestment').click(function() {
        var investor_id = $('#investorId').val();
        var date = $('#date').val();
        var amount = $('#amount').val();
        
        if (amount && amount > 0) {
            $.ajax({
                type: "POST",
                url: APP_URL + "api/investment/create.php",
                data: JSON.stringify({ 
                    investor_id: investor_id, 
                    date: date, 
                    amount: amount 
                }),
                success: function(data) {
                    if (data === "created") {
                        showAlert("Investment added successfully!", "success");
                        $('#investmentModal').modal('hide'); // Hide the modal after success
                        getAll();
                    } else {
                        showAlert("An error occurred while processing investment.", "error");
                    }
                },
                error: function() {
                    showAlert("An error occurred while saving investment.", "error");
                }
            });
        } else {
            showAlert("Please enter a valid amount.", "warning");
        }
    });

    function getInvestment(id){
        var investor_id = $('#investorId').val();
        $("#investmentTable").find("tbody").find("tr").remove();
        $.ajax({
            url: APP_URL + "api/investment/get_all_rows.php",
            type: "POST",
            data: JSON.stringify({ investor_id: investor_id })
        }).done(function(data) {
            console.log(data);
            $.each(data.records, function(i, v) {
                console.log(v);
                $("#investmentTable").find("tbody")
                .append($('<tr>')
                    .append("<td>" + v.date + "</td>")
                    .append("<td>" + v.amount + "</td>")
                    .append("<td><button type='button' class='btn btn-outline-danger btn-sm remove-btn' onclick='delInvestment(" + v.id + ", this)'>Remove</button></td>")
                    // .append("<td><button type='button' class='btn btn-block btn-danger btn-sm' onclick='delDeposit(" + v.id + ", this)' style='padding: 0px 10px;font-size: 20px; min-width: 35px'>&times;</button></td>")
                    )
            });
            calculate();
        });
    }

    function delInvestment(id) {
        Swal.fire({
            title: 'Are you sure?',
            text: `You are about to delete investment`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    type: "POST",
                    url: APP_URL + "api/investment/delete.php",
                    data: JSON.stringify({ id: id }),
                    success: function(data) {
                        if (data=== "deleted") {
                            getInvestment();
                            getAll();
                            showAlert("Investment Deleted Successfully!", "success");
                        } else {
                            showAlert("An error occurred on the server!", "error");
                        }
                    },
                    error: function() {
                        showAlert("An error occurred while saving!", "error");
                    }
                });
            }
        });
    }

function showAlert(message, type) {
    Swal.fire({
        title: type === 'success' ? 'Success!' : 'Oops!',
        text: message,
        icon: type,
        timer: 1000,
        timerProgressBar: true, 
        willClose: () => {
            console.log('Alert closed');
        }
    });
}
</script>
