Mini Shell

Direktori : /home/mhcadmin/www/Portal/
Upload File :
Current File : /home/mhcadmin/www/Portal/Complaints.php

<?php
session_start();
$rootPath = dirname(__FILE__); // Current directory
require_once $rootPath . '/config/config.php';
require_once $rootPath . '/include/auth_validate.php';
include_once 'include/AdminHeader.php';

$userId = mysqli_real_escape_string($conn, $_SESSION['id']); // Get current user ID

// Check if user has Administrator access level and get user data including UserAccessName, Region, and UserDepartment
$userQuery = mysqli_query($conn, "SELECT Access_Level, Full_Name, HOD, Position, Region, UserAccessName, UserDepartment FROM admin_accounts WHERE id = '$userId'");
if (!$userQuery) {
    die("Database query failed: " . mysqli_error($conn));
}
$userData = mysqli_fetch_assoc($userQuery);
$isAdmin = ($userData['Access_Level'] == 'Administrator') ? true : false;
$currentUserName = $userData['Full_Name'];
$sessionUserRegion = trim($userData['Region']); // Store session user's region
$sessionUserDepartment = trim($userData['UserDepartment']); // Store session user's department
$currentUserIsHOD = ($userData['HOD'] == '1');
$currentUserPosition = !empty($userData['Position']) ? $userData['Position'] : 'Staff';
$userAccessName = isset($userData['UserAccessName']) ? $userData['UserAccessName'] : '';

// Initialize permission variables
$Manage_Regional_Users = 0;
$Manage_All_Users = 0;

// Fetch permissions from accesslevelmanagement table based on UserAccessName
if (!empty($userAccessName)) {
    $accessQuery = mysqli_query($conn, "SELECT View_Reg_Files, View_All_Files FROM accesslevelmanagement WHERE AccessName = '$userAccessName'");
    if ($accessQuery && mysqli_num_rows($accessQuery) > 0) {
        $accessData = mysqli_fetch_assoc($accessQuery);
        $Manage_Regional_Users = isset($accessData['View_Reg_Files']) ? (int)$accessData['View_Reg_Files'] : 0;
        $Manage_All_Users = isset($accessData['View_All_Files']) ? (int)$accessData['View_All_Files'] : 0;
    }
}

// Get Input data from query string with proper escaping
$search_string = isset($_GET['search_string']) ? mysqli_real_escape_string($conn, $_GET['search_string']) : '';
$filter_col = isset($_GET['filter_col']) ? mysqli_real_escape_string($conn, $_GET['filter_col']) : '';
$order_by = isset($_GET['order_by']) ? mysqli_real_escape_string($conn, $_GET['order_by']) : '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$pagelimit = 10;

if (!$filter_col) {
    $filter_col = "ComplaintID";
}
if (!$order_by) {
    $order_by = "Desc";
}

// Calculate offset for pagination
$offset = ($page - 1) * $pagelimit;

// Build the WHERE clause based on user permissions
$whereClause = "";

if ($Manage_All_Users == 1) {
    // User can see ALL complaints (no filtering)
    $whereClause = "1=1";
} elseif ($Manage_Regional_Users == 1) {
    // User can see complaints where BOTH Region AND Department match for users involved
    // Check Assigned_To, Originated_From, and response users (From, UserID)
    $whereClause = "(
        -- Check if Assigned_To user matches BOTH Region AND Department of session user
        EXISTS (
            SELECT 1 FROM admin_accounts a 
            WHERE a.id = c.Assigned_To 
            AND a.Region IS NOT NULL
            AND a.UserDepartment IS NOT NULL
            AND TRIM(a.Region) = TRIM('$sessionUserRegion')
            AND TRIM(a.UserDepartment) = TRIM('$sessionUserDepartment')
        )
        -- OR Check if Originated_From user matches BOTH Region AND Department of session user
        OR EXISTS (
            SELECT 1 FROM admin_accounts a 
            WHERE a.id = c.Originated_From 
            AND a.Region IS NOT NULL
            AND a.UserDepartment IS NOT NULL
            AND TRIM(a.Region) = TRIM('$sessionUserRegion')
            AND TRIM(a.UserDepartment) = TRIM('$sessionUserDepartment')
        )
        -- OR Check if there are responses from users that match BOTH Region AND Department
        OR EXISTS (
            SELECT 1 FROM responce_trend rt
            LEFT JOIN admin_accounts a1 ON rt.`From` = a1.id
            LEFT JOIN admin_accounts a2 ON rt.UserID = a2.id
            WHERE rt.ComplaintID = c.ComplaintID
            AND (
                (a1.Region IS NOT NULL AND a1.UserDepartment IS NOT NULL 
                 AND TRIM(a1.Region) = TRIM('$sessionUserRegion') 
                 AND TRIM(a1.UserDepartment) = TRIM('$sessionUserDepartment'))
                OR (a2.Region IS NOT NULL AND a2.UserDepartment IS NOT NULL 
                 AND TRIM(a2.Region) = TRIM('$sessionUserRegion') 
                 AND TRIM(a2.UserDepartment) = TRIM('$sessionUserDepartment'))
            )
        )
    )";
} else {
    // Regular user - only see their own complaints
    $whereClause = "(
        -- User created the complaint
        c.Originated_From = '$userId'
        -- OR User is assigned to the complaint
        OR c.Assigned_To = '$userId'
        -- OR User has responded to the complaint (either as From or UserID in responce_trend)
        OR c.ComplaintID IN (
            SELECT DISTINCT ComplaintID 
            FROM responce_trend 
            WHERE `From` = '$userId' OR UserID = '$userId'
        )
        -- OR User is the attention user (Atentioned_User)
        OR c.Atentioned_User = '$userId'
    )";
}

// Build the SQL query to get complaints with joins for names and positions
$sql = "SELECT DISTINCT c.*, 
        a1.Full_Name as Assigned_Full_Name, a1.HOD as Assigned_HOD, a1.Position as Assigned_Position, a1.Region as Assigned_Region, a1.UserDepartment as Assigned_Department,
        a2.Full_Name as Attention_Full_Name, a2.HOD as Attention_HOD, a2.Position as Attention_Position, a2.Region as Attention_Region, a2.UserDepartment as Attention_Department,
        a3.Full_Name as Originator_Full_Name, a3.HOD as Originator_HOD, a3.Position as Originator_Position, a3.Region as Originator_Region, a3.UserDepartment as Originator_Department
        FROM complaints c 
        LEFT JOIN admin_accounts a1 ON c.Assigned_To = a1.id
        LEFT JOIN admin_accounts a2 ON c.Atentioned_User = a2.id
        LEFT JOIN admin_accounts a3 ON c.Originated_From = a3.id
        WHERE $whereClause";

// Add search filter if provided
if ($search_string) {
    $sql .= " AND (c.Heading LIKE '%$search_string%' OR c.Name LIKE '%$search_string%')";
}

// Add order by
$order_col = mysqli_real_escape_string($conn, $filter_col);
$order_dir = ($order_by == 'Asc') ? 'ASC' : 'DESC';
$sql .= " ORDER BY c.$order_col $order_dir";

// Add pagination
$sql .= " LIMIT $offset, $pagelimit";

// Execute query to get records
$result = mysqli_query($conn, $sql);
if (!$result) {
    die("Database query failed: " . mysqli_error($conn) . "<br>SQL: " . $sql);
}

$complaints = [];
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $complaints[] = $row;
    }
}

// Get total count for pagination
$countSql = "SELECT COUNT(DISTINCT c.ComplaintID) as total FROM complaints c WHERE $whereClause";

if ($search_string) {
    $countSql .= " AND (c.Heading LIKE '%$search_string%' OR c.Name LIKE '%$search_string%')";
}

$countResult = mysqli_query($conn, $countSql);
$total_records = 0;
if ($countResult && mysqli_num_rows($countResult) > 0) {
    $countRow = mysqli_fetch_assoc($countResult);
    $total_records = $countRow['total'];
}
$total_pages = ceil($total_records / $pagelimit);

// Get filter options from the first record or default
$filter_options = ['ComplaintID', 'Heading', 'Name', 'Status', 'Department'];

// Get unique ComplaintIDs from responce_trend for additional info if needed
$responseData = [];
$responseQuery = mysqli_query($conn, "SELECT DISTINCT ComplaintID, `From`, UserID FROM responce_trend");
if ($responseQuery && mysqli_num_rows($responseQuery) > 0) {
    while ($row = mysqli_fetch_assoc($responseQuery)) {
        $responseData[$row['ComplaintID']][] = $row;
    }
}

// Helper function to format user display with position from Position column
function formatUserDisplay($fullName, $position) {
    if (empty($fullName)) {
        return 'Not Assigned';
    }
    $displayPosition = !empty($position) ? $position : 'Staff';
    return htmlspecialchars($fullName, ENT_QUOTES, 'UTF-8') . " (" . htmlspecialchars($displayPosition, ENT_QUOTES, 'UTF-8') . ")";
}

// Helper function to get access level display
function getAccessLevelDisplay($manageAll, $manageRegional) {
    if ($manageAll == 1) {
        return '<span class="role-badge" style="background: linear-gradient(135deg, #e74c3c, #c0392b);"><i class="fas fa-globe"></i> Full Access</span>';
    } elseif ($manageRegional == 1) {
        return '<span class="role-badge" style="background: linear-gradient(135deg, #3498db, #2980b9);"><i class="fas fa-building"></i> Regional & Department Access</span>';
    } else {
        return '<span class="role-badge" style="background: linear-gradient(135deg, #95a5a6, #7f8c8d);"><i class="fas fa-user"></i> Personal Access</span>';
    }
}
?>

<!-- Add Font Awesome and Bootstrap Select -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js"></script>

<style>
    /* BEAUTIFUL STYLING - Based on reference file */
    :root {
        --primary-green: #2ecc71;
        --dark-green: #27ae60;
        --light-green: #d4edda;
        --soft-white: #f8f9fa;
        --pure-white: #ffffff;
        --light-gray: #e9ecef;
        --medium-gray: #ced4da;
        --dark-gray: #495057;
        --charcoal: #343a40;
        --black: #212529;
        --shadow: 0 2px 4px rgba(0,0,0,0.1);
        --warning-color: #ffc107;
        --danger-color: #dc3545;
        --info-color: #17a2b8;
        --regional-color: #3498db;
    }

    body {
        background-color: #f0f2f5;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }

    #page-wrapper {
        min-height: 100vh;
        padding: 15px;
    }

    /* Main Container */
    .form-container {
        max-width: 1400px;
        margin: 0 auto;
    }

    /* Header Styles */
    .page-header {
        background: var(--pure-white);
        padding: 15px 25px;
        border-radius: 8px;
        margin: 0 0 20px 0;
        box-shadow: var(--shadow);
        border-left: 4px solid var(--primary-green);
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-wrap: wrap;
        gap: 15px;
    }

    .page-header h1 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: var(--black);
        display: flex;
        align-items: center;
        gap: 10px;
        flex-wrap: wrap;
    }

    .page-header h1 i {
        color: var(--primary-green);
        font-size: 24px;
    }

    /* Action Buttons */
    .action-buttons {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
    }

    .btn-custom {
        padding: 8px 16px;
        border-radius: 6px;
        font-weight: 500;
        font-size: 13px;
        text-transform: uppercase;
        letter-spacing: 0.3px;
        transition: all 0.2s ease;
        border: none;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        gap: 6px;
        text-decoration: none;
    }

    .btn-custom i {
        font-size: 14px;
    }

    .btn-custom-primary {
        background: var(--pure-white);
        color: var(--black);
        border: 1px solid var(--light-gray);
    }

    .btn-custom-primary:hover {
        background: var(--light-gray);
        text-decoration: none;
        color: var(--black);
    }

    .btn-custom-success {
        background: var(--primary-green);
        color: var(--pure-white);
    }

    .btn-custom-success:hover {
        background: var(--dark-green);
        text-decoration: none;
        color: var(--pure-white);
    }

    /* Role Badge */
    .role-badge {
        background: linear-gradient(135deg, #3498db, #2980b9);
        color: white;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 11px;
        font-weight: 600;
        display: inline-flex;
        align-items: center;
        gap: 5px;
        margin-left: 10px;
    }
    
    .region-badge {
        background: linear-gradient(135deg, #9b59b6, #8e44ad);
        color: white;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 11px;
        font-weight: 600;
        display: inline-flex;
        align-items: center;
        gap: 5px;
    }
    
    .department-badge {
        background: linear-gradient(135deg, #f39c12, #e67e22);
        color: white;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 11px;
        font-weight: 600;
        display: inline-flex;
        align-items: center;
        gap: 5px;
    }

    /* Alert Messages */
    .alert-custom {
        padding: 12px 18px;
        border-radius: 6px;
        margin-bottom: 20px;
        border: none;
        display: flex;
        align-items: center;
        gap: 12px;
        font-size: 14px;
        box-shadow: var(--shadow);
    }

    .alert-custom i {
        font-size: 18px;
    }

    .alert-custom-success {
        background: var(--light-green);
        color: var(--dark-green);
        border-left: 4px solid var(--primary-green);
    }

    .alert-custom-danger {
        background: #f8d7da;
        color: #721c24;
        border-left: 4px solid var(--danger-color);
    }
    
    .alert-custom-info {
        background: #d1ecf1;
        color: #0c5460;
        border-left: 4px solid var(--info-color);
    }

    /* Filter Section - One Line */
    .filter-section {
        background: var(--pure-white);
        border-radius: 8px;
        padding: 15px 20px;
        margin-bottom: 20px;
        box-shadow: var(--shadow);
        border: 1px solid var(--light-gray);
        overflow-x: auto;
    }

    .filter-form {
        display: flex;
        align-items: center;
        gap: 15px;
        min-width: min-content;
        flex-wrap: wrap;
    }

    .filter-form .form-control {
        height: 38px;
        border: 1px solid var(--light-gray);
        border-radius: 6px;
        padding: 0 10px;
        font-size: 13px;
        background: var(--pure-white);
    }

    .filter-form .form-control:focus {
        border-color: var(--primary-green);
        outline: none;
        box-shadow: 0 0 0 2px rgba(46, 204, 113, 0.1);
    }

    .filter-form .btn-primary {
        height: 38px;
        padding: 0 20px;
        background: var(--primary-green);
        border: none;
        border-radius: 6px;
        color: white;
        font-weight: 500;
        font-size: 13px;
        display: flex;
        align-items: center;
        gap: 5px;
        white-space: nowrap;
        cursor: pointer;
    }

    .filter-form .btn-primary:hover {
        background: var(--dark-green);
    }

    .filter-label {
        display: flex;
        align-items: center;
        gap: 5px;
        color: var(--dark-gray);
        font-weight: 500;
        font-size: 13px;
        white-space: nowrap;
    }

    .filter-label i {
        color: var(--primary-green);
        font-size: 14px;
    }

    /* Table Styles - Beautiful Design */
    .table-container {
        background: var(--pure-white);
        border-radius: 10px;
        padding: 15px;
        box-shadow: var(--shadow);
        margin-bottom: 20px;
        overflow-x: auto;
    }

    .table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 0;
    }

    .table thead tr {
        background: linear-gradient(135deg, var(--charcoal) 0%, var(--black) 100%);
    }

    .table thead th {
        padding: 12px 10px;
        color: var(--pure-white);
        font-weight: 500;
        font-size: 13px;
        text-transform: uppercase;
        letter-spacing: 0.3px;
        border: none;
        white-space: nowrap;
    }

    .table thead th:first-child {
        border-radius: 6px 0 0 6px;
    }

    .table thead th:last-child {
        border-radius: 0 6px 6px 0;
    }

    .table tbody tr {
        border-bottom: 1px solid var(--light-gray);
        transition: background-color 0.2s ease;
    }

    .table tbody tr:hover {
        background-color: rgba(46, 204, 113, 0.05);
    }

    .table tbody td {
        padding: 12px 10px;
        color: var(--dark-gray);
        font-size: 13px;
        vertical-align: middle;
    }

    .table tbody td h5 {
        margin: 0;
        font-size: 13px;
        font-weight: 500;
        color: var(--black);
    }

    .table tbody td strong {
        font-size: 13px;
    }

    /* Status badges - clean text style */
    .status-badge {
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 11px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.2px;
        display: inline-block;
    }

    .status-open {
        background: #fef3f2;
        color: #e74c3c;
    }

    .status-in-progress {
        background: #fff4e6;
        color: #f39c12;
    }

    .status-closed {
        background: var(--light-green);
        color: var(--dark-green);
    }

    /* Origin Badges */
    .origin-badge {
        display: inline-block;
        padding: 3px 8px;
        border-radius: 12px;
        font-size: 10px;
        font-weight: 600;
        margin-top: 5px;
    }
    
    .origin-created {
        background: #e8f5e9;
        color: #2e7d32;
    }
    
    .origin-assigned {
        background: #e3f2fd;
        color: #1565c0;
    }
    
    .origin-response {
        background: #fff3e0;
        color: #e65100;
    }
    
    .origin-attention {
        background: #f3e5f5;
        color: #9b59b6;
    }
    
    .region-indicator {
        font-size: 10px;
        color: #7f8c8d;
        margin-top: 3px;
        display: inline-block;
    }
    
    .department-indicator {
        font-size: 10px;
        color: #f39c12;
        margin-top: 3px;
        display: inline-block;
    }

    /* Assigned Info */
    .assigned-info {
        display: flex;
        flex-direction: column;
        gap: 5px;
    }
    
    .sent-info {
        display: flex;
        align-items: center;
        gap: 5px;
    }
    
    .attention-info {
        display: flex;
        align-items: center;
        gap: 5px;
        margin-top: 5px;
        padding-top: 5px;
        border-top: 1px dashed var(--light-gray);
    }
    
    .sent-to-me {
        background: var(--light-green);
        padding: 2px 6px;
        border-radius: 4px;
        font-weight: 500;
        font-size: 11px;
    }
    
    .attention-to-me {
        background: #f3e5f5;
        padding: 2px 6px;
        border-radius: 4px;
        font-weight: 500;
        font-size: 11px;
        color: #9b59b6;
    }
    
    .origin-name {
        font-weight: 500;
        color: var(--charcoal);
        font-size: 12px;
    }
    
    .system-origin {
        background: #f8f9fa;
        color: #6c757d;
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 10px;
        border: 1px dashed #adb5bd;
    }

    /* Action Dropdown - Hover-based */
    .action-dropdown {
        position: relative;
        display: inline-block;
    }

    .action-toggle {
        background: var(--light-gray);
        border: none;
        padding: 8px 12px;
        border-radius: 6px;
        color: var(--dark-gray);
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 5px;
        font-size: 12px;
        transition: all 0.2s ease;
    }

    .action-toggle:hover {
        background: var(--primary-green);
        color: white;
    }

    /* Invisible bridge between button and menu */
    .action-dropdown::after {
        content: '';
        position: absolute;
        top: 100%;
        right: 0;
        width: 100%;
        height: 10px;
        background: transparent;
        z-index: 999;
    }

    .action-menu {
        position: absolute;
        right: 0;
        top: 100%;
        background: var(--pure-white);
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        min-width: 200px;
        z-index: 1000;
        visibility: hidden;
        opacity: 0;
        margin-top: 0;
        border: 1px solid var(--light-gray);
        transition: all 0.2s ease;
        transform: translateY(-10px);
        pointer-events: none;
    }

    /* Show menu on hover */
    .action-dropdown:hover .action-menu {
        visibility: visible;
        opacity: 1;
        transform: translateY(5px);
        pointer-events: all;
    }

    /* Also show when hovering menu itself */
    .action-menu:hover {
        visibility: visible;
        opacity: 1;
        transform: translateY(5px);
        pointer-events: all;
    }

    .action-menu-item {
        padding: 12px 15px;
        display: flex;
        align-items: center;
        gap: 12px;
        color: var(--dark-gray);
        text-decoration: none;
        font-size: 13px;
        transition: all 0.2s ease;
        border-bottom: 1px solid var(--light-gray);
        cursor: pointer;
        white-space: nowrap;
    }

    .action-menu-item:last-child {
        border-bottom: none;
    }

    .action-menu-item:hover {
        background: rgba(46, 204, 113, 0.1);
        color: var(--primary-green);
        text-decoration: none;
    }

    .action-menu-item i {
        width: 18px;
        font-size: 14px;
        text-align: center;
    }

    /* Modal Styles - Beautiful Design */
    .modal-content-custom {
        border-radius: 12px;
        border: none;
        box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        overflow: hidden;
    }

    .modal-header-custom {
        background: linear-gradient(135deg, var(--charcoal) 0%, var(--black) 100%);
        color: var(--pure-white);
        padding: 15px 20px;
        border-bottom: none;
        position: relative;
    }

    .modal-header-custom h4, .modal-header-custom h5 {
        margin: 0;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .modal-header-custom h4 i, .modal-header-custom h5 i {
        color: var(--primary-green);
        font-size: 20px;
    }

    .modal-header-custom .close {
        color: var(--pure-white);
        opacity: 0.8;
        text-shadow: none;
    }

    .modal-header-custom .close:hover {
        opacity: 1;
    }

    .modal-body-custom {
        padding: 20px;
        background: var(--soft-white);
    }

    .modal-footer-custom {
        padding: 15px 20px;
        background: var(--pure-white);
        border-top: 1px solid var(--light-gray);
    }

    /* Modal Buttons */
    .modal-btn {
        padding: 8px 20px;
        border-radius: 6px;
        font-weight: 500;
        font-size: 13px;
        text-transform: uppercase;
        letter-spacing: 0.3px;
        transition: all 0.2s ease;
        border: none;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    .modal-btn-primary {
        background: var(--primary-green);
        color: var(--pure-white);
    }

    .modal-btn-primary:hover {
        background: var(--dark-green);
    }

    .modal-btn-default {
        background: var(--light-gray);
        color: var(--dark-gray);
    }

    .modal-btn-default:hover {
        background: var(--medium-gray);
    }

    .modal-btn-danger {
        background: var(--danger-color);
        color: white;
    }

    .modal-btn-danger:hover {
        background: #c82333;
    }

    /* File Trail Table */
    .file-trail-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 13px;
    }
    
    .file-trail-table th {
        background: #f8f9fa;
        padding: 12px 10px;
        text-align: left;
        font-weight: 600;
        color: var(--charcoal);
        border-bottom: 2px solid var(--primary-green);
        font-size: 12px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    
    .file-trail-table td {
        padding: 12px 10px;
        border-bottom: 1px solid var(--light-gray);
        vertical-align: top;
        font-size: 12px;
    }

    /* Pagination */
    .pagination-container {
        text-align: center;
        margin-top: 20px;
    }

    .pagination {
        display: inline-flex;
        gap: 5px;
        list-style: none;
        padding: 0;
        margin: 0;
    }

    .pagination li {
        display: inline;
    }

    .pagination li a {
        display: inline-block;
        padding: 8px 12px;
        background: var(--pure-white);
        border: 1px solid var(--light-gray);
        border-radius: 6px;
        color: var(--dark-gray);
        font-size: 13px;
        text-decoration: none;
        transition: all 0.2s ease;
    }

    .pagination li.active a {
        background: var(--primary-green);
        color: white;
        border-color: var(--primary-green);
    }

    .pagination li a:hover {
        background: var(--light-gray);
    }

    /* Empty State */
    .empty-state {
        text-align: center;
        padding: 50px;
    }

    .empty-state i {
        font-size: 48px;
        color: var(--light-gray);
        margin-bottom: 15px;
    }

    .empty-state h4 {
        color: var(--dark-gray);
        margin-bottom: 10px;
    }

    .empty-state p {
        color: #95a5a6;
    }

    /* Responsive */
    @media (max-width: 992px) {
        .filter-section {
            overflow-x: auto;
        }
        
        .filter-form {
            min-width: 700px;
        }
    }

    @media (max-width: 768px) {
        .page-header {
            flex-direction: column;
            text-align: center;
        }
        
        .table-container {
            overflow-x: auto;
        }
    }
</style>

<div id="page-wrapper">
    <div class="form-container">
        <!-- Header Section -->
        <div class="page-header">
            <h1>
                <i class="fas fa-folder-open"></i>
                File Records
                <?php echo getAccessLevelDisplay($Manage_All_Users, $Manage_Regional_Users); ?>
                <?php if ($Manage_Regional_Users == 1 && !empty($sessionUserRegion)): ?>
                    <span class="region-badge"><i class="fas fa-map-marker-alt"></i> Region: <?php echo htmlspecialchars($sessionUserRegion, ENT_QUOTES, 'UTF-8'); ?></span>
                <?php endif; ?>
                <?php if ($Manage_Regional_Users == 1 && !empty($sessionUserDepartment)): ?>
                    <span class="department-badge"><i class="fas fa-building"></i> Department: <?php echo htmlspecialchars($sessionUserDepartment, ENT_QUOTES, 'UTF-8'); ?></span>
                <?php endif; ?>
            </h1>
            <div class="action-buttons">
                <?php if ($Add_File  == 1) { ?>
                <a href="add_complaint.php?operation=create" class="btn-custom btn-custom-success">
                    <i class="fas fa-plus-circle"></i>
                    Add New
                </a>
               <?php } ?>
                <a href="Complaints.php" class="btn-custom btn-custom-primary">
                    <i class="fas fa-sync-alt"></i>
                    Refresh
                </a>
            </div>
        </div>
        
        <!-- Access Info Alert -->
        <?php if ($Manage_All_Users == 1): ?>
        <div class="alert-custom alert-custom-info">
            <i class="fas fa-globe"></i>
            <div><strong>Full System Access:</strong> You can view and manage all Tasks in the system.</div>
        </div>
        <?php elseif ($Manage_Regional_Users == 1): ?>
        <div class="alert-custom alert-custom-info">
            <i class="fas fa-building"></i>
            <div>
                <strong>Regional & Department Access:</strong> You can view Tasks where users involved (Assigned To, Originator, or Respondents) have BOTH the same Region AND Department as you.<br>
                <strong>Your Region:</strong> <?php echo htmlspecialchars($sessionUserRegion, ENT_QUOTES, 'UTF-8'); ?><br>
                <strong>Your Department:</strong> <?php echo htmlspecialchars($sessionUserDepartment, ENT_QUOTES, 'UTF-8'); ?>
            </div>
        </div>
        <?php else: ?>
        <div class="alert-custom alert-custom-info">
            <i class="fas fa-user"></i>
            <div><strong>Personal Access:</strong> You can only view Tasks you created, are assigned to, have responded to, or have been attentioned to.</div>
        </div>
        <?php endif; ?>
        
        <!-- Alert Messages -->
        <?php include('./include/flash_messages.php') ?>
        
        <!-- Filter Section - All in One Line -->
        <div class="filter-section">
            <form class="filter-form" action="">
                <div class="filter-label">
                    <i class="fas fa-search"></i>
                    <span>Search</span>
                </div>
                <input type="text" class="form-control" id="input_search" placeholder="Name or Heading" name="search_string" 
                       value="<?php echo htmlspecialchars($search_string ?? '', ENT_QUOTES, 'UTF-8'); ?>" style="width: 200px;">
                
                <div class="filter-label" style="margin-left: 5px;">
                    <i class="fas fa-sort"></i>
                    <span>Order By</span>
                </div>
                <select name="filter_col" class="form-control" style="width: 130px;">
                    <?php
                    foreach ($filter_options as $option) {
                        $selected = ($filter_col === $option) ? "selected" : "";
                        echo '<option value="' . htmlspecialchars($option ?? '', ENT_QUOTES, 'UTF-8') . '" ' . $selected . '>' . htmlspecialchars($option ?? '', ENT_QUOTES, 'UTF-8') . '</option>';
                    }
                    ?>
                </select>

                <select name="order_by" class="form-control" id="input_order" style="width: 100px;">
                    <option value="Asc" <?php echo ($order_by == 'Asc') ? "selected" : ""; ?>>Asc</option>
                    <option value="Desc" <?php echo ($order_by == 'Desc') ? "selected" : ""; ?>>Desc</option>
                </select>
                
                <button type="submit" class="btn-primary">
                    <i class="fas fa-filter"></i> Go
                </button>
            </form>
        </div>
        
        <!-- Table Section -->
        <div class="table-container">
            <table class="table">
                <thead>
                    <tr>
                        <th>Heading</th>
                        <th>Client Name</th>
                        <th>Task</th>
                        <th>Sent To</th>
                        <th>Status</th>
                        <th>Origin</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($complaints)): ?>
                        <tr>
                            <td colspan="7" class="empty-state">
                                <i class="fas fa-folder-open"></i>
                                <h4>No records found</h4>
                                <?php if ($Manage_All_Users == 1): ?>
                                    <p>No Tasks found in the system. Click "Add New" to create one.</p>
                                <?php elseif ($Manage_Regional_Users == 1): ?>
                                    <p>No Tasks found where users involved (Assigned To, Originator, or Respondents) have BOTH Region '<strong><?php echo htmlspecialchars($sessionUserRegion, ENT_QUOTES, 'UTF-8'); ?></strong>' AND Department '<strong><?php echo htmlspecialchars($sessionUserDepartment, ENT_QUOTES, 'UTF-8'); ?></strong>'.</p>
                                <?php else: ?>
                                    <p>Records you create, are sent to you, have your attention, or you have responded to will appear here.</p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endif; ?>
                    
                    <?php foreach ($complaints as $row) : 
                        // Get assigned to name with position from Position column
                        $assignedToId = isset($row['Assigned_To']) ? $row['Assigned_To'] : '';
                        $assignedFullName = isset($row['Assigned_Full_Name']) ? $row['Assigned_Full_Name'] : '';
                        $assignedPosition = isset($row['Assigned_Position']) ? $row['Assigned_Position'] : '';
                        $assignedRegion = isset($row['Assigned_Region']) ? $row['Assigned_Region'] : '';
                        $assignedDepartment = isset($row['Assigned_Department']) ? $row['Assigned_Department'] : '';
                        $assignedDisplay = formatUserDisplay($assignedFullName, $assignedPosition);
                        
                        // Get attention user name with position from Position column
                        $attentionUserId = isset($row['Atentioned_User']) ? $row['Atentioned_User'] : '';
                        $attentionFullName = isset($row['Attention_Full_Name']) ? $row['Attention_Full_Name'] : '';
                        $attentionPosition = isset($row['Attention_Position']) ? $row['Attention_Position'] : '';
                        $attentionDisplay = '';
                        if (!empty($attentionFullName)) {
                            $attentionDisplay = formatUserDisplay($attentionFullName, $attentionPosition);
                        }
                        
                        // Get originator name with position from Position column
                        $originatorId = isset($row['Originated_From']) ? $row['Originated_From'] : '';
                        $originatorFullName = isset($row['Originator_Full_Name']) ? $row['Originator_Full_Name'] : '';
                        $originatorPosition = isset($row['Originator_Position']) ? $row['Originator_Position'] : '';
                        $originatorRegion = isset($row['Originator_Region']) ? $row['Originator_Region'] : '';
                        $originatorDepartment = isset($row['Originator_Department']) ? $row['Originator_Department'] : '';
                        
                        $originatorName = '';
                        if (!empty($originatorFullName)) {
                            $originatorName = formatUserDisplay($originatorFullName, $originatorPosition);
                        } else {
                            $originatorName = '<span class="system-origin"><i class="fas fa-cog"></i> System / Not Specified</span>';
                        }
                        
                        // Determine if this record is sent to current user
                        $isSentToMe = ($assignedToId == $userId);
                        
                        // Determine if this record has attention to current user
                        $isAttentionToMe = ($attentionUserId == $userId);
                        
                        // Determine relationship type (only for personal access)
                        $relationshipType = '';
                        $relationshipClass = '';
                        
                        if ($Manage_All_Users != 1 && $Manage_Regional_Users != 1) {
                            if ($originatorId == $userId) {
                                $relationshipType = 'Created by me';
                                $relationshipClass = 'origin-created';
                            } elseif ($assignedToId == $userId) {
                                $relationshipType = 'Sent to me';
                                $relationshipClass = 'origin-assigned';
                            } elseif ($attentionUserId == $userId) {
                                $relationshipType = 'My attention';
                                $relationshipClass = 'origin-attention';
                            } elseif (isset($responseData[$row['ComplaintID']])) {
                                foreach ($responseData[$row['ComplaintID']] as $response) {
                                    if ((isset($response['From']) && $response['From'] == $userId) || 
                                        (isset($response['UserID']) && $response['UserID'] == $userId)) {
                                        $relationshipType = 'My response';
                                        $relationshipClass = 'origin-response';
                                        break;
                                    }
                                }
                            }
                        }
                        
                        // Status class
                        $status = isset($row['Status']) ? $row['Status'] : '';
                        $statusClass = '';
                        if (strtolower((string)$status) == 'open' || strtolower((string)$status) == 'new') {
                            $statusClass = 'status-open';
                        } elseif (strpos(strtolower((string)$status), 'progress') !== false) {
                            $statusClass = 'status-in-progress';
                        } elseif (strtolower((string)$status) == 'closed' || strtolower((string)$status) == 'completed') {
                            $statusClass = 'status-closed';
                        } else {
                            $statusClass = 'status-open';
                        }
                    ?>
                        <tr>
                            <td>
                                <h5><?php echo isset($row['Heading']) ? htmlspecialchars((string)$row['Heading'], ENT_QUOTES, 'UTF-8') : ''; ?></h5>
                            </td>
                            <td>
                                <h5><?php echo isset($row['Name']) ? htmlspecialchars((string)$row['Name'], ENT_QUOTES, 'UTF-8') : ''; ?></h5>
                            </td>
                            <td>
                                <?php 
                                    $problem = isset($row['Problem']) ? $row['Problem'] : '';
                                    echo htmlspecialchars(substr((string)$problem, 0, 50), ENT_QUOTES, 'UTF-8') . (strlen((string)$problem) > 50 ? '...' : ''); 
                                ?>
                            </td>
                            <td>
                                <div class="assigned-info">
                                    <div class="sent-info">
                                        <i class="fas fa-paper-plane" style="color: var(--primary-green); font-size: 11px;"></i>
                                        <?php if ($isSentToMe): ?>
                                            <span class="sent-to-me">
                                                <i class="fas fa-hand-point-right"></i> 
                                                <strong>Sent to: Me</strong>
                                            </span>
                                        <?php else: ?>
                                            <span>Sent to: <?php echo $assignedDisplay; ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <?php if (!empty($assignedRegion) && ($Manage_All_Users == 1 || $Manage_Regional_Users == 1)): ?>
                                        <div class="region-indicator">
                                            <i class="fas fa-map-marker-alt"></i> Region: <?php echo htmlspecialchars($assignedRegion, ENT_QUOTES, 'UTF-8'); ?>
                                        </div>
                                    <?php endif; ?>
                                    <?php if (!empty($assignedDepartment) && ($Manage_All_Users == 1 || $Manage_Regional_Users == 1)): ?>
                                        <div class="department-indicator">
                                            <i class="fas fa-building"></i> Dept: <?php echo htmlspecialchars($assignedDepartment, ENT_QUOTES, 'UTF-8'); ?>
                                        </div>
                                    <?php endif; ?>
                                    <?php if (!empty($attentionDisplay) && $attentionDisplay != 'Not Assigned'): ?>
                                        <div class="attention-info">
                                            <i class="fas fa-bell" style="font-size: 11px;"></i>
                                            <?php if ($isAttentionToMe): ?>
                                                <span class="attention-to-me">
                                                    <i class="fas fa-bell"></i> 
                                                    <strong>Attentioned to: Me</strong>
                                                </span>
                                            <?php else: ?>
                                                <span>Attentioned to: <?php echo $attentionDisplay; ?></span>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td>
                                <span class="status-badge <?php echo $statusClass; ?>"><?php echo htmlspecialchars((string)$status, ENT_QUOTES, 'UTF-8'); ?></span>
                            </td>
                            <td>
                                <div style="display: flex; flex-direction: column; gap: 5px;">
                                    <span class="origin-name">
                                        <i class="fas fa-user-circle" style="color: var(--primary-green);"></i>
                                        <?php echo $originatorName; ?>
                                    </span>
                                    <?php if (!empty($originatorRegion) && ($Manage_All_Users == 1 || $Manage_Regional_Users == 1)): ?>
                                        <div class="region-indicator">
                                            <i class="fas fa-map-marker-alt"></i> Region: <?php echo htmlspecialchars($originatorRegion, ENT_QUOTES, 'UTF-8'); ?>
                                        </div>
                                    <?php endif; ?>
                                    <?php if (!empty($originatorDepartment) && ($Manage_All_Users == 1 || $Manage_Regional_Users == 1)): ?>
                                        <div class="department-indicator">
                                            <i class="fas fa-building"></i> Dept: <?php echo htmlspecialchars($originatorDepartment, ENT_QUOTES, 'UTF-8'); ?>
                                        </div>
                                    <?php endif; ?>
                                    <?php if (!empty($relationshipType)): ?>
                                        <span class="origin-badge <?php echo $relationshipClass; ?>">
                                            <i class="fas fa-<?php echo ($relationshipClass == 'origin-created') ? 'plus-circle' : (($relationshipClass == 'origin-assigned') ? 'paper-plane' : (($relationshipClass == 'origin-attention') ? 'bell' : 'comment')); ?>"></i>
                                            <?php echo $relationshipType; ?>
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td>
                                <div class="action-dropdown">
                                    <button class="action-toggle" type="button">
                                        <i class="fas fa-cog"></i> Actions <i class="fas fa-chevron-down"></i>
                                    </button>
                                    <div class="action-menu">
                                        <a href="AddResponce.php?ComplaintID=<?php echo urlencode($row['ComplaintID'] ?? ''); ?>&operation=launch_complaint" class="action-menu-item">
                                            <i class="fas fa-plus" style="color: var(--primary-green);"></i> Respond
                                        </a>
                                        
                                        <a href="#" data-toggle="modal" data-target="#fileTrailModal-<?php echo $row['ComplaintID'] ?? ''; ?>" class="action-menu-item">
                                            <i class="fas fa-eye" style="color: #9b59b6;"></i> File Trail
                                        </a>
                                        
                                        <?php 
                                        // Show edit button ONLY if:
                                        // 1. Current user is the creator of the file
                                        // 2. There are no responses yet
                                        $ComplaintID = $row['ComplaintID'];
                                        $responseCheck = mysqli_query($conn, "SELECT COUNT(*) as response_count FROM responce_trend WHERE ComplaintID = '$ComplaintID'");
                                        $hasResponses = false;
                                        if ($responseCheck) {
                                            $responseData_count = mysqli_fetch_assoc($responseCheck);
                                            $hasResponses = ($responseData_count['response_count'] > 0);
                                        }
                                        
                                        // Check if current user is the creator AND there are no responses
                                        if ($originatorId == $userId && !$hasResponses) {
                                        ?>
                                            <a href="Edit_File.php?ComplaintID=<?php echo urlencode($row['ComplaintID'] ?? ''); ?>&operation=edit" class="action-menu-item">
                                                <i class="fas fa-edit" style="color: var(--primary-green);"></i> Edit file
                                            </a>
                                        <?php 
                                        }
                                        ?>
                                        
                                        <?php if ($Delete_File  == 1) { ?>
                                       
                                            <a href="#" data-toggle="modal" data-target="#deleteModal-<?php echo $row['ComplaintID'] ?? ''; ?>" class="action-menu-item">
                                                <i class="fas fa-trash-alt" style="color: var(--danger-color);"></i> Delete file
                                            </a>
                                       
                                        <?php } ?>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        
                        <!-- Delete Confirmation Modal -->
                        <div class="modal fade" id="deleteModal-<?php echo $row['ComplaintID'] ?? ''; ?>" tabindex="-1" role="dialog">
                            <div class="modal-dialog" role="document">
                                <div class="modal-content modal-content-custom">
                                    <div class="modal-header modal-header-custom">
                                        <h5 class="modal-title">
                                            <i class="fas fa-trash-alt" style="color: var(--danger-color);"></i>
                                            Confirm Delete
                                        </h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <form action="delete_customer.php" method="POST">
                                        <div class="modal-body modal-body-custom">
                                            <input type="hidden" name="del_id" value="<?php echo $row['ComplaintID'] ?? ''; ?>">
                                            <div style="text-align: center; padding: 20px;">
                                                <i class="fas fa-exclamation-triangle" style="font-size: 48px; color: var(--danger-color); margin-bottom: 15px;"></i>
                                                <p style="font-size: 16px; color: var(--dark-gray);">
                                                    Are you sure you want to delete this record?
                                                </p>
                                                <p style="font-size: 13px; color: #999;">This action cannot be undone.</p>
                                            </div>
                                        </div>
                                        <div class="modal-footer modal-footer-custom">
                                            <button type="button" class="modal-btn modal-btn-default" data-dismiss="modal">
                                                <i class="fas fa-times"></i> Cancel
                                            </button>
                                            <button type="submit" class="modal-btn modal-btn-danger">
                                                <i class="fas fa-trash-alt"></i> Delete
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        
                        <!-- File Trail Modal -->
                        <div class="modal fade" id="fileTrailModal-<?php echo $row['ComplaintID'] ?? ''; ?>" tabindex="-1" role="dialog">
                            <div class="modal-dialog modal-lg" role="document">
                                <div class="modal-content modal-content-custom">
                                    <div class="modal-header modal-header-custom">
                                        <h5 class="modal-title">
                                            <i class="fas fa-eye"></i>
                                            File Trail - Case History
                                        </h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="modal-body modal-body-custom">
                                        <div id="fileTrailContent-<?php echo $row['ComplaintID'] ?? ''; ?>">
                                            <p style="text-align: center; color: #666;"><i class="fas fa-spinner fa-spin"></i> Loading file trail...</p>
                                        </div>
                                    </div>
                                    <div class="modal-footer modal-footer-custom">
                                        <button type="button" class="modal-btn modal-btn-default" data-dismiss="modal">
                                            <i class="fas fa-times"></i> Close
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>      
                </tbody>
            </table>
        </div>

        <!-- Pagination links-->
        <?php if ($total_pages > 1): ?>
            <div class="pagination-container">
                <?php
                if (!empty($_GET)) {
                    $get_params = $_GET;
                    unset($get_params['page']);
                    $http_query = "?" . http_build_query($get_params);
                } else {
                    $http_query = "?";
                }
                ?>
                <ul class="pagination">
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="<?php echo ($page == $i) ? 'active' : ''; ?>">
                            <a href="Complaints.php<?php echo $http_query; ?>&page=<?php echo $i; ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </div>
        <?php endif; ?>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>

<script>
$(document).ready(function() {
    // Initialize Bootstrap Select
    $('.selectpicker').selectpicker({
        size: 5,
        dropupAuto: false
    });

    // Load file trail when modal is shown
    <?php foreach ($complaints as $row): ?>
    $('#fileTrailModal-<?php echo $row['ComplaintID'] ?? ''; ?>').on('show.bs.modal', function(e) {
        var complaintId = '<?php echo $row['ComplaintID'] ?? ''; ?>';
        var contentDiv = $('#fileTrailContent-' + complaintId);
        contentDiv.html('<p style="text-align: center; color: #666;"><i class="fas fa-spinner fa-spin"></i> Loading file trail...</p>');
        
        // AJAX request to fetch file trail data
        $.ajax({
            url: 'get_file_trail.php',
            type: 'GET',
            data: { complaint_id: complaintId },
            dataType: 'html',
            success: function(response) {
                contentDiv.html(response);
            },
            error: function() {
                contentDiv.html('<p style="text-align: center; color: #e74c3c;"><i class="fas fa-exclamation-triangle"></i> Error loading file trail. Please try again.</p>');
            }
        });
    });
    <?php endforeach; ?>
});
</script>

<?php include_once './include/footer.php'; ?>