<?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"><a href="customer_add.php" data-bs-toggle="modal" data-bs-target="#basicModal">Customer Add</a></li>
    <li class="breadcrumb-item">Customer List</li>
    </ol>
</nav>
<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="CustomerForm">
                        <div class="modal-header">
                            <h5 class="modal-title" id="basicModalLabel">Customer Form</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            
                            <div class="row">
                                <div class="col mb-3">
                                    <label for="name" class="form-label">Customer Name</label>
                                    <input type="text" id="name" name="name" class="form-control" placeholder="Enter 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">Address</label>
                                    <input type="text" id="address" name="address" class="form-control" />
                                </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>

<div class="card">
<div class="card-datatable table-responsive pt-0">
<table class="datatables-ajax table table-bordered table-responsive">
    <thead>
        <tr>
            <th>Customer Name</th>
            <th>Mobile</th>
            <th>Email</th>
            <th>Address</th>
            <th>Total Bookings</th>
            <th>Avg. Discount %</th>
            <!--<th>Total Discount</th>-->
            <th>Total Amount</th>
            <th>Status</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <?php
        $query = "
            SELECT 
                c.id AS customer_id,
                c.name,
                c.phone,
                c.email,
                CONCAT_WS(', ', c.address, c.city, c.state, c.country) AS full_address,
                c.status AS customer_status,
                COUNT(pb.id) AS total_bookings,
                SUM(pb.discount_amount) AS total_discount,
                SUM(pb.total_amount) AS total_amount,
                (CASE 
                    WHEN SUM(pb.total_amount) > 0 
                    THEN (SUM(pb.discount_amount) / SUM(pb.total_amount)) * 100 
                    ELSE 0 
                END) AS avg_discount_percent
            FROM customers c
            LEFT JOIN package_bookings pb ON c.id = pb.customer_id
            GROUP BY c.id
            ORDER BY total_bookings ASC
        ";
        $result = mysqli_query($conn, $query);

        while ($row = mysqli_fetch_assoc($result)) {
        ?>
        <tr>
            <td><?= htmlspecialchars(ucwords(strtolower(trim($row['name'])))) ?></td>
            <td><?= htmlspecialchars($row['phone']) ?></td>
            <td><?= htmlspecialchars($row['email']) ?></td>
            <td><?= htmlspecialchars(ucwords(strtolower(trim($row['full_address'])))) ?></td>
            <td><?= (int)$row['total_bookings'] ?></td>
            <td><?= number_format($row['avg_discount_percent'], 2) ?>%</td>
            <td>₹<?= number_format($row['total_amount'], 2) ?></td>
            <td>
                <label class="switch">
                    <input type="checkbox" class="switch-input" value="<?= $row['customer_id'] ?>"
                        <?= $row['customer_status'] == 'active' ? '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['customer_id']; ?>" class="btn btn-xs btn-warning update"><i class="far fa-edit"></i></button>
                <button type="button" id="<?php echo $row['customer_id']; ?>" class="btn btn-xs btn-danger delete"><i class="far fa-trash-alt"></i></button>
            </td>
        </tr>
        <?php } ?>
    </tbody>
</table>


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

    // Show modal for Create
    $('#modal_button').click(function () {
        $('#CustomerForm')[0].reset();
        $('.modal-title').text("Create New Customer");
        $('#action').val('Create');
        $('#id').val('');
        $('#basicModal').modal('show');
    });

    // Show modal for Update
    $(document).on('click', '.update', function () {
        const id = $(this).attr("id");
        $.ajax({
            url: "controller/CustomerController.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);
                $('#address').val(data.address);
                $('#id').val(id);
                $('#action').val('Update');
                $('.modal-title').text("Update Customer");
                $('#basicModal').modal('show');
            },
            error: function () {
                toastr.error('Error fetching customer data.');
            }
        });
    });

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

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

        if (formData.name && formData.phone && formData.email) {
            $.ajax({
                url: "controller/CustomerController.php",
                method: "POST",
                data: formData,
                dataType: "json",
                success: function (response) {
                    $('#basicModal').modal('hide');
                    if (response.status === 'success') {
                        toastr.success(response.message);
                        setTimeout(function() {
                    window.location.reload();  // Page will reload after the timeout
                }, 3000);  // 3 seconds delay before reloading
                        
                    } else {
                        toastr.error(response.message);
                    }
                },
                error: function () {
                    toastr.error('Request failed. Please try again.');
                }
            });
        } else {
            toastr.error("Please fill all required fields.");
        }
    });

    // Status change
    window.statusChange = function (id) {
        $.ajax({
            url: 'controller/CustomerController.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/CustomerController.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');?>