<?php
include('../db/model.php');
include('../config/config.php');
$db = new Model();

$event = null;
$assignedEmp = null;
$empList = $db->EmployeeList(true);

if (isset($_POST["type"])) {

    if (isset($_POST['id'])) {
        $id = (int)$_POST['id'];
        if (is_numeric($id) && $id > 0 && $id != '' && $id != null) {
            $event = $db->GetEventById($id);
            $assignedEmp = $db->GetAssignedEmpByEventId($id);
        }
    }

    if ($_POST["type"] == "get_emp") {
        $id = (int)$_POST['emp_id'];
        if (is_numeric($id) && $id > 0 && $id != '' && $id != null) {
            $emp = $db->GetEmpById($id);
            header('Content-Type: application/json');
            echo json_encode($emp);
        }
        exit();
    }

    if ($_POST["type"] == "assign") {
        try {
            $result = $db->AssignEmployee($_POST);

            if ($result) {
                header('Content-Type: application/json');
                echo json_encode([
                    'result' => true,
                    'message' => 'Employees assigned successfully!'
                ]);
            } else {
                header('Content-Type: application/json');
                echo json_encode([
                    'result' => false,
                    'message' => 'Error: Could not assign employees.'
                ]);
            }
        } catch (Exception $ex) {
            if (strpos($ex->getMessage(), 'duplicate entry') !== false) {
                header('Content-Type: application/json');
                echo json_encode([
                    'result' => false,
                    'message' => 'Error: Duplicate entry detected. This employee is already assigned.'
                ]);
            } else {
                header('Content-Type: application/json');
                echo json_encode([
                    'result' => false,
                    'message' => 'An unexpected error occurred: ' . $ex->getMessage()
                ]);
            }
        }
        exit();
    }



    if (isset($_POST['id']) && isset($_POST['eventId'])) {
        if ($_POST["type"] == "delete") {
            $db->DeleteAssignedEmployee($_POST['id'], $_POST['eventId']);
        }
        exit();
    }
}
?>

<style>
    #dataTable tbody td:nth-child(2),
    #dataTable tbody td:nth-child(3) {
        text-align: center;
    }
</style>


<div class="modal fade" id="modalModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="modalModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header text-center">
                <h1 class="modal-title fs-5 w-100" id="modalModalLabel">ASSIGN EMPLOYEE</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div id="custom-form-light">
                <div class="modal-body">

                    <input type="hidden" name="eventId" id="eventId" value="<?php echo ($event) ? $event['id'] : ""; ?>">

                    <div class="input-group mb-1">
                        <div class="col-12 col-sm-12 col-md-8 mb-1 pe-md-2">
                            <label for="mEventName">Event Name</label>
                            <input type="text" name="mEventName" id="mEventName" value="<?php echo ($event) ? $event['event_name'] . ' (' . $event['package_name'] . ')' : ""; ?>" class="form-control" readonly>
                        </div>

                        <div class="col-12 col-sm-12 col-md-4">
                            <label for="mEventDate">Event Date</label>
                            <input type="text" name="mEventDate" id="mEventDate" value="<?php echo ($event) ? sDate($event['event_date_time']) : ""; ?>" class="form-control" readonly>
                        </div>

                    </div>

                    <label>Employee</label>
                    <div class="input-group mb-1">
                        <div class="col-12 mb-1">
                            <select name="empList" id="empList" class="form-control">
                                <option value="">Select Employee</option>
                                <?php foreach ($empList as $row): ?>
                                    <option value="<?php echo $row['id']; ?>">
                                        <?php echo $row['full_name'].' ('.$row['designation'].')'; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="input-group mb-1">
                        <div class="col-12 col-md-8 mb-1 pe-md-2">
                            <label for="">Shift Payable</label>
                            <div class="input-group align-item-center">
                                <input type="number" name="shiftPayable" id="shiftPayable" class="form-control text-center">
                                <input type="number" name="totalShift" id="totalShift" class="form-control text-center" placeholder="1">
                                <input type="number" name="totalShiftPayable" id="totalShiftPayable" class="form-control text-center" readonly>
                            </div>
                        </div>
                        <div class="col-12 col-md-4">
                            <label for="">Editing Fee</label>
                            <input type="number" name="editingFee" id="editingFee" class="form-control text-center" placeholder="0">
                        </div>
                    </div>

                    <div class="input-group mb-2">
                        <div class="col-12 col-md-8 mb-1 pe-md-2">
                            <label for="">Extra Hour</label>
                            <div class="input-group align-item-center">
                                <input type="number" name="perHour" id="perHour" value="500" class="form-control text-center">
                                <input type="number" name="totalHour" id="totalHour" class="form-control text-center" placeholder="Total Hour">
                                <input type="number" name="extraHourPayable" id="extraHourPayable" class="form-control text-center" readonly>
                            </div>
                        </div>
                        <div class="col-12 col-md-4">
                            <label for="">Travel Cost</label>
                            <input type="number" name="travelCost" id="travelCost" class="form-control text-center" placeholder="0">
                        </div>
                    </div>


                    <div class="input-group mb-2">
                        <div class="col-12 col-md-8 mb-2 pe-md-2">
                            <div class="input-group">
                                <span class="input-group-text text-success">Total Payable</span>
                                <input type="number" name="totalPayable" id="totalPayable" class="form-control text-center text-success" readonly>
                            </div>
                        </div>
                        <div class="col-12 col-md-4">
                            <button class="btn action-btn form-control" id="assignEmployee" onclick="assignEmployee()"><i class="bi bi-plus-lg me-2"></i> Assign</button>
                        </div>
                    </div>

                    <div class="mt-4">
                        <div class="table-responsive">
                            <table id="dataTable" class="table table-sm table-dark table-hover table-bordered">
                                <thead style="color:var(--s-text-color);" class="mt-3">
                                    <th>Employee Name</th>
                                    <th style="width: 10px;">Payable Amount</th>
                                    <th style="max-width: 10px;">Action</th>
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<script>
    $(document).ready(function() {

        loadSelect2(['#empList'], '#modalModal');

        var tableEmp = $('#dataTable').DataTable({
            "paging": false,
            "lengthChange": false,
            "searching": false,
            "ordering": false,
            "info": false
        });
        
        var assignEmpList = <?php echo json_encode($assignedEmp ? $assignedEmp : []); ?>;
        assignEmpList.forEach(function(assign) {
            tableEmp.row.add([
                assign.full_name,
                assign.payable_amt,
                `<div class="btn-group">
                  <button class="btn btn-sm action-btn" onclick="DeleteAssign(${assign.id},${assign.event_id})">
                      <i class="bi bi-trash-fill"></i>
                  </button>
              </div>`
            ]).draw();
        });

        function calculateTotalShiftPayable() {
            var shiftPayable = parseInt($('#shiftPayable').val()) || 0;
            var totalShift = parseFloat($('#totalShift').val()) || 1;

            var totalShiftPayable = shiftPayable * totalShift;

            $('#totalShiftPayable').val(totalShiftPayable);
            calculateTotalPayable();
        }

        function calculateExtraHourPayable() {
            var hourPayable = parseInt($('#perHour').val()) || 0;
            var totalHour = parseFloat($('#totalHour').val()) || 0;

            var totalHourPayable = hourPayable * totalHour;

            $('#extraHourPayable').val(totalHourPayable);
            calculateTotalPayable();
        }

        function calculateTotalPayable() {
            var totalShiftPayable = parseInt($('#totalShiftPayable').val()) || 0;
            var extraHourPayable = parseInt($('#extraHourPayable').val()) || 0;
            var editingFee = parseInt($('#editingFee').val()) || 0;
            var travelCost = parseInt($('#travelCost').val()) || 0;

            var totalPayable = totalShiftPayable + extraHourPayable + editingFee + travelCost;

            $('#totalPayable').val(totalPayable);
        }

        $('#shiftPayable, #totalShift').on('input input', function() {
            calculateTotalShiftPayable();
        });

        $('#perHour, #totalHour').on('input input', function() {
            calculateExtraHourPayable();
        });

        $('#editingFee, #travelCost').on('input input', function() {
            calculateTotalPayable();
        });

        $("#empList").on('change', function() {
            var emp_id = $(this).val();

            $.ajax({
                type: "post",
                url: "modal_assign_emp.php",
                data: {
                    type: "get_emp",
                    emp_id: emp_id
                },
                success: function(response) {
                    $('#shiftPayable').val(response.salary);
                    calculateTotalShiftPayable();
                }
            });
        });
        calculateTotalShiftPayable();
        calculateExtraHourPayable();
        calculateTotalPayable();
    });
</script>