<?php
session_start();
include_once('includes/config.php');
if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Mariyappa Nadar Ricemill | Complaints Management</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    
    <style>
        /* Full-height layout and compact paddings */
        html, body, #wrapper, #content-wrapper, #content { height: 100%; }
        .container-fluid { padding: 8px 10px; }
        
        .complaint-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
            transition: all 0.2s ease;
            border: 1px solid #e8e8e8;
            margin-bottom: 15px;
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        
        .complaint-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.15);
            border-color: #4e73df;
        }
        
        .complaint-header {
            background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
            color: white;
            border-radius: 8px 8px 0 0;
            padding: 10px 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .complaint-number {
            font-weight: 600;
            font-size: 0.9rem;
        }
        
        .complaint-status {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 500;
            background: rgba(255, 255, 255, 0.2);
        }
        
        .status-pending .complaint-header {
            background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%);
        }
        
        .status-in-progress .complaint-header {
            background: linear-gradient(135deg, #36b9cc 0%, #258391 100%);
        }
        
        .status-resolved .complaint-header {
            background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);
        }
        
        .status-closed .complaint-header {
            background: linear-gradient(135deg, #6c757d 0%, #545b62 100%);
        }
        
        .complaint-body {
            padding: 12px;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }
        
        .complaint-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px;
            margin-bottom: 10px;
        }
        
        .info-item {
            padding: 8px;
            background: #f8f9fc;
            border-radius: 6px;
            text-align: center;
        }
        
        .info-label {
            font-size: 0.7rem;
            color: #858796;
            margin-bottom: 4px;
        }
        
        .info-value {
            font-weight: 600;
            color: #5a5c69;
            font-size: 0.85rem;
        }
        
        .customer-info {
            background: #e3f2fd;
            border-radius: 6px;
            padding: 8px;
            margin-bottom: 10px;
        }
        
        .customer-name {
            font-weight: 600;
            color: #1976d2;
            font-size: 0.9rem;
        }
        
        .customer-details {
            font-size: 0.75rem;
            color: #666;
        }
        
        .complaint-details {
            background: #fff3cd;
            border-radius: 6px;
            padding: 8px;
            margin-bottom: 10px;
            border: 1px solid #ffeaa7;
        }
        
        .complaint-title {
            font-weight: 600;
            color: #856404;
            font-size: 0.85rem;
            margin-bottom: 4px;
        }
        
        .complaint-description {
            font-size: 0.75rem;
            color: #856404;
            line-height: 1.3;
        }
        
        .complaint-actions {
            display: flex;
            gap: 4px;
            flex-wrap: wrap;
            margin-top: auto;
            border-top: 1px solid #f8f9fc;
            padding-top: 10px;
        }
        
        .btn-action {
            flex: 1;
            min-width: 70px;
            padding: 6px 8px;
            border: none;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.15s ease-in-out;
            text-align: center;
        }
        
        .btn-resolve {
            background: #1cc88a;
            color: white;
        }
        
        .btn-resolve:hover {
            background: #17a673;
            transform: translateY(-1px);
        }
        
        .btn-progress {
            background: #36b9cc;
            color: white;
        }
        
        .btn-progress:hover {
            background: #2c9faf;
            transform: translateY(-1px);
        }
        
        .btn-edit {
            background: #f6c23e;
            color: white;
        }
        
        .btn-edit:hover {
            background: #dda20a;
            transform: translateY(-1px);
        }
        
        .btn-close {
            background: #e74a3b;
            color: white;
        }
        
        .btn-close:hover {
            background: #c0392b;
            transform: translateY(-1px);
        }
        
        .btn-view {
            background: #6c757d;
            color: white;
        }
        
        .btn-view:hover {
            background: #545b62;
            transform: translateY(-1px);
        }
        
        .priority-high {
            border-left: 4px solid #e74a3b !important;
        }
        
        .priority-medium {
            border-left: 4px solid #f6c23e !important;
        }
        
        .priority-low {
            border-left: 4px solid #1cc88a !important;
        }
        
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px;
            padding: 12px 14px;
            margin-bottom: 12px;
        }
        
        .back-btn {
            background: #6c757d;
            color: white;
            border: none;
            border-radius: 8px;
            padding: 6px 10px;
            font-weight: 500;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s ease;
            margin-bottom: 12px;
            font-size: 0.85rem;
        }
        
        .back-btn:hover {
            background: #545b62;
            color: white;
            text-decoration: none;
            transform: translateY(-1px);
        }
        
        .filter-tabs {
            display: flex;
            background: white;
            border-radius: 8px;
            padding: 4px;
            margin-bottom: 12px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
        }
        
        .filter-tab {
            flex: 1;
            padding: 8px 12px;
            background: none;
            border: none;
            border-radius: 6px;
            color: #858796;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.15s ease-in-out;
            font-size: 0.85rem;
            text-align: center;
        }
        
        .filter-tab.active {
            background: #4e73df;
            color: white;
        }
        
        .empty-state {
            text-align: center;
            padding: 2rem 1rem;
            color: #858796;
        }
        
        .empty-state i {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: #dddfeb;
        }
        
        /* Tighter grid gutters */
        .row > [class^="col-"] { padding-left: 6px; padding-right: 6px; }

        @media (max-width: 768px) {
            .complaint-info {
                grid-template-columns: 1fr;
                gap: 6px;
            }
            
            .complaint-actions {
                gap: 4px;
            }
            
            .btn-action {
                font-size: 0.7rem;
                padding: 5px 6px;
            }
            
            .page-header {
                padding: 10px 12px;
            }
            
            .filter-tab {
                padding: 6px 8px;
                font-size: 0.8rem;
            }
        }
        
        /* Filter Modal Styles */
        .filter-option-btn {
            height: 80px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-size: 0.9rem;
            border-radius: 8px;
            transition: all 0.2s ease;
        }
        
        .filter-option-btn i {
            font-size: 1.5rem;
        }
        
        .filter-option-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        
        .custom-date-range {
            background: #f8f9fc;
            border-radius: 8px;
            padding: 15px;
        }
        
        .d-flex.gap-2 {
            gap: 8px;
        }
        
        .resolution-info {
            background: #d1ecf1;
            border-radius: 6px;
            padding: 8px;
            margin-bottom: 10px;
            border: 1px solid #b8daff;
        }
        
        .resolution-title {
            font-weight: 600;
            color: #0c5460;
            font-size: 0.8rem;
            margin-bottom: 4px;
        }
        
        .resolution-text {
            font-size: 0.75rem;
            color: #0c5460;
            line-height: 1.3;
        }
    </style>
</head>

<body id="page-top">
    <!-- Page Wrapper -->
    <div id="wrapper">
        <!-- Sidebar -->
        <?php include_once('includes/sidebar.php'); ?>
        
        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">
            <!-- Main Content -->
            <div id="content">
                <!-- Topbar -->
                <?php include_once('includes/topbar.php'); ?>
                
                <!-- Begin Page Content -->
                <div class="container-fluid">
                    
                    <!-- Back Button -->
                    <a href="dashboard.php" class="back-btn">
                        <i class="fas fa-arrow-left"></i>
                        Back to Dashboard
                    </a>
                    
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <h1 class="h5 mb-1">
                                    <i class="fas fa-comment-dots mr-2"></i>
                                    Complaints Management
                                </h1>
                                <p class="mb-0" style="font-size: 0.85rem; opacity: 0.9;">Manage customer complaints and resolutions</p>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-sm" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3);" onclick="openDateFilterModal()">
                                    <i class="fas fa-filter mr-1"></i>Filter
                                </button>
                                <button type="button" class="btn btn-sm" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3);" onclick="openNewComplaintModal()">
                                    <i class="fas fa-plus mr-1"></i>New Complaint
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Filter Tabs -->
                    <div class="filter-tabs">
                        <button class="filter-tab active" onclick="filterComplaints('all')" id="tab-all">
                            <i class="fas fa-list mr-1"></i>All
                        </button>
                        <button class="filter-tab" onclick="filterComplaints('Pending')" id="tab-pending">
                            <i class="fas fa-clock mr-1"></i>Pending
                        </button>
                        <button class="filter-tab" onclick="filterComplaints('In Progress')" id="tab-in-progress">
                            <i class="fas fa-cog mr-1"></i>In Progress
                        </button>
                        <button class="filter-tab" onclick="filterComplaints('Resolved')" id="tab-resolved">
                            <i class="fas fa-check mr-1"></i>Resolved
                        </button>
                        <button class="filter-tab" onclick="filterComplaints('Closed')" id="tab-closed">
                            <i class="fas fa-times mr-1"></i>Closed
                        </button>
                    </div>
                    
                    <!-- Complaints Container -->
                    <div class="row" id="complaints-container">
                        <div class="col-12">
                            <div class="empty-state">
                                <i class="fas fa-spinner fa-spin"></i>
                                <h5>Loading complaints...</h5>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- /.container-fluid -->
            </div>
            <!-- End of Main Content -->
            
            <!-- Footer -->
            <?php include_once('includes/footer.php'); ?>
        </div>
        <!-- End of Content Wrapper -->
    </div>
    <!-- End of Page Wrapper -->
    
    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Date Filter Modal -->
    <div class="modal fade" id="dateFilterModal" tabindex="-1" role="dialog" aria-labelledby="dateFilterModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="dateFilterModalLabel">
                        <i class="fas fa-filter mr-2"></i>Filter Complaints by Date
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="text-center mb-3">
                        <p class="text-muted">Select a time period to filter your complaints</p>
                    </div>
                    
                    <div class="row">
                        <div class="col-6 mb-3">
                            <button type="button" class="btn btn-outline-primary btn-block filter-option-btn" onclick="applyDateFilter('today')">
                                <i class="fas fa-calendar-day mb-1"></i><br>
                                <span>Today</span>
                            </button>
                        </div>
                        <div class="col-6 mb-3">
                            <button type="button" class="btn btn-outline-primary btn-block filter-option-btn" onclick="applyDateFilter('yesterday')">
                                <i class="fas fa-calendar-minus mb-1"></i><br>
                                <span>Yesterday</span>
                            </button>
                        </div>
                        <div class="col-6 mb-3">
                            <button type="button" class="btn btn-outline-primary btn-block filter-option-btn" onclick="applyDateFilter('this_week')">
                                <i class="fas fa-calendar-week mb-1"></i><br>
                                <span>This Week</span>
                            </button>
                        </div>
                        <div class="col-6 mb-3">
                            <button type="button" class="btn btn-outline-primary btn-block filter-option-btn" onclick="applyDateFilter('last_week')">
                                <i class="fas fa-calendar-alt mb-1"></i><br>
                                <span>Last Week</span>
                            </button>
                        </div>
                        <div class="col-6 mb-3">
                            <button type="button" class="btn btn-outline-primary btn-block filter-option-btn" onclick="applyDateFilter('this_month')">
                                <i class="fas fa-calendar mb-1"></i><br>
                                <span>This Month</span>
                            </button>
                        </div>
                        <div class="col-6 mb-3">
                            <button type="button" class="btn btn-outline-primary btn-block filter-option-btn" onclick="applyDateFilter('last_month')">
                                <i class="fas fa-calendar-times mb-1"></i><br>
                                <span>Last Month</span>
                            </button>
                        </div>
                    </div>
                    
                    <hr>
                    
                    <!-- Custom Date Range -->
                    <div class="custom-date-range">
                        <h6 class="text-center mb-3"><i class="fas fa-calendar-check mr-1"></i>Custom Date Range</h6>
                        <div class="row">
                            <div class="col-6">
                                <label class="small text-muted">From Date:</label>
                                <input type="date" class="form-control form-control-sm" id="fromDate">
                            </div>
                            <div class="col-6">
                                <label class="small text-muted">To Date:</label>
                                <input type="date" class="form-control form-control-sm" id="toDate">
                            </div>
                        </div>
                        <div class="text-center mt-3">
                            <button type="button" class="btn btn-success btn-sm" onclick="applyCustomDateFilter()">
                                <i class="fas fa-search mr-1"></i>Apply Custom Filter
                            </button>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" onclick="clearDateFilter()">
                        <i class="fas fa-undo mr-1"></i>Clear Filter
                    </button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times mr-1"></i>Close
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- New Complaint Modal -->
    <div class="modal fade" id="newComplaintModal" tabindex="-1" role="dialog" aria-labelledby="newComplaintModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="newComplaintModalLabel">
                        <i class="fas fa-plus mr-2"></i>Register New Complaint
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="complaintForm">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="small text-muted">Customer *</label>
                                    <select class="form-control" id="customerSelect" required>
                                        <option value="">Select Customer</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="small text-muted">Rice Bag *</label>
                                    <select class="form-control" id="riceBagSelect" required>
                                        <option value="">Select Rice Bag</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="small text-muted">Complaint Type *</label>
                                    <select class="form-control" id="complaintType" required>
                                        <option value="Quality">Quality Issue</option>
                                        <option value="Quantity">Quantity Issue</option>
                                        <option value="Delivery">Delivery Issue</option>
                                        <option value="Pricing">Pricing Issue</option>
                                        <option value="Service">Service Issue</option>
                                        <option value="Other">Other</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="small text-muted">Priority</label>
                                    <select class="form-control" id="priority">
                                        <option value="Low">Low</option>
                                        <option value="Medium" selected>Medium</option>
                                        <option value="High">High</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="small text-muted">Complaint Title *</label>
                            <input type="text" class="form-control" id="complaintTitle" placeholder="Brief title of the complaint" required>
                        </div>
                        
                        <div class="form-group">
                            <label class="small text-muted">Complaint Description *</label>
                            <textarea class="form-control" id="complaintDescription" rows="4" placeholder="Detailed description of the complaint" required></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">
                            <i class="fas fa-times mr-1"></i>Cancel
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save mr-1"></i>Register Complaint
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Complaint Resolution Modal -->
    <div class="modal fade" id="resolutionModal" tabindex="-1" role="dialog" aria-labelledby="resolutionModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header bg-success text-white">
                    <h5 class="modal-title" id="resolutionModalLabel">
                        <i class="fas fa-check mr-2"></i>Resolve Complaint
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="resolutionForm">
                    <div class="modal-body">
                        <input type="hidden" id="resolutionComplaintId">
                        <div class="form-group">
                            <label class="small text-muted">Resolution Details *</label>
                            <textarea class="form-control" id="resolutionText" rows="4" placeholder="Describe how the complaint was resolved" required></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">
                            <i class="fas fa-times mr-1"></i>Cancel
                        </button>
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-check mr-1"></i>Mark as Resolved
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Bootstrap core JavaScript-->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    
    <!-- Core plugin JavaScript-->
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    
    <!-- Custom scripts for all pages-->
    <script src="js/sb-admin-2.min.js"></script>
    
    <script>
        let currentFilter = 'all';
        let currentDateFilter = null;
        
        $(document).ready(function() {
            // Hide sidebar on load for compact, content-focused layout
            $('body').addClass('sidebar-toggled');
            $('.sidebar').addClass('toggled');
            
            loadComplaints('all');
            loadCustomers();
            loadRiceBags();
            
            // Setup form handlers
            $('#complaintForm').on('submit', handleNewComplaint);
            $('#resolutionForm').on('submit', handleResolution);
        });
        
        // Filter complaints by status
        function filterComplaints(status) {
            currentFilter = status;
            
            // Update active tab
            $('.filter-tab').removeClass('active');
            $('#tab-' + status.toLowerCase().replace(' ', '-')).addClass('active');
            
            // Load complaints
            loadComplaints(status);
        }
        
        // Load complaints from API
        function loadComplaints(status) {
            $('#complaints-container').html(`
                <div class="col-12">
                    <div class="empty-state">
                        <i class="fas fa-spinner fa-spin"></i>
                        <h4>Loading complaints...</h4>
                    </div>
                </div>
            `);
            
            let url = 'api/complaints.php?status=' + encodeURIComponent(status);
            
            if (currentDateFilter) {
                url += '&from_date=' + currentDateFilter.from + '&to_date=' + currentDateFilter.to;
            }
            
            $.ajax({
                url: url,
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        renderComplaints(response.data, status);
                    } else if (response.setup_required) {
                        // Table needs to be created
                        $('#complaints-container').html(`
                            <div class="col-12">
                                <div class="card border-warning">
                                    <div class="card-body text-center">
                                        <i class="fas fa-exclamation-triangle fa-3x text-warning mb-3"></i>
                                        <h5 class="card-title">Complaints System Setup Required</h5>
                                        <p class="card-text">${response.error}</p>
                                        <a href="setup-complaints.php" class="btn btn-warning">
                                            <i class="fas fa-cog mr-2"></i>Setup Complaints Table
                                        </a>
                                        <a href="test-database.php" class="btn btn-info ml-2">
                                            <i class="fas fa-search mr-2"></i>Check Database
                                        </a>
                                    </div>
                                </div>
                            </div>
                        `);
                    } else {
                        showError('Error loading complaints: ' + (response.message || response.error || 'Unknown error'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading complaints:', error);
                    showError('Error loading complaints. Please try again.');
                }
            });
        }
        
        // Render complaints list
        function renderComplaints(complaints, status) {
            const container = $('#complaints-container');
            
            if (complaints.length === 0) {
                container.html(`
                    <div class="col-12">
                        <div class="empty-state">
                            <i class="fas fa-comment-dots"></i>
                            <h5>No ${status.toLowerCase()} complaints found</h5>
                            <p>There are no complaints with ${status.toLowerCase()} status at the moment.</p>
                            <button class="btn btn-primary btn-sm" onclick="openNewComplaintModal()">
                                <i class="fas fa-plus mr-1"></i>Register New Complaint
                            </button>
                        </div>
                    </div>
                `);
                return;
            }
            
            // Show filter info if date filter is active
            let html = '';
            if (currentDateFilter) {
                let filterText = '';
                if (currentDateFilter.type === 'custom') {
                    filterText = `Custom range: ${currentDateFilter.from} to ${currentDateFilter.to}`;
                } else {
                    filterText = currentDateFilter.type.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase());
                }
                
                html += `
                    <div class="col-12 mb-3">
                        <div class="alert alert-info alert-dismissible fade show" role="alert">
                            <i class="fas fa-filter mr-2"></i>
                            <strong>Filtered by:</strong> ${filterText} (${complaints.length} complaints found)
                            <button type="button" class="btn btn-sm btn-outline-primary ml-3" onclick="clearDateFilter()">
                                <i class="fas fa-times mr-1"></i>Clear Filter
                            </button>
                        </div>
                    </div>
                `;
            }
            
            complaints.forEach(complaint => {
                html += renderComplaintCard(complaint);
            });
            
            container.html(html);
        }
        
        // Render individual complaint card
        function renderComplaintCard(complaint) {
            const statusClass = 'status-' + complaint.Status.toLowerCase().replace(' ', '-');
            const priorityClass = 'priority-' + complaint.Priority.toLowerCase();
            const complaintDate = new Date(complaint.ComplaintDate).toLocaleDateString('en-IN', {
                day: '2-digit', month: 'short'
            });
            
            let actions = '';
            if (complaint.Status === 'Pending') {
                actions = `
                    <button class="btn-action btn-progress" onclick="setInProgress('${complaint.ID}')">
                        <i class="fas fa-cog"></i> In Progress
                    </button>
                    <button class="btn-action btn-resolve" onclick="openResolutionModal('${complaint.ID}')">
                        <i class="fas fa-check"></i> Resolve
                    </button>
                    <button class="btn-action btn-edit" onclick="editComplaint('${complaint.ID}')">
                        <i class="fas fa-edit"></i> Edit
                    </button>
                `;
            } else if (complaint.Status === 'In Progress') {
                actions = `
                    <button class="btn-action btn-resolve" onclick="openResolutionModal('${complaint.ID}')">
                        <i class="fas fa-check"></i> Resolve
                    </button>
                    <button class="btn-action btn-edit" onclick="editComplaint('${complaint.ID}')">
                        <i class="fas fa-edit"></i> Edit
                    </button>
                `;
            } else if (complaint.Status === 'Resolved') {
                actions = `
                    <button class="btn-action btn-close" onclick="closeComplaint('${complaint.ID}')">
                        <i class="fas fa-times"></i> Close
                    </button>
                    <button class="btn-action btn-view" onclick="viewComplaint('${complaint.ID}')">
                        <i class="fas fa-eye"></i> View
                    </button>
                `;
            } else {
                actions = `
                    <button class="btn-action btn-view" onclick="viewComplaint('${complaint.ID}')">
                        <i class="fas fa-eye"></i> View Details
                    </button>
                `;
            }
            
            let resolutionInfo = '';
            if (complaint.Resolution && complaint.Status !== 'Pending') {
                resolutionInfo = `
                    <div class="resolution-info">
                        <div class="resolution-title">Resolution:</div>
                        <div class="resolution-text">${complaint.Resolution}</div>
                        ${complaint.ResolvedDate ? `<div class="resolution-text mt-1"><strong>Resolved on:</strong> ${new Date(complaint.ResolvedDate).toLocaleDateString()} by ${complaint.ResolvedByName || 'N/A'}</div>` : ''}
                    </div>
                `;
            }
            
            return `
                <div class="col-lg-3 col-md-4 col-sm-6 col-12">
                    <div class="complaint-card ${statusClass} ${priorityClass}">
                        <div class="complaint-header">
                            <div class="complaint-number">${complaint.ComplaintNumber}</div>
                            <div class="complaint-status">
                                ${complaint.Status}
                                <span class="ml-1" style="background: rgba(255,255,255,0.3); padding: 2px 6px; border-radius: 8px;">
                                    ${complaint.Priority}
                                </span>
                            </div>
                        </div>
                        <div class="complaint-body">
                            <div class="customer-info">
                                <div class="customer-name">${complaint.CustomerName}</div>
                                <div class="customer-details">
                                    <i class="fas fa-phone mr-1"></i>${complaint.Mobile || 'N/A'} • 
                                    <i class="fas fa-map-marker-alt mr-1"></i>${complaint.Area || 'N/A'}
                                </div>
                            </div>
                            
                            <div class="complaint-details">
                                <div class="complaint-title">
                                    <i class="fas fa-seedling mr-1"></i>${complaint.RiceBagName || 'N/A'} - ${complaint.Brand || 'N/A'}
                                </div>
                                <div class="complaint-title">${complaint.ComplaintTitle}</div>
                                <div class="complaint-description">${complaint.ComplaintDescription}</div>
                            </div>
                            
                            ${resolutionInfo}
                            
                            <div class="complaint-info">
                                <div class="info-item">
                                    <div class="info-label">Date</div>
                                    <div class="info-value">${complaintDate}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Type</div>
                                    <div class="info-value">${complaint.ComplaintType}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Created By</div>
                                    <div class="info-value">${complaint.CreatedByName || 'N/A'}</div>
                                </div>
                                <div class="info-item">
                                    <div class="info-label">Time</div>
                                    <div class="info-value">${complaint.ComplaintTime ? complaint.ComplaintTime.substring(0, 5) : 'N/A'}</div>
                                </div>
                            </div>
                            
                            <div class="complaint-actions">
                                ${actions}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
        
        // Set complaint status to In Progress
        function setInProgress(complaintId) {
            updateComplaintStatus(complaintId, 'In Progress');
        }
        
        // Open resolution modal
        function openResolutionModal(complaintId) {
            $('#resolutionComplaintId').val(complaintId);
            $('#resolutionText').val('');
            $('#resolutionModal').modal('show');
        }
        
        // Handle resolution form submission
        function handleResolution(e) {
            e.preventDefault();
            
            const complaintId = $('#resolutionComplaintId').val();
            const resolutionText = $('#resolutionText').val().trim();
            
            if (!resolutionText) {
                alert('Please provide resolution details');
                return;
            }
            
            $.ajax({
                url: 'api/complaints.php',
                method: 'PUT',
                data: JSON.stringify({
                    complaint_id: complaintId,
                    status: 'Resolved',
                    resolution: resolutionText
                }),
                contentType: 'application/json',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        $('#resolutionModal').modal('hide');
                        alert('Complaint resolved successfully');
                        loadComplaints(currentFilter);
                    } else {
                        alert('Error resolving complaint: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error resolving complaint:', error);
                    alert('Error resolving complaint. Please try again.');
                }
            });
        }
        
        // Close complaint
        function closeComplaint(complaintId) {
            if (confirm('Are you sure you want to close this complaint? This action cannot be undone.')) {
                updateComplaintStatus(complaintId, 'Closed');
            }
        }
        
        // Update complaint status
        function updateComplaintStatus(complaintId, status) {
            $.ajax({
                url: 'api/complaints.php',
                method: 'PUT',
                data: JSON.stringify({
                    complaint_id: complaintId,
                    status: status
                }),
                contentType: 'application/json',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        alert('Complaint status updated successfully');
                        loadComplaints(currentFilter);
                    } else {
                        alert('Error updating complaint: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error updating complaint:', error);
                    alert('Error updating complaint. Please try again.');
                }
            });
        }
        
        // Edit complaint (placeholder)
        function editComplaint(complaintId) {
            alert('Edit complaint functionality coming soon!');
        }
        
        // View complaint details (placeholder)
        function viewComplaint(complaintId) {
            alert('View complaint details functionality coming soon!');
        }
        
        // Open new complaint modal
        function openNewComplaintModal() {
            $('#newComplaintModal').modal('show');
        }
        
        // Handle new complaint form submission
        function handleNewComplaint(e) {
            e.preventDefault();
            
            const formData = {
                customer_id: $('#customerSelect').val(),
                rice_bag_id: $('#riceBagSelect').val(),
                complaint_type: $('#complaintType').val(),
                complaint_title: $('#complaintTitle').val(),
                complaint_description: $('#complaintDescription').val(),
                priority: $('#priority').val()
            };
            
            $.ajax({
                url: 'api/complaints.php',
                method: 'POST',
                data: JSON.stringify(formData),
                contentType: 'application/json',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        $('#newComplaintModal').modal('hide');
                        $('#complaintForm')[0].reset();
                        alert('Complaint registered successfully');
                        loadComplaints(currentFilter);
                    } else {
                        alert('Error registering complaint: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error registering complaint:', error);
                    alert('Error registering complaint. Please try again.');
                }
            });
        }
        
        // Load customers for dropdown
        function loadCustomers() {
            $.ajax({
                url: 'api/get-customers-search.php',
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success && response.data) {
                        const select = $('#customerSelect');
                        select.empty().append('<option value="">Select Customer</option>');
                        
                        response.data.forEach(customer => {
                            select.append(`<option value="${customer.ID}">${customer.CustomerName} - ${customer.Mobile}</option>`);
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading customers:', error);
                }
            });
        }
        
        // Load rice bags for dropdown
        function loadRiceBags() {
            $.ajax({
                url: 'api/get-rice-bag.php',
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success && response.data) {
                        const select = $('#riceBagSelect');
                        select.empty().append('<option value="">Select Rice Bag</option>');
                        
                        response.data.forEach(riceBag => {
                            select.append(`<option value="${riceBag.ID}">${riceBag.RiceBagName} - ${riceBag.Brand}</option>`);
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading rice bags:', error);
                }
            });
        }
        
        // Show error message
        function showError(message) {
            $('#complaints-container').html(`
                <div class="col-12">
                    <div class="empty-state">
                        <i class="fas fa-exclamation-triangle" style="color: #e74a3b;"></i>
                        <h5>Error</h5>
                        <p>${message}</p>
                        <button class="btn btn-primary btn-sm" onclick="loadComplaints(currentFilter)">Try Again</button>
                    </div>
                </div>
            `);
        }
        
        // Date Filter Functions (similar to orders management)
        function openDateFilterModal() {
            $('#dateFilterModal').modal('show');
        }
        
        function applyDateFilter(filterType) {
            const today = new Date();
            let fromDate, toDate;
            
            switch(filterType) {
                case 'today':
                    fromDate = toDate = today.toISOString().split('T')[0];
                    break;
                    
                case 'yesterday':
                    const yesterday = new Date(today);
                    yesterday.setDate(yesterday.getDate() - 1);
                    fromDate = toDate = yesterday.toISOString().split('T')[0];
                    break;
                    
                case 'this_week':
                    const startOfWeek = new Date(today);
                    const dayOfWeek = today.getDay();
                    startOfWeek.setDate(today.getDate() - dayOfWeek);
                    fromDate = startOfWeek.toISOString().split('T')[0];
                    toDate = today.toISOString().split('T')[0];
                    break;
                    
                case 'last_week':
                    const lastWeekEnd = new Date(today);
                    const lastWeekStart = new Date(today);
                    lastWeekEnd.setDate(today.getDate() - today.getDay() - 1);
                    lastWeekStart.setDate(lastWeekEnd.getDate() - 6);
                    fromDate = lastWeekStart.toISOString().split('T')[0];
                    toDate = lastWeekEnd.toISOString().split('T')[0];
                    break;
                    
                case 'this_month':
                    fromDate = new Date(today.getFullYear(), today.getMonth(), 1).toISOString().split('T')[0];
                    toDate = today.toISOString().split('T')[0];
                    break;
                    
                case 'last_month':
                    const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
                    const lastMonthEnd = new Date(today.getFullYear(), today.getMonth(), 0);
                    fromDate = lastMonth.toISOString().split('T')[0];
                    toDate = lastMonthEnd.toISOString().split('T')[0];
                    break;
            }
            
            currentDateFilter = { from: fromDate, to: toDate, type: filterType };
            loadComplaints(currentFilter);
            $('#dateFilterModal').modal('hide');
        }
        
        function applyCustomDateFilter() {
            const fromDate = $('#fromDate').val();
            const toDate = $('#toDate').val();
            
            if (!fromDate || !toDate) {
                alert('Please select both from and to dates');
                return;
            }
            
            if (new Date(fromDate) > new Date(toDate)) {
                alert('From date cannot be later than to date');
                return;
            }
            
            currentDateFilter = { from: fromDate, to: toDate, type: 'custom' };
            loadComplaints(currentFilter);
            $('#dateFilterModal').modal('hide');
        }
        
        function clearDateFilter() {
            currentDateFilter = null;
            loadComplaints(currentFilter);
            $('#dateFilterModal').modal('hide');
        }
    </script>
</body>
</html>