<?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">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    
    <style>
        /* Amazon-inspired modern design */
        body { 
            background: #f8f9fa;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        
        .main-header {
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f4c75 100%);
            color: white;
            padding: 8px 0;
            margin-bottom: 12px;
            box-shadow: 0 1px 6px rgba(0,0,0,0.1);
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 8px;
        }
        
        .header-title {
            display: flex;
            align-items: center;
            gap: 8px;
            margin: 0;
            font-size: 16px;
        }
        
        .header-title i {
            font-size: 14px;
        }
        
        .header-actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .btn-modern {
            border-radius: 4px;
            font-weight: 500;
            font-size: 12px;
            padding: 6px 12px;
            transition: all 0.3s ease;
            border: none;
            position: relative;
            overflow: hidden;
        }
        
        .btn-modern:before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
            transition: left 0.5s;
        }
        
        .btn-modern:hover:before {
            left: 100%;
        }
        
        .btn-create {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            box-shadow: 0 2px 8px rgba(40, 167, 69, 0.3);
        }
        
        .btn-create:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(40, 167, 69, 0.4);
            color: white;
        }
        
        .filter-section {
            background: white;
            border-radius: 6px;
            padding: 12px;
            margin-bottom: 12px;
            box-shadow: 0 1px 2px rgba(0,0,0,0.08);
        }
        
        .filter-tabs {
            display: flex;
            gap: 4px;
            flex-wrap: wrap;
            margin-bottom: 10px;
        }
        
        .filter-tab {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            color: #495057;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 500;
            transition: all 0.3s ease;
            cursor: pointer;
            position: relative;
        }
        
        .filter-tab:hover {
            background: #e9ecef;
            transform: translateY(-1px);
        }
        
        .filter-tab.active {
            background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
            border-color: #4e73df;
            color: white;
            box-shadow: 0 2px 8px rgba(78, 115, 223, 0.3);
        }
        
        .search-controls {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            align-items: center;
        }
        
        .search-input {
            flex: 1;
            min-width: 200px;
            padding: 6px 30px 6px 8px;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            font-size: 12px;
            transition: all 0.3s ease;
            height: 32px;
        }
        
        .search-input:focus {
            border-color: #4e73df;
            box-shadow: 0 0 0 2px rgba(78, 115, 223, 0.1);
            outline: none;
        }
        
        .search-wrapper {
            position: relative;
            flex: 1;
            min-width: 250px;
        }
        
        .search-icon {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
        }
        
        /* Amazon-style Cards */
        .complaints-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 16px;
            margin-bottom: 30px;
        }
        
        .complaint-card {
            background: white;
            border: 1px solid #ddd;
            border-radius: 8px;
            overflow: hidden;
            transition: all 0.3s ease;
            position: relative;
            display: flex;
            flex-direction: column;
            height: 100%;
        }
        
        .complaint-card:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            transform: translateY(-2px);
            border-color: #4e73df;
        }
        
        .card-header {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 12px 15px;
            border-bottom: 1px solid #dee2e6;
            display: flex;
            justify-content: between;
            align-items: center;
        }
        
        .complaint-id {
            font-weight: 600;
            color: #4e73df;
            font-size: 14px;
        }
        
        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .status-pending { background: #fff3cd; color: #856404; }
        .status-in-progress { background: #cce5ff; color: #0056b3; }
        .status-resolved { background: #d4edda; color: #155724; }
        .status-closed { background: #f8d7da; color: #721c24; }
        
        .card-body {
            padding: 15px;
            flex: 1;
            display: flex;
            flex-direction: column;
        }
        
        .complaint-title {
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
            font-size: 16px;
            line-height: 1.3;
        }
        
        .complaint-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            margin-bottom: 10px;
            font-size: 13px;
            color: #666;
        }
        
        .meta-item {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .complaint-description {
            color: #666;
            font-size: 14px;
            line-height: 1.4;
            margin-bottom: 15px;
            flex: 1;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
        }
        
        .priority-indicator {
            position: absolute;
            top: 0;
            right: 0;
            width: 30px;
            height: 30px;
            clip-path: polygon(100% 0%, 0% 100%, 100% 100%);
        }
        
        .priority-high { background: #dc3545; }
        .priority-medium { background: #ffc107; }
        .priority-low { background: #28a745; }
        
        .card-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-top: 10px;
            border-top: 1px solid #f1f1f1;
        }
        
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        
        .btn-sm-modern {
            padding: 6px 12px;
            font-size: 12px;
            border-radius: 4px;
            border: none;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
        }
        
        .btn-view { background: #17a2b8; color: white; }
        .btn-edit { background: #ffc107; color: #212529; }
        .btn-delete { background: #dc3545; color: white; }
        
        .btn-sm-modern:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 6px rgba(0,0,0,0.2);
        }
        
        .status-selector {
            background: white;
            border: 2px solid #ddd;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
            color: #333;
            min-width: 120px;
            transition: all 0.3s ease;
        }
        
        .status-selector:hover {
            border-color: #4e73df;
            box-shadow: 0 0 0 2px rgba(78, 115, 223, 0.1);
        }
        
        .status-selector:focus {
            outline: none;
            border-color: #4e73df;
            box-shadow: 0 0 0 3px rgba(78, 115, 223, 0.2);
        }
        
        /* Mobile Responsive */
        @media (max-width: 768px) {
            .header-content {
                flex-direction: column;
                align-items: stretch;
            }
            
            .header-actions {
                justify-content: center;
            }
            
            .complaints-grid {
                grid-template-columns: 1fr;
                gap: 12px;
            }
            
            .search-controls {
                flex-direction: column;
                align-items: stretch;
            }
            
            .search-wrapper {
                min-width: 100%;
            }
            
            .filter-tabs {
                justify-content: center;
            }
            
            .filter-tab {
                flex: 1;
                text-align: center;
                min-width: 80px;
            }
        }
        
        /* Loading and Empty States */
        .loading-state, .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }
        
        .loading-spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #4e73df;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* Modal Improvements */
        .modal-content {
            border-radius: 8px;
            border: none;
            box-shadow: 0 8px 25px rgba(0,0,0,0.2);
        }
        
        .modal-header {
            background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
            color: white;
            border-radius: 8px 8px 0 0;
            padding: 12px 16px;
        }
        
        .modal-title {
            font-weight: 600;
            font-size: 14px;
        }
        
        .modal-body {
            padding: 16px;
        }
        
        .modal-footer {
            padding: 12px 16px;
        }
        
        .close {
            color: white;
            opacity: 0.8;
            font-size: 28px;
        }
        
        .close:hover {
            opacity: 1;
        }
        
        .form-control {
            border-radius: 4px;
            border: 1px solid #e9ecef;
            padding: 6px 8px;
            font-size: 12px;
            transition: all 0.3s ease;
            background: white !important;
            color: #333 !important;
            font-weight: 400;
            height: 32px;
            line-height: 1.2;
        }
        
        .form-control:focus {
            border-color: #4e73df;
            box-shadow: 0 0 0 2px rgba(78, 115, 223, 0.1);
            outline: none;
        }
        
        .form-control option {
            padding: 4px 8px;
            color: #333 !important;
            background: white !important;
            font-weight: 400;
            font-size: 12px;
        }
        
        .form-control select {
            background-color: white !important;
            color: #333 !important;
            appearance: menulist;
            -webkit-appearance: menulist;
            -moz-appearance: menulist;
        }
        
        /* Compact form styling */
        .form-group {
            margin-bottom: 12px;
        }
        
        .form-group label {
            font-size: 11px;
            font-weight: 600;
            margin-bottom: 4px;
            color: #555;
        }
        
        .priority-filter {
            min-width: 120px;
            width: auto !important;
            font-weight: 400;
            color: #333;
            background: white;
            padding: 6px 8px;
            font-size: 12px;
            height: 32px;
        }
        
        .priority-filter option {
            padding: 4px 8px;
            color: #333;
            font-weight: 400;
            font-size: 12px;
        }
        
        .stats-row {
            background: white;
            border-radius: 6px;
            padding: 8px;
            margin-bottom: 12px;
            box-shadow: 0 1px 2px rgba(0,0,0,0.08);
        }
        
        .stat-card {
            text-align: center;
            padding: 8px;
            border-radius: 4px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        }
        
        .stat-number {
            font-size: 18px;
            font-weight: 700;
            color: #4e73df;
            margin-bottom: 2px;
        }
        
        .stat-label {
            font-size: 10px;
            color: #6c757d;
            font-weight: 500;
            text-transform: uppercase;
        }
        
        /* Filter Modal Styles */
        .filter-option-btn {
            padding: 20px 10px;
            height: 100px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            border: 2px solid #4e73df;
            border-radius: 8px;
            transition: all 0.3s ease;
            text-align: center;
        }
        
        .filter-option-btn i {
            font-size: 24px;
            margin-bottom: 8px;
        }
        
        .filter-option-btn:hover {
            background: #4e73df;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(78, 115, 223, 0.3);
        }
        
        /* Compact Select2 Styling */
        .select2-container {
            width: 100% !important;
            font-size: 12px;
        }
        
        .select2-container--default .select2-selection--single {
            border: 1px solid #e9ecef !important;
            border-radius: 4px !important;
            height: 32px !important;
            padding: 2px 6px !important;
            font-size: 12px !important;
            font-weight: 400 !important;
            color: #333 !important;
            background: white !important;
        }
        
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 26px !important;
            color: #333 !important;
            padding-left: 2px !important;
            font-size: 12px !important;
        }
        
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 30px !important;
            right: 4px !important;
            top: 1px !important;
        }
        
        .select2-container--default.select2-container--focus .select2-selection--single {
            border-color: #4e73df !important;
            box-shadow: 0 0 0 2px rgba(78, 115, 223, 0.1) !important;
        }
        
        .select2-dropdown {
            border: 1px solid #4e73df !important;
            border-radius: 4px !important;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15) !important;
            font-size: 12px;
        }
        
        .select2-container--default .select2-results__option {
            padding: 6px 8px !important;
            font-size: 12px !important;
            font-weight: 400 !important;
        }
        
        .select2-container--default .select2-results__option--highlighted[aria-selected] {
            background-color: #4e73df !important;
        }
        
        .select2-search--dropdown .select2-search__field {
            border: 1px solid #e9ecef !important;
            border-radius: 4px !important;
            padding: 4px 6px !important;
            font-size: 12px !important;
            height: 28px !important;
        }
        
        .select2-search--dropdown .select2-search__field:focus {
            border-color: #4e73df !important;
            outline: none !important;
        }
    </style>
</head>

<body id="page-top">
    <div id="wrapper">
        <?php include_once('includes/sidebar.php'); ?>
        
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <?php include_once('includes/topbar.php'); ?>
                
                <!-- Main Header -->
                <div class="main-header">
                    <div class="container-fluid">
                        <div class="header-content">
                            <h1 class="header-title">
                                <i class="fas fa-comment-dots"></i>
                                <span>Complaints Management</span>
                            </h1>
                            <div class="header-actions">
                                <button class="btn btn-outline-light btn-modern" onclick="openDateFilterModal()">
                                    <i class="fas fa-filter mr-2"></i>Filter
                                </button>
                                <button class="btn btn-create btn-modern" onclick="openCreateModal()">
                                    <i class="fas fa-plus mr-2"></i>New Complaint
                                </button>
                                <button class="btn btn-outline-light btn-modern" onclick="refreshData()">
                                    <i class="fas fa-sync-alt mr-2"></i>Refresh
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="container-fluid">
                    <!-- Stats Row -->
                    <div class="stats-row">
                        <div class="row" id="statsRow">
                            <div class="col-lg-3 col-md-6 mb-3">
                                <div class="stat-card">
                                    <div class="stat-number" id="totalCount">-</div>
                                    <div class="stat-label">Total</div>
                                </div>
                            </div>
                            <div class="col-lg-3 col-md-6 mb-3">
                                <div class="stat-card">
                                    <div class="stat-number" id="pendingCount">-</div>
                                    <div class="stat-label">Pending</div>
                                </div>
                            </div>
                            <div class="col-lg-3 col-md-6 mb-3">
                                <div class="stat-card">
                                    <div class="stat-number" id="progressCount">-</div>
                                    <div class="stat-label">In Progress</div>
                                </div>
                            </div>
                            <div class="col-lg-3 col-md-6 mb-3">
                                <div class="stat-card">
                                    <div class="stat-number" id="resolvedCount">-</div>
                                    <div class="stat-label">Resolved</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="filter-section">
                        <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>
                        
                        <div class="search-controls">
                            <div class="search-wrapper">
                                <input type="text" class="search-input" id="searchInput" placeholder="Search complaints by number, title, or description...">
                                <i class="fas fa-search search-icon"></i>
                            </div>
                            <select class="form-control priority-filter" id="priorityFilter">
                                <option value="">All Priorities</option>
                                <option value="High">High Priority</option>
                                <option value="Medium">Medium Priority</option>
                                <option value="Low">Low Priority</option>
                            </select>
                        </div>
                    </div>

                    <!-- Complaints Grid -->
                    <div class="complaints-grid" id="complaintsGrid">
                        <!-- Loading state -->
                        <div class="loading-state" id="loadingState">
                            <div class="loading-spinner"></div>
                            <h5>Loading complaints...</h5>
                            <p>Please wait while we fetch the data.</p>
                        </div>
                    </div>

                    <!-- Empty State -->
                    <div class="empty-state" id="emptyState" style="display: none;">
                        <i class="fas fa-comment-slash fa-4x mb-3" style="color: #dee2e6;"></i>
                        <h5>No complaints found</h5>
                        <p>There are no complaints matching your current filters.</p>
                        <button class="btn btn-create btn-modern" onclick="openCreateModal()">
                            <i class="fas fa-plus mr-2"></i>Create First Complaint
                        </button>
                    </div>
                </div>
            </div>
            
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>

    <!-- Create/Edit Complaint Modal -->
    <div class="modal fade" id="complaintModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="modalTitle">
                        <i class="fas fa-plus-circle mr-2"></i>New Complaint
                    </h4>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="complaintForm">
                        <input type="hidden" id="complaintId" name="complaint_id">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Customer <span class="text-danger">*</span></label>
                                    <select class="form-control" id="customerId" name="customer_id" required>
                                        <option value="">Select Customer</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Rice Bag <span class="text-danger">*</span></label>
                                    <select class="form-control" id="riceBagId" name="rice_bag_id" required>
                                        <option value="">Select Rice Bag</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Complaint Type <span class="text-danger">*</span></label>
                                    <select class="form-control" id="complaintType" name="complaint_type" 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>Priority <span class="text-danger">*</span></label>
                                    <select class="form-control" id="priority" name="priority" required>
                                        <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>Complaint Title <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="complaintTitle" name="complaint_title" 
                                   placeholder="Enter a brief title for the complaint" required>
                        </div>
                        
                        <div class="form-group">
                            <label>Description <span class="text-danger">*</span></label>
                            <textarea class="form-control" id="complaintDescription" name="complaint_description" 
                                      rows="4" placeholder="Describe the complaint in detail" required></textarea>
                        </div>
                        
                        <div class="form-group" id="statusGroup" style="display: none;">
                            <label>Status</label>
                            <select class="form-control" id="status" name="status">
                                <option value="Pending">Pending</option>
                                <option value="In Progress">In Progress</option>
                                <option value="Resolved">Resolved</option>
                                <option value="Closed">Closed</option>
                            </select>
                        </div>
                        
                        <div class="form-group" id="resolutionGroup" style="display: none;">
                            <label>Resolution</label>
                            <textarea class="form-control" id="resolution" name="resolution" 
                                      rows="3" placeholder="Enter resolution details"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-create btn-modern" onclick="saveComplaint()">
                        <i class="fas fa-save mr-2"></i>Save Complaint
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- View Details Modal -->
    <div class="modal fade" id="viewModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">
                        <i class="fas fa-eye mr-2"></i>Complaint Details
                    </h4>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="viewModalBody">
                    <!-- Dynamic content loaded here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-edit btn-modern" onclick="editFromView()">
                        <i class="fas fa-edit mr-2"></i>Edit
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Date Filter Modal -->
    <div class="modal fade" id="dateFilterModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">
                        <i class="fas fa-filter mr-2"></i>Filter Complaints by Date
                    </h4>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="text-center mb-4">
                        <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-2"></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-2"></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-2"></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-2"></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-2"></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-2"></i><br>
                                <span>Last Month</span>
                            </button>
                        </div>
                    </div>
                    
                    <hr>
                    
                    <div class="row">
                        <div class="col-12">
                            <h6 class="mb-3">Custom Date Range</h6>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>From Date</label>
                                        <input type="date" class="form-control" id="customFromDate">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>To Date</label>
                                        <input type="date" class="form-control" id="customToDate">
                                    </div>
                                </div>
                            </div>
                            <button type="button" class="btn btn-primary btn-block" onclick="applyCustomDateFilter()">
                                <i class="fas fa-search mr-2"></i>Apply Custom Filter
                            </button>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-warning" onclick="clearDateFilter()">
                        <i class="fas fa-times mr-2"></i>Clear Filter
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
        let currentFilter = 'all';
        let currentData = [];
        let editingId = null;

        $(document).ready(function() {
            // Hide sidebar for compact mobile layout
            $('body').addClass('sidebar-toggled');
            $('.sidebar').addClass('toggled');
            
            // Load this week's data by default
            applyDateFilter('this_week');
            loadCustomers();
            loadRiceBags();
            loadStats();
            
            // Initialize Select2 for searchable dropdowns
            initializeSelect2();
            
            // Search functionality
            $('#searchInput').on('input', debounce(filterData, 300));
            $('#priorityFilter').on('change', filterData);
            
            // Status change handling
            $('#status').on('change', function() {
                const status = $(this).val();
                if (status === 'Resolved' || status === 'Closed') {
                    $('#resolutionGroup').show();
                } else {
                    $('#resolutionGroup').hide();
                }
            });
        });

        function debounce(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        }

        function initializeSelect2() {
            // Initialize Select2 for customer dropdown
            $('#customerId').select2({
                placeholder: 'Search and select customer...',
                allowClear: true,
                dropdownParent: $('#complaintModal'),
                width: '100%',
                theme: 'default'
            });
            
            // Initialize Select2 for rice bag dropdown  
            $('#riceBagId').select2({
                placeholder: 'Search and select rice bag...',
                allowClear: true,
                dropdownParent: $('#complaintModal'),
                width: '100%',
                theme: 'default'
            });
            
            // Reinitialize when modal opens
            $('#complaintModal').on('shown.bs.modal', function () {
                $('#customerId, #riceBagId').select2({
                    placeholder: function() {
                        return $(this).data('placeholder') || 'Search...';
                    },
                    allowClear: true,
                    dropdownParent: $('#complaintModal'),
                    width: '100%'
                });
            });
            
            // Destroy when modal closes to prevent conflicts
            $('#complaintModal').on('hidden.bs.modal', function () {
                $('#customerId, #riceBagId').select2('destroy');
            });
        }

        function loadComplaintsData() {
            showLoading();
            
            $.ajax({
                url: 'api/complaints.php',
                method: 'GET',
                data: { status: currentFilter },
                success: function(response) {
                    if (response.success) {
                        currentData = response.data || [];
                        renderComplaints(currentData);
                        updateStats();
                    } else {
                        showError('Error loading complaints: ' + (response.message || 'Unknown error'));
                    }
                },
                error: function() {
                    showError('Failed to load complaints. Please try again.');
                }
            });
        }

        function renderComplaints(complaints) {
            const grid = $('#complaintsGrid');
            
            if (!complaints || complaints.length === 0) {
                grid.html('');
                $('#emptyState').show();
                $('#loadingState').hide();
                return;
            }
            
            $('#emptyState').hide();
            $('#loadingState').hide();
            
            let html = '';
            complaints.forEach(complaint => {
                html += createComplaintCard(complaint);
            });
            
            grid.html(html);
        }

        function createComplaintCard(complaint) {
            const statusClass = `status-${complaint.Status.toLowerCase().replace(' ', '-')}`;
            const priorityClass = `priority-${complaint.Priority.toLowerCase()}`;
            
            return `
                <div class="complaint-card">
                    <div class="priority-indicator ${priorityClass}"></div>
                    
                    <div class="card-header">
                        <span class="complaint-id">${complaint.ComplaintNumber}</span>
                        <span class="status-badge ${statusClass}">${complaint.Status}</span>
                    </div>
                    
                    <div class="card-body">
                        <h6 class="complaint-title">${complaint.ComplaintTitle}</h6>
                        
                        <div class="complaint-meta">
                            <div class="meta-item">
                                <i class="fas fa-user"></i>
                                <span>${complaint.CustomerName}</span>
                            </div>
                            <div class="meta-item">
                                <i class="fas fa-tag"></i>
                                <span>${complaint.ComplaintType}</span>
                            </div>
                            <div class="meta-item">
                                <i class="fas fa-calendar"></i>
                                <span>${formatDate(complaint.ComplaintDate)}</span>
                            </div>
                            <div class="meta-item">
                                <i class="fas fa-exclamation-circle"></i>
                                <span>${complaint.Priority}</span>
                            </div>
                        </div>
                        
                        <p class="complaint-description">${complaint.ComplaintDescription}</p>
                        
                        <div class="card-actions">
                            <div class="action-buttons">
                                <button class="btn-sm-modern btn-view" onclick="viewComplaint(${complaint.ID})" title="View Details">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <button class="btn-sm-modern btn-edit" onclick="editComplaint(${complaint.ID})" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn-sm-modern btn-delete" onclick="deleteComplaint(${complaint.ID})" title="Delete">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                            
                            <select class="status-selector" onchange="quickStatusChange(${complaint.ID}, this.value)" ${complaint.Status === 'Closed' ? 'disabled' : ''}>
                                <option value="Pending" ${complaint.Status === 'Pending' ? 'selected' : ''}>Pending</option>
                                <option value="In Progress" ${complaint.Status === 'In Progress' ? 'selected' : ''}>In Progress</option>
                                <option value="Resolved" ${complaint.Status === 'Resolved' ? 'selected' : ''}>Resolved</option>
                                <option value="Closed" ${complaint.Status === 'Closed' ? 'selected' : ''}>Closed</option>
                            </select>
                        </div>
                    </div>
                </div>
            `;
        }

        function filterComplaints(status) {
            currentFilter = status;
            
            // Update active tab
            $('.filter-tab').removeClass('active');
            $(`#tab-${status.toLowerCase().replace(' ', '-')}`).addClass('active');
            
            loadComplaintsData();
        }

        function filterData() {
            const searchTerm = $('#searchInput').val().toLowerCase();
            const priorityFilter = $('#priorityFilter').val();
            
            let filteredData = [...currentData];
            
            if (searchTerm) {
                filteredData = filteredData.filter(complaint => 
                    complaint.ComplaintNumber.toLowerCase().includes(searchTerm) ||
                    complaint.ComplaintTitle.toLowerCase().includes(searchTerm) ||
                    complaint.ComplaintDescription.toLowerCase().includes(searchTerm) ||
                    complaint.CustomerName.toLowerCase().includes(searchTerm)
                );
            }
            
            if (priorityFilter) {
                filteredData = filteredData.filter(complaint => 
                    complaint.Priority === priorityFilter
                );
            }
            
            renderComplaints(filteredData);
        }

        function openCreateModal() {
            editingId = null;
            $('#modalTitle').html('<i class="fas fa-plus-circle mr-2"></i>New Complaint');
            $('#complaintForm')[0].reset();
            $('#complaintId').val('');
            $('#statusGroup').hide();
            $('#resolutionGroup').hide();
            
            // Clear Select2 selections
            $('#customerId').val(null).trigger('change');
            $('#riceBagId').val(null).trigger('change');
            
            $('#complaintModal').modal('show');
        }

        function editComplaint(id) {
            const complaint = currentData.find(c => c.ID == id);
            if (!complaint) return;
            
            editingId = id;
            $('#modalTitle').html('<i class="fas fa-edit mr-2"></i>Edit Complaint');
            $('#complaintId').val(complaint.ID);
            
            // Set Select2 values properly
            $('#customerId').val(complaint.CustomerID).trigger('change');
            $('#riceBagId').val(complaint.RiceBagID).trigger('change');
            
            $('#complaintType').val(complaint.ComplaintType);
            $('#priority').val(complaint.Priority);
            $('#complaintTitle').val(complaint.ComplaintTitle);
            $('#complaintDescription').val(complaint.ComplaintDescription);
            $('#status').val(complaint.Status);
            $('#resolution').val(complaint.Resolution || '');
            
            $('#statusGroup').show();
            if (complaint.Status === 'Resolved' || complaint.Status === 'Closed') {
                $('#resolutionGroup').show();
            }
            
            $('#complaintModal').modal('show');
        }

        function viewComplaint(id) {
            const complaint = currentData.find(c => c.ID == id);
            if (!complaint) return;
            
            const statusBadge = `<span class="status-badge status-${complaint.Status.toLowerCase().replace(' ', '-')}">${complaint.Status}</span>`;
            const priorityBadge = `<span class="badge badge-${complaint.Priority.toLowerCase() === 'high' ? 'danger' : complaint.Priority.toLowerCase() === 'medium' ? 'warning' : 'success'}">${complaint.Priority}</span>`;
            
            const html = `
                <div class="row">
                    <div class="col-md-8">
                        <h5>${complaint.ComplaintTitle}</h5>
                        <p><strong>ID:</strong> ${complaint.ComplaintNumber}</p>
                    </div>
                    <div class="col-md-4 text-right">
                        ${statusBadge}
                        ${priorityBadge}
                    </div>
                </div>
                <hr>
                <div class="row">
                    <div class="col-md-6">
                        <p><strong>Customer:</strong> ${complaint.CustomerName}</p>
                        <p><strong>Rice Bag:</strong> ${complaint.RiceBagName}</p>
                        <p><strong>Type:</strong> ${complaint.ComplaintType}</p>
                    </div>
                    <div class="col-md-6">
                        <p><strong>Date:</strong> ${formatDate(complaint.ComplaintDate)}</p>
                        <p><strong>Time:</strong> ${complaint.ComplaintTime}</p>
                        <p><strong>Created By:</strong> ${complaint.CreatedByName}</p>
                    </div>
                </div>
                <div class="form-group">
                    <label><strong>Description:</strong></label>
                    <p>${complaint.ComplaintDescription}</p>
                </div>
                ${complaint.Resolution ? `
                    <div class="form-group">
                        <label><strong>Resolution:</strong></label>
                        <p>${complaint.Resolution}</p>
                        ${complaint.ResolvedDate ? `<small class="text-muted">Resolved on: ${formatDate(complaint.ResolvedDate)}</small>` : ''}
                    </div>
                ` : ''}
            `;
            
            $('#viewModalBody').html(html);
            $('#viewModal').data('complaint-id', id).modal('show');
        }

        function editFromView() {
            const id = $('#viewModal').data('complaint-id');
            $('#viewModal').modal('hide');
            setTimeout(() => editComplaint(id), 300);
        }

        function saveComplaint() {
            const formData = new FormData($('#complaintForm')[0]);
            const data = {};
            
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }
            
            const url = editingId ? 'api/complaints.php' : 'api/complaints.php';
            const method = editingId ? 'PUT' : 'POST';
            
            $.ajax({
                url: url,
                method: method,
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function(response) {
                    if (response.success) {
                        $('#complaintModal').modal('hide');
                        showSuccess(response.message || 'Complaint saved successfully!');
                        loadComplaintsData();
                        loadStats();
                    } else {
                        showError('Error: ' + (response.message || 'Failed to save complaint'));
                    }
                },
                error: function() {
                    showError('Failed to save complaint. Please try again.');
                }
            });
        }

        function quickStatusChange(id, newStatus) {
            if (confirm(`Change status to "${newStatus}"?`)) {
                $.ajax({
                    url: 'api/complaints.php',
                    method: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        complaint_id: id,
                        status: newStatus
                    }),
                    success: function(response) {
                        if (response.success) {
                            showSuccess('Status updated successfully!');
                            loadComplaintsData();
                            loadStats();
                        } else {
                            showError('Error: ' + (response.message || 'Failed to update status'));
                        }
                    },
                    error: function() {
                        showError('Failed to update status. Please try again.');
                        loadComplaintsData(); // Reload to reset the dropdown
                    }
                });
            } else {
                loadComplaintsData(); // Reset dropdown if cancelled
            }
        }

        function deleteComplaint(id) {
            if (confirm('Are you sure you want to delete this complaint? This action cannot be undone.')) {
                $.ajax({
                    url: `api/complaints.php?id=${id}`,
                    method: 'DELETE',
                    success: function(response) {
                        if (response.success) {
                            showSuccess('Complaint deleted successfully!');
                            loadComplaintsData();
                            loadStats();
                        } else {
                            showError('Error: ' + (response.message || 'Failed to delete complaint'));
                        }
                    },
                    error: function() {
                        showError('Failed to delete complaint. Please try again.');
                    }
                });
            }
        }

        function loadCustomers() {
            $.ajax({
                url: 'api/get-customers-search.php',
                method: 'GET',
                success: function(response) {
                    if (response.success && response.data) {
                        let options = '<option value="">Search and select customer...</option>';
                        response.data.forEach(customer => {
                            // Include customer name and any available contact info for better search
                            const displayText = customer.CustomerName + 
                                (customer.Mobile ? ` (${customer.Mobile})` : '') +
                                (customer.Area ? ` - ${customer.Area}` : '');
                            options += `<option value="${customer.ID}">${displayText}</option>`;
                        });
                        $('#customerId').html(options);
                        
                        // Reinitialize Select2 after loading data
                        if ($('#customerId').hasClass('select2-hidden-accessible')) {
                            $('#customerId').select2('destroy');
                        }
                        $('#customerId').select2({
                            placeholder: 'Search and select customer...',
                            allowClear: true,
                            dropdownParent: $('#complaintModal'),
                            width: '100%'
                        });
                    }
                },
                error: function() {
                    console.log('Failed to load customers');
                }
            });
        }

        function loadRiceBags() {
            $.ajax({
                url: 'api/get-rice-bag.php',
                method: 'GET',
                success: function(response) {
                    if (response.success && response.data) {
                        let options = '<option value="">Search and select rice bag...</option>';
                        response.data.forEach(bag => {
                            // Include product name, brand, and category for better search
                            const displayText = (bag.ProductName || bag.RiceBagName || 'Rice Bag') +
                                (bag.Brand ? ` - ${bag.Brand}` : '') +
                                (bag.Category ? ` (${bag.Category})` : '');
                            options += `<option value="${bag.ID}">${displayText}</option>`;
                        });
                        $('#riceBagId').html(options);
                        
                        // Reinitialize Select2 after loading data
                        if ($('#riceBagId').hasClass('select2-hidden-accessible')) {
                            $('#riceBagId').select2('destroy');
                        }
                        $('#riceBagId').select2({
                            placeholder: 'Search and select rice bag...',
                            allowClear: true,
                            dropdownParent: $('#complaintModal'),
                            width: '100%'
                        });
                    }
                },
                error: function() {
                    console.log('Failed to load rice bags');
                }
            });
        }

        function loadStats() {
            $.ajax({
                url: 'api/complaints.php?action=stats',
                method: 'GET',
                success: function(response) {
                    if (response.success && response.stats) {
                        const stats = response.stats;
                        $('#totalCount').text(Object.values(stats).reduce((a, b) => a + b, 0));
                        $('#pendingCount').text(stats.Pending || 0);
                        $('#progressCount').text(stats['In Progress'] || 0);
                        $('#resolvedCount').text(stats.Resolved || 0);
                    }
                }
            });
        }

        function updateStats() {
            const total = currentData.length;
            const pending = currentData.filter(c => c.Status === 'Pending').length;
            const progress = currentData.filter(c => c.Status === 'In Progress').length;
            const resolved = currentData.filter(c => c.Status === 'Resolved').length;
            
            $('#totalCount').text(total);
            $('#pendingCount').text(pending);
            $('#progressCount').text(progress);
            $('#resolvedCount').text(resolved);
        }

        function refreshData() {
            loadComplaintsData();
            loadStats();
            showSuccess('Data refreshed successfully!');
        }

        function showLoading() {
            $('#complaintsGrid').html(`
                <div class="loading-state">
                    <div class="loading-spinner"></div>
                    <h5>Loading complaints...</h5>
                    <p>Please wait while we fetch the data.</p>
                </div>
            `);
            $('#emptyState').hide();
        }

        function showSuccess(message) {
            // You can implement toast notifications here
            alert(message);
        }

        function showError(message) {
            alert(message);
        }

        function formatDate(dateStr) {
            if (!dateStr) return 'N/A';
            const date = new Date(dateStr);
            return date.toLocaleDateString('en-US', { 
                year: 'numeric', 
                month: 'short', 
                day: 'numeric' 
            });
        }

        // Date Filter Functions - Make them globally accessible
        window.openDateFilterModal = function() {
            $('#dateFilterModal').modal('show');
        }
        
        window.applyDateFilter = function(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);
                    let 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);
                    dayOfWeek = today.getDay();
                    lastWeekEnd.setDate(today.getDate() - dayOfWeek - 1);
                    lastWeekStart.setDate(today.getDate() - dayOfWeek - 7);
                    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 lastMonthStart = new Date(today.getFullYear(), today.getMonth() - 1, 1);
                    const lastMonthEnd = new Date(today.getFullYear(), today.getMonth(), 0);
                    fromDate = lastMonthStart.toISOString().split('T')[0];
                    toDate = lastMonthEnd.toISOString().split('T')[0];
                    break;
            }
            
            applyDateRangeFilter(fromDate, toDate, filterType);
        }
        
        window.applyCustomDateFilter = function() {
            const fromDate = $('#customFromDate').val();
            const toDate = $('#customToDate').val();
            
            if (!fromDate || !toDate) {
                alert('Please select both from and to dates');
                return;
            }
            
            if (fromDate > toDate) {
                alert('From date cannot be later than to date');
                return;
            }
            
            applyDateRangeFilter(fromDate, toDate, 'custom');
        }
        
        window.applyDateRangeFilter = function(fromDate, toDate, filterType) {
            // Filter the current data based on date range
            const filteredData = currentData.filter(complaint => {
                const complaintDate = complaint.ComplaintDate;
                return complaintDate >= fromDate && complaintDate <= toDate;
            });
            
            renderComplaints(filteredData);
            
            // Update UI to show filter is active
            const filterText = getFilterText(filterType, fromDate, toDate);
            showActiveFilter(filterText);
            
            $('#dateFilterModal').modal('hide');
        }
        
        window.getFilterText = function(filterType, fromDate, toDate) {
            switch(filterType) {
                case 'today': return 'Today';
                case 'yesterday': return 'Yesterday';
                case 'this_week': return 'This Week';
                case 'last_week': return 'Last Week';
                case 'this_month': return 'This Month';
                case 'last_month': return 'Last Month';
                case 'custom': return `${fromDate} to ${toDate}`;
                default: return 'Date Range';
            }
        }
        
        window.showActiveFilter = function(filterText) {
            // Update header to show active filter
            $('.header-title span').text(`Complaints Management - Filtered by ${filterText}`);
            
            // Show clear filter option in header
            if (!$('.clear-filter-btn').length) {
                $('.header-actions').prepend(`
                    <button class="btn btn-outline-light btn-modern clear-filter-btn" onclick="clearDateFilter()">
                        <i class="fas fa-times mr-2"></i>Clear Filter
                    </button>
                `);
            }
        }
        
        window.clearDateFilter = function() {
            // Reset to show all data
            renderComplaints(currentData);
            
            // Reset header
            $('.header-title span').text('Complaints Management');
            $('.clear-filter-btn').remove();
            
            // Clear custom date inputs
            $('#customFromDate, #customToDate').val('');
            
            $('#dateFilterModal').modal('hide');
            showSuccess('Date filter cleared');
        }
    </script>
</body>
</html>