<?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="quotation_add.php">Quotation Add</a></li>
    <li class="breadcrumb-item">Quotation List</li>
    </ol>
</nav>
<!-- Modal for Status Change -->
<div class="modal fade" id="statusChangeModal" tabindex="-1" aria-labelledby="statusChangeModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="statusChangeModalLabel">Change Quotation Status</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="statusChangeForm">
          <input type="hidden" id="quotationId" name="quotation_id" value="">
          <div class="form-group">
            <label for="status">Status</label>
            <select class="form-select" id="status" name="status">
              <option value="pending">Pending</option>
              <option value="accepted">Accepted</option>
              <option value="rejected">Rejected</option>
              <option value="closed">Closed</option>
            </select>
          </div>
        </form>
      </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="saveStatusBtn">Save changes</button>
      </div>
    </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 style="display: none"></th>
            <th>Date</th>
            <th>Quotation No.</th>
            <th>Name</th>
            <th>Mobile</th>
			<th>Package Amount</th>
            <th>Total Amount</th>
            <th>Quotation Status</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <?php
        // Fetch quotations along with customer details
        $nox = 0;
        $ure = mysqli_query($conn, "SELECT * FROM quotations ORDER BY ABS(id) DESC");
        while ($urow = mysqli_fetch_array($ure)) {
            $id = $urow[0];
            $no = 1 + $nox++;
            $uupQry = "UPDATE quotations SET orderlist='$no' WHERE id='$id'";
            $uuresult = mysqli_query($conn, $uupQry);
        }

        // Get quotations with customer data
        $result = mysqli_query($conn, "SELECT q.*, c.name AS customer_name, c.phone AS customer_phone FROM quotations q JOIN customers c ON q.customer_id = c.id ORDER BY q.id DESC");

        while ($row = mysqli_fetch_array($result)) {
            // Determine the status class based on the quotation status
            $statusclass = strtolower($row['status']) == 'pending' ? 'btn-warning' :
                           (strtolower($row['status']) == 'accepted' ? 'btn-success' :
                           (strtolower($row['status']) == 'rejected' ? 'btn-secondary' : 'btn-info'));
        ?>
        <tr class="showtr">
            <td style="display: none"><?php echo $row['orderlist']; ?></td>
            <td><?php echo htmlspecialchars(date('d-m-Y', strtotime($row['quotation_date']))); ?></td>
            <td><?php echo htmlspecialchars($row['quotation_no']); ?></td>
            <td><a href="quotation_details.php?quotationid=<?php echo $row['id']; ?>" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="View Details"><?php echo htmlspecialchars(ucwords($row['customer_name'])); ?></a></td>
            <td><?php echo htmlspecialchars($row['customer_phone']); ?></td>
			<td><?php echo htmlspecialchars(ucwords($row['package_name'])); ?></td>
            <td><?php echo number_format((float)$row['grand_total'], 2); ?></td>
            <td><button class="btn btn-sm <?php echo $statusclass; ?> changeStatusBtn" 
            data-id="<?php echo $row['id']; ?>" data-current-status="<?php echo htmlspecialchars(strtolower($row['status'])); ?>"><?php echo htmlspecialchars(ucwords(strtolower($row['status']))); ?></button><br><small class="text-muted">
        <?php echo !empty($row['last_followup_date']) ? 'Last: ' . date('d-m-Y', strtotime($row['last_followup_date'])) : ''; ?></small></td>

            <td>
				<button type="button" class="btn btn-xs btn-info download" data-id="<?= $row['id']; ?>"><i class="far fa-file-pdf"></i></button>
                <button type="button" class="btn btn-xs btn-warning" onclick="window.location.href='quotation_edit.php?id=<?php echo $row['id']; ?>'" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Edit">
                    <i class="far fa-edit"></i>
                </button>
                <button type="button" id="<?php echo $row['id']; ?>" class="btn btn-xs btn-danger delete" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Delete"><i class="far fa-trash-alt"></i></button>
            </td>
        </tr>
        <?php } ?>
    </tbody>
</table>
</div>
</div>
</div>
<script>
$(document).ready(function () {
    // Open modal and populate it with quotation details
    $(document).on('click', '.changeStatusBtn', function () {
        var quotationId = $(this).data('id');
        var currentStatus = $(this).data('current-status');

        // Set the quotation ID and current status in the modal
        $('#quotationId').val(quotationId);
        $('#status').val(currentStatus); // Set the current status in the dropdown

        // Show the modal
        $('#statusChangeModal').modal('show');
    });

    // Save the new status when the "Save changes" button is clicked
    $('#saveStatusBtn').click(function () {
        var quotationId = $('#quotationId').val();
        var newStatus = $('#status').val();

        // Check if a new status is selected
        if (!newStatus) {
            alert('Please select a status.');
            return;
        }
		$('#statusChangeModal').modal('hide');
        // SweetAlert confirmation before making the AJAX request
        Swal.fire({
            title: 'Are you sure?',
            text: "change the status of this quotation.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, update it!',
            cancelButtonText: 'No, cancel!',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                // AJAX request to update the status in the database
                $.ajax({
                    url: 'controller/QuotationController.php',
                    method: 'POST',
                    data: {
                        action: 'update_status',
                        id: quotationId,
                        status: newStatus
                    },
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            // Close the modal
                            $('#statusChangeModal').modal('hide');

                            // Update the status in the table
                            $('button[data-id="' + quotationId + '"]').closest('tr').find('td:eq(7)').html('<button class="btn btn-sm btn-' + getStatusClass(newStatus) + '">' + capitalizeFirstLetter(newStatus) + '</button>');

                            // Show success notification
                            Swal.fire('Updated!', 'Status has been updated successfully.', 'success');
                        } else {
                            Swal.fire('Failed!', 'Status update failed: ' + response.message, 'error');
                        }
                    },
                    error: function() {
                        Swal.fire('Error!', 'An error occurred while updating the status.', 'error');
                    }
                });
            } else {
                // If the user cancels the action
                Swal.fire('Cancelled', 'The status was not changed.', 'info');
            }
        });
    });

    // Helper function to capitalize the first letter of a string
    function capitalizeFirstLetter(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }

    // Helper function to get the correct class based on the status
    function getStatusClass(status) {
        switch (status.toLowerCase()) {
            case 'pending': return 'warning';
            case 'accepted': return 'success';
            case 'rejected': return 'secondary';
            case 'closed': return 'info'; // Added 'closed' status
            default: return 'info';
        }
    }
});


$(document).ready(function () {
    
    // Handle delete action
    $(document).on('click', '.delete', function () {
    var id = $(this).attr("id");
    var row = $(this).closest('tr');
    if (confirm('Are you sure you want to delete this record?')) {
        $.ajax({
            url: 'controller/QuotationController.php',
            method: 'POST',
            data: { id: id, action: 'Delete' },
            dataType: 'json', // Expect JSON response
            success: function (response) {
                console.log('Server Response:', response); // Log the response
                if (response.status === 'Delete') {
                    toastr.success(response.message);
                    row.css('background-color', '#63ba8f').fadeOut(800, function() {
                        $(this).remove();
                    });
                } else {
                    toastr.error(response.message);
                }
            },
            error: function () {
                toastr.error('Error while deleting record.');
            }
        });
    }
});

// Download PDF
    $('.download').on('click', function() {
        const id = $(this).data('id');
        window.open('controller/DownloadPDFQuotationController.php?id=' + id, '_blank');
    });

});

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