<?php include('inc/template.php');?>

<div class="container-fluid flex-grow-1 container-p-y">
<nav aria-label="breadcrumb">
	<ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="index.php">Home</a></li>
    <li class="breadcrumb-item active">Sales Master</li>
    </ol>
</nav>
    <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#basicModal">
        <span class="ti-xs ti ti-plus me-1"></span> Add New Sales
    </button>
    <div class="row mb-4">
                <!--  Modal -->
        <div class="modal fade" id="basicModal" tabindex="-1" aria-labelledby="basicModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <form id="salesForm">
                        <div class="modal-header">
                            <h5 class="modal-title" id="basicModalLabel">Sales Form</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <input type="hidden" id="role" name="role" value="sales" />

                            <!-- Name -->
                            <div class="row">
                                <div class="col mb-3">
                                    <label for="name" class="form-label">Name</label>
                                    <input type="text" id="name" name="name" class="form-control" placeholder="Enter Full Name" required />
                                </div>
                            </div>

                            <!-- Phone -->
                            <div class="row">
                                <div class="col mb-3">
                                    <label for="mobile" class="form-label">Mobile</label>
                                    <input type="tel" id="phone" name="phone" class="form-control" placeholder="Enter Mobile Number" pattern="\d{10}" maxlength="10" required />
                                </div>
                            </div>

                            <!-- Email -->
                            <div class="row">
                                <div class="col mb-3">
                                    <label for="email" class="form-label">Email</label>
                                    <input type="email" id="email" name="email" class="form-control" required />
                                </div>
                            </div>
							
							
                            <!-- Username -->
                            <div class="row">
                                <div class="col mb-3">
                                    <label for="username" class="form-label">Username</label>
                                    <input type="text" id="username" name="username" class="form-control" required />
                                </div>
                            </div>

                            <!-- Password -->
                            <div class="row" id="passwordContainer">
                                <div class="col mb-3">
                                    <div class="form-password-toggle">
                    <label for="password" class="form-label">Password</label>
                    <div class="input-group input-group-merge">
                        <input type="password" id="password" name="password" class="form-control" placeholder="Enter Password" 
                            maxlength="20" required />
                        <span class="input-group-text cursor-pointer" id="togglePassword">
                            <i class="ti ti-eye-off"></i>
                        </span>
                    </div>
                </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <input type="hidden" name="id" id="id" />
                            <input type="hidden" name="action" id="action" value="Create" />
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary">Save Changes</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Users Table -->
        <div class="col-xl-12 col-lg-6 col-md-6">
            <div class="card">
                <div class="card-datatable table-responsive pt-0">
                    <table class="datatables-ajax table table-bordered table-responsive">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Mobile</th>
                                <th>Email</th>
                                <th>Username</th>
								<th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $result = mysqli_query($conn, "SELECT * FROM users WHERE role = 'sales' ORDER BY id ASC");
                            while ($row = mysqli_fetch_array($result)) {
                            ?>
                            <tr class="showtr">
                                <td><?php echo htmlspecialchars($row['name']); ?></td>
                                <td><?php echo htmlspecialchars($row['phone']); ?></td>
                                <td><?php echo htmlspecialchars($row['email']); ?></td>
                                <td><?php echo htmlspecialchars($row['username']); ?></td>
								
                                <td>
                                    <label class="switch">
                                        <input type="checkbox" class="switch-input" value="<?php echo $row[0]; ?>"
                                               <?php if ($row['status'] == 'active') echo "checked"; ?>
                                               onClick="statusChange(this.value);" />
                                        <span class="switch-toggle-slider">
                                            <span class="switch-on"></span>
                                            <span class="switch-off"></span>
                                        </span>
                                    </label>
                                </td>
                                <td>
									
									<button type="button" id="<?php echo $row[0]; ?>" class="btn btn-xs btn-warning update"><i class="far fa-edit"></i></button>
                   				 <button type="button" id="<?php echo $row[0]; ?>" class="btn btn-xs btn-danger delete"><i class="far fa-trash-alt"></i></button>
                                   
                                </td>
                            </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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

    // Show modal for Create
    $('#modal_button').click(function () {
        $('#salesForm')[0].reset();
        $('.modal-title').text("Create New Record");
        $('#action').val('Create');
        $('#id').val('');
        $('#passwordContainer').show();
        $('#password').attr('required', true);
        $('#basicModal').modal('show');
    });

    // Show modal for Update
    $(document).on('click', '.update', function () {
        const id = $(this).attr("id");
        $.ajax({
            url: "controller/SalesController.php",
            method: "POST",
            data: { id: id, action: 'Select' },
            dataType: "json",
            success: function (data) {
                $('#name').val(data.name);
                $('#phone').val(data.phone);
                $('#email').val(data.email);
                $('#username').val(data.username);
                $('#role').val(data.role);
                $('#id').val(id);
                $('#action').val('Update');
                $('.modal-title').text("Update Record");
                $('#passwordContainer').hide();
                $('#password').removeAttr('required');
                $('#basicModal').modal('show');
            },
            error: function () {
                toastr.error('Error fetching data.');
            }
        });
    });

    // Submit form for Create or Update
    $('#salesForm').on('submit', function (e) {
        e.preventDefault();

        const formData = {
            name: $('#name').val(),
            phone: $('#phone').val(),
            email: $('#email').val(),
            username: $('#username').val(),
            password: $('#password').val(),
            role: $('#role').val(),
            action: $('#action').val(),
            id: $('#id').val()
        };

        if (formData.name && formData.phone && formData.email && formData.username) {
            $.ajax({
                url: "controller/SalesController.php",
                method: "POST",
                data: formData,
                dataType: "json",
                success: function (response) {
                    $('#basicModal').modal('hide');
                    if (response.status === 'success') {
                        toastr.success(response.message);
                        //setTimeout(() => location.reload(), 1500);
                    } else {
                        toastr.error(response.message);
                    }
                },
                error: function () {
                    toastr.error('Error processing request.');
                }
            });
        } else {
            toastr.error("Please fill all required fields.");
        }
    });

    // Prevent space in password
    window.AvoidSpace = function (event) {
        return (event.which !== 32);
    }

    // Status change
    window.statusChange = function (id) {
        $.ajax({
            url: 'controller/SalesController.php',
            method: 'POST',
            data: { id: id, action: 'ToggleStatus' },
            dataType: "json",
            success: function (response) {
                if (response.status === 'success') {
                    const newStatus = response.new_status === "active" ? "Active" : "Inactive";
                    toastr.success(`Status changed to ${newStatus}`);
                } else {
                    toastr.error(response.message);
                }
            },
            error: function () {
                toastr.error('Failed to update status.');
            }
        });
    };

    // Delete user
    $(document).on('click', '.delete', function () {
        const id = $(this).attr("id");
        const row = $(this).closest('tr');

        if (confirm('Are you sure you want to delete this admin?')) {
            $.ajax({
                url: 'controller/SalesController.php',
                method: 'POST',
                data: { id: id, action: 'Delete' },
                dataType: "json",
                success: function (response) {
                    if (response.status === 'success') {
                        toastr.success(response.message);
                        row.css('background-color', '#f8d7da').fadeOut(800, function () {
                            $(this).remove();
                        });
                    } else {
                        toastr.error(response.message);
                    }
                },
                error: function () {
                    toastr.error('Error deleting user.');
                }
            });
        }
    });

});
</script>


<?php include('inc/footer.php');?>