Mini Shell

Direktori : /home/mhcadmin/.trash/IMS/
Upload File :
Current File : /home/mhcadmin/.trash/IMS/AddResponce.php

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

// ============================================
// CHECK RESPONCE_TREND TABLE FOR HISTORY
// ============================================
$ComplaintID = filter_input(INPUT_GET, 'ComplaintID', FILTER_VALIDATE_INT);
$operation = filter_input(INPUT_GET, 'operation', FILTER_SANITIZE_FULL_SPECIAL_CHARS); 
($operation == 'edit') ? $edit = true : $edit = true;

$db = getDbInstance();

// Initialize arrays
$complaints = array();
$showHistory = false;
$forwardedFrom = '';
$previousRemarks = [];

// Check for history if ComplaintID exists
if ($ComplaintID) {
    // Check if there are any records in responce_trend for this ComplaintID
    // Note: `From` is a reserved word in MySQL, so we need to escape it with backticks
    $historyQuery = "SELECT rt.*, 
                     aa.Full_Name as AdminName,
                     from_admin.Full_Name as FromAdminName
                     FROM responce_trend rt
                     LEFT JOIN admin_accounts aa ON rt.UserID = aa.id
                     LEFT JOIN admin_accounts from_admin ON rt.`From` = from_admin.id
                     WHERE rt.ComplaintID = '$ComplaintID'
                     ORDER BY rt.Responce_TrendID DESC";
    
    $historyResult = mysqli_query($connection, $historyQuery);
    
    if ($historyResult && mysqli_num_rows($historyResult) > 0) {
        $showHistory = true;
        $allRecords = [];
        
        while ($row = mysqli_fetch_assoc($historyResult)) {
            $allRecords[] = $row;
        }
        
        // Debug - log what we found
        error_log("Found " . count($allRecords) . " records for ComplaintID: " . $ComplaintID);
        
        // FIRST: Get the last record (first in array since we ordered DESC)
        if (!empty($allRecords)) {
            $lastRecord = $allRecords[0]; // Most recent record
            
            // For Forwarded_From, we need to check both possibilities:
            // 1. If there's a 'From' column value, use that to get the admin name
            // 2. Otherwise use the UserID of the last record
            
            if (!empty($lastRecord['From']) && $lastRecord['From'] != 0) {
                // Use the 'From' field to get the admin who forwarded it
                $forwardedFrom = $lastRecord['FromAdminName'] ?? '';
                
                // If still empty, try to get it directly
                if (empty($forwardedFrom)) {
                    $userQuery = "SELECT Full_Name FROM admin_accounts WHERE id = '" . $lastRecord['From'] . "'";
                    $userResult = mysqli_query($connection, $userQuery);
                    if ($userResult && mysqli_num_rows($userResult) > 0) {
                        $userData = mysqli_fetch_assoc($userResult);
                        $forwardedFrom = $userData['Full_Name'];
                    } else {
                        $forwardedFrom = 'Unknown (ID: ' . $lastRecord['From'] . ')';
                    }
                }
            } elseif (!empty($lastRecord['UserID'])) {
                // Fallback to UserID if From is empty
                $forwardedFrom = $lastRecord['AdminName'] ?? '';
                
                if (empty($forwardedFrom)) {
                    $userQuery = "SELECT Full_Name FROM admin_accounts WHERE id = '" . $lastRecord['UserID'] . "'";
                    $userResult = mysqli_query($connection, $userQuery);
                    if ($userResult && mysqli_num_rows($userResult) > 0) {
                        $userData = mysqli_fetch_assoc($userResult);
                        $forwardedFrom = $userData['Full_Name'];
                    } else {
                        $forwardedFrom = 'Unknown (ID: ' . $lastRecord['UserID'] . ')';
                    }
                }
            }
        }
        
        // SECOND: Prepare previous remarks list (all records including the last one)
        foreach ($allRecords as $index => $record) {
            // Get the admin name for this record (the person who made the response)
            $adminName = $record['AdminName'] ?? '';
            
            // If admin name is empty, try to get it from UserID
            if (empty($adminName) && !empty($record['UserID'])) {
                $nameQuery = "SELECT Full_Name FROM admin_accounts WHERE id = '" . $record['UserID'] . "'";
                $nameResult = mysqli_query($connection, $nameQuery);
                if ($nameResult && mysqli_num_rows($nameResult) > 0) {
                    $nameData = mysqli_fetch_assoc($nameResult);
                    $adminName = $nameData['Full_Name'];
                } else {
                    $adminName = 'Unknown User (ID: ' . $record['UserID'] . ')';
                }
            } elseif (empty($adminName)) {
                $adminName = 'System';
            }
            
            // Get who forwarded it (From field)
            $fromName = $record['FromAdminName'] ?? '';
            if (empty($fromName) && !empty($record['From'])) {
                $fromQuery = "SELECT Full_Name FROM admin_accounts WHERE id = '" . $record['From'] . "'";
                $fromResult = mysqli_query($connection, $fromQuery);
                if ($fromResult && mysqli_num_rows($fromResult) > 0) {
                    $fromData = mysqli_fetch_assoc($fromResult);
                    $fromName = $fromData['Full_Name'];
                }
            }
            
            // Debug - log attachment for this record
            error_log("Record ID: " . $record['Responce_TrendID'] . " Attachment: " . ($record['Attachment'] ?? 'empty'));
            
            $previousRemarks[] = [
                'UserID' => $record['UserID'],
                'From' => $record['From'],
                'FromName' => $fromName,
                'FullName' => $adminName,
                'Responce' => $record['Responce'],
                'Remarks' => $record['Remarks'],
                'Status' => $record['Status'],
                'Date' => $record['Responce_Date'],
                'Attachment' => $record['Attachment'] ?? ''  // Include attachment field
            ];
        }
    } else {
        error_log("No records found for ComplaintID: " . $ComplaintID);
    }
}

// Handle POST request
if ($_SERVER["REQUEST_METHOD"] == "POST") {
 
    // Check if connection is established
    if (!isset($connection)) {
        $_SESSION['failure'] = "Database connection failed!";
        header('location: AddResponce.php?ComplaintID=' . $ComplaintID);
        exit();
    }
    
    // Sanitize input data
    $ComplaintID = mysqli_real_escape_string($connection, trim($_POST['ComplaintID']));
    $MyComment = mysqli_real_escape_string($connection, trim($_POST['MyComment'])); 
    $Remarks = mysqli_real_escape_string($connection, trim($_POST['Remarks'] ?? '')); 
    $Department = mysqli_real_escape_string($connection, trim($_POST['Department']));  
    $Assigned_Admin = mysqli_real_escape_string($connection, trim($_POST['Assigned_Admin']));
    $Status = mysqli_real_escape_string($connection, trim($_POST['Status']));
    
	$Forwarded_From = mysqli_real_escape_string($connection, trim($_POST['Forwarded_From']));
    $Originated_From = mysqli_real_escape_string($connection, trim($_POST['Originated_From']));
    
	$From = "";
	if (empty($Forwarded_From)) {$From = $Originated_From; } else {$From = $Forwarded_From; }
	
    // Validate required fields
    $errors = array();
    if (empty($MyComment)) $errors[] = "Your Comment is required";
    if (empty($Department)) $errors[] = "Department is required";
    if (empty($Assigned_Admin)) $errors[] = "Assigned Person is required";
    if (empty($Status)) $errors[] = "Status is required";
    
    if (empty($errors)) {
        
            
            date_default_timezone_set('Africa/Blantyre');
            $Responce_Date = date('Y-m-d', time()); // Using date only as per your table structure

            // File Upload Handling
            $file_name = '';
            
            if(isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
                $name = $_FILES['file']['name'];
                $size = $_FILES['file']['size'];
                $temp = $_FILES['file']['tmp_name'];
                
                // Validate file size (max 5MB)
                $max_size = 5 * 1024 * 1024; // 5MB in bytes
                if ($size > $max_size) {
                    $_SESSION['failure'] = "File size too large. Maximum size is 5MB.";
                    header('location: AddResponce.php?ComplaintID=' . $ComplaintID);
                    exit();
                }
                
                // Validate file type
                $allowed_types = array('jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'txt');
                $file_ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
                
                if (!in_array($file_ext, $allowed_types)) {
                    $_SESSION['failure'] = "Invalid file type. Allowed types: " . implode(', ', $allowed_types);
                    header('location: AddResponce.php?ComplaintID=' . $ComplaintID);
                    exit();
                }
                
                // Create unique filename with timestamp
                $fname = date("YmdHis") . '_' . preg_replace("/[^a-zA-Z0-9.]/", "_", $name);
                
                // Create upload directory if it doesn't exist
                $upload_dir = "Uploads/";
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0755, true);
                }
                
                // Move uploaded file
                $upload_path = $upload_dir . $fname;
                $move = move_uploaded_file($temp, $upload_path);
                
                if ($move) {
                    $file_name = $fname;
                    chmod($upload_path, 0644);
                } else {
                    $_SESSION['failure'] = "Failed to upload file! Please check directory permissions.";
                    header('location: AddResponce.php?ComplaintID=' . $ComplaintID);
                    exit();
                }
            }
            
            // Get current user ID from session (assuming you have user session)
            $currentUserID = $_SESSION['user_id'] ?? 1; // Fallback to 1 if not set
            
            // Get the From ID (who is forwarding this) - this should be the current user
            $fromID = $currentUserID;
            
            // Insert into responce_trend table
			
			
			$query = "UPDATE responce_trend SET View_Status = 'Seen' WHERE ComplaintID = '$ComplaintID' AND `From` = '$fromID' AND View_Status = 'New'";
            $response_sql = mysqli_query($connection, $query);
			
            // Note: `From` is a reserved word, so we need to escape it with backticks
            $query = "INSERT INTO responce_trend (ComplaintID, `From`, UserID, Responce, Remarks, Status, Responce_Date, Attachment) 
                      VALUES ('$ComplaintID', '$fromID', '$Assigned_Admin', '$MyComment', '$Remarks', '$Status', '$Responce_Date', '$file_name')";
            
            $responce_sql = mysqli_query($connection, $query);
			
			$query = "UPDATE complaints SET Status = '$Status' WHERE ComplaintID = '$ComplaintID'";
            $response_sql = mysqli_query($connection, $query);
			
			
 
            if ($responce_sql) {
                $responce_id = mysqli_insert_id($connection);
                
                $_SESSION['success'] = "Response #$responce_id added successfully! Case forwarded to $Admin_Name ($Admin_Type) from $Department department!";
                
                header('location: Complaints.php');
                exit();
            } else {
                $_SESSION['failure'] = "Error saving response: " . mysqli_error($connection);
                header('location: AddResponce.php?ComplaintID=' . $ComplaintID);
                exit();
            }
        
        
    } else {
        $_SESSION['failure'] = implode("<br>", $errors);
        header('location: AddResponce.php?ComplaintID=' . $ComplaintID);
        exit();
    }
}

// If edit variable is set, we are performing the update operation.
if($edit && $ComplaintID)
{
    $db->where('ComplaintID', $ComplaintID);
    // Get data to pre-populate the form.
    $complaints = $db->getOne("complaints");
    
    // Check if record was found
    if(empty($complaints)) {
        $_SESSION['failure'] = "Complaint with ID " . $ComplaintID . " not found.";
        header('Location: Complaints.php');
        exit();
    }
} else if($edit && !$ComplaintID) {
    // If edit mode but no ComplaintID provided
    $_SESSION['failure'] = "No complaint ID provided for editing.";
    header('Location: Complaints.php');
    exit();
}

include_once 'includes/header.php'; 
?>

<!-- Add jQuery if not already included -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>

<!-- Add Bootstrap Select if needed -->
<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>

<!-- Font Awesome for icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

<style>
    /* COMPACT FORM STYLES */
    :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;
    }

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

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

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

    /* Header Styles - Compact */
    .page-header {
        background: var(--pure-white);
        padding: 12px 20px;
        border-radius: 8px;
        margin: 0 0 15px 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: 10px;
    }

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

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

    /* Action Buttons - Smaller */
    .action-buttons {
        display: flex;
        gap: 8px;
        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);
    }

    /* Alert Messages - Compact */
    .alert-custom {
        padding: 12px 18px;
        border-radius: 6px;
        margin-bottom: 15px;
        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);
    }

    /* Main Form Card - Smaller */
    .form-card {
        background: var(--pure-white);
        border-radius: 10px;
        box-shadow: var(--shadow);
        overflow: hidden;
        margin-bottom: 20px;
    }

    .form-card-header {
        background: linear-gradient(135deg, var(--charcoal) 0%, var(--black) 100%);
        color: var(--pure-white);
        padding: 12px 20px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .form-card-header i {
        font-size: 18px;
        color: var(--primary-green);
    }

    .form-card-header h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
    }

    .form-card-body {
        padding: 15px;
    }

    /* Section Styles - More Compact */
    .section-card {
        background: var(--soft-white);
        border-radius: 8px;
        margin-bottom: 12px;
        overflow: hidden;
        border: 1px solid var(--light-gray);
    }

    .section-header {
        background: var(--pure-white);
        padding: 10px 15px;
        border-bottom: 1px solid var(--light-gray);
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .section-header i {
        font-size: 16px;
        color: var(--primary-green);
        background: rgba(46, 204, 113, 0.1);
        padding: 6px;
        border-radius: 6px;
    }

    .section-header h4 {
        margin: 0;
        color: var(--black);
        font-size: 15px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.3px;
    }

    .section-body {
        padding: 12px;
    }

    /* Form Group Styles - Tighter */
    .form-row {
        display: flex;
        flex-wrap: wrap;
        margin: 0 -6px 8px -6px;
    }

    .form-col {
        flex: 1;
        padding: 0 6px;
        min-width: 200px;
    }

    .form-group-custom {
        margin-bottom: 8px;
    }

    .form-label {
        display: block;
        margin-bottom: 3px;
        color: var(--dark-gray);
        font-weight: 500;
        font-size: 12px;
        text-transform: uppercase;
        letter-spacing: 0.2px;
    }

    .form-label i {
        color: var(--primary-green);
        margin-right: 4px;
        font-size: 11px;
    }

    .required-field::after {
        content: "*";
        color: #e74c3c;
        margin-left: 3px;
        font-weight: bold;
        font-size: 12px;
    }

    .input-group-custom {
        position: relative;
        display: flex;
        align-items: center;
    }

    .input-icon {
        position: absolute;
        left: 10px;
        color: var(--primary-green);
        font-size: 12px;
        z-index: 2;
    }

    .form-control-custom {
        width: 100%;
        padding: 8px 10px 8px 32px;
        font-size: 13px;
        color: var(--black);
        background: var(--pure-white);
        border: 1px solid var(--light-gray);
        border-radius: 6px;
        transition: all 0.2s ease;
        outline: none;
    }

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

    .form-control-custom::placeholder {
        color: var(--medium-gray);
        font-size: 12px;
    }

    textarea.form-control-custom {
        resize: vertical;
        min-height: 60px;
        padding: 8px 10px 8px 32px;
    }

    /* Select Styles - Compact */
    .select-custom {
        width: 100%;
        padding: 8px 10px 8px 32px;
        font-size: 13px;
        color: var(--black);
        background: var(--pure-white);
        border: 1px solid var(--light-gray);
        border-radius: 6px;
        appearance: none;
        background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
        background-repeat: no-repeat;
        background-position: right 10px center;
        background-size: 14px;
    }

    /* Admin Info Styles - Compact */
    .admin-info-card {
        background: var(--pure-white);
        border-left: 4px solid var(--primary-green);
        padding: 10px 15px;
        border-radius: 6px;
        margin: 8px 0;
        box-shadow: var(--shadow);
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .admin-info-icon {
        width: 36px;
        height: 36px;
        background: rgba(46, 204, 113, 0.1);
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        color: var(--primary-green);
    }

    .admin-info-content {
        flex: 1;
    }

    .admin-info-title {
        font-weight: 600;
        color: var(--black);
        margin-bottom: 2px;
        font-size: 13px;
    }

    .admin-info-text {
        color: var(--dark-gray);
        font-size: 12px;
        line-height: 1.4;
    }

    .admin-badge {
        display: inline-block;
        padding: 3px 8px;
        border-radius: 12px;
        font-size: 10px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.2px;
        margin-right: 4px;
    }

    .badge-super {
        background: var(--dark-green);
        color: var(--pure-white);
    }

    .badge-regular {
        background: var(--light-gray);
        color: var(--dark-gray);
    }

    /* Loading Spinner - Smaller */
    .loading-spinner {
        width: 18px;
        height: 18px;
        border: 2px solid var(--light-gray);
        border-top: 2px solid var(--primary-green);
        border-radius: 50%;
        animation: spin 0.8s linear infinite;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    /* Submit Button - Compact */
    .submit-section {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        margin-top: 15px;
        padding-top: 10px;
        border-top: 1px solid var(--light-gray);
        flex-wrap: wrap;
    }

    .btn-submit {
        background: linear-gradient(135deg, var(--primary-green) 0%, var(--dark-green) 100%);
        color: var(--pure-white);
        padding: 10px 25px;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        transition: all 0.2s ease;
        box-shadow: var(--shadow);
    }

    .btn-submit:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.15);
    }

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

    .btn-cancel {
        background: var(--pure-white);
        color: var(--dark-gray);
        padding: 10px 25px;
        border: 1px solid var(--light-gray);
        border-radius: 6px;
        font-size: 14px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        transition: all 0.2s ease;
        text-decoration: none;
    }

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

    /* Validation Styles */
    .has-error .form-control-custom {
        border-color: var(--danger-color);
        background-color: #fff8f8;
    }

    .help-block {
        display: block;
        margin-top: 3px;
        color: var(--danger-color);
        font-size: 11px;
        font-weight: 500;
        padding-left: 32px;
    }

    /* File Input Styling - Compact */
    .file-input-wrapper {
        position: relative;
        width: 100%;
    }

    .file-input-wrapper input[type="file"] {
        width: 100%;
        padding: 8px 10px;
        background: var(--soft-white);
        border: 1px dashed var(--primary-green);
        border-radius: 6px;
        color: var(--dark-gray);
        font-size: 12px;
        cursor: pointer;
    }

    .file-input-wrapper input[type="file"]::-webkit-file-upload-button {
        background: var(--primary-green);
        color: var(--pure-white);
        padding: 5px 10px;
        border: none;
        border-radius: 4px;
        font-weight: 500;
        margin-right: 10px;
        font-size: 11px;
        cursor: pointer;
    }

    .file-input-wrapper input[type="file"]::file-selector-button {
        background: var(--primary-green);
        color: var(--pure-white);
        padding: 5px 10px;
        border: none;
        border-radius: 4px;
        font-weight: 500;
        margin-right: 10px;
        font-size: 11px;
        cursor: pointer;
    }

    /* Previous Remarks Styling */
    .previous-remarks-container {
        background-color: var(--soft-white);
        border-radius: 6px;
        min-height: 200px;
        border: 1px solid var(--light-gray);
        padding: 10px;
        position: relative;
    }

    .remark-item {
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px dashed var(--light-gray);
        display: none;
    }

    .remark-item.active {
        display: block;
    }

    .remark-item:last-child {
        border-bottom: none !important;
        margin-bottom: 0 !important;
        padding-bottom: 0 !important;
    }

    .remark-item:hover {
        background-color: rgba(46, 204, 113, 0.05);
        transition: background-color 0.2s ease;
    }

    /* Pagination Controls */
    .pagination-controls {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
        padding: 8px;
        background-color: var(--pure-white);
        border-radius: 6px;
        border: 1px solid var(--light-gray);
    }

    .pagination-info {
        font-size: 12px;
        color: var(--dark-gray);
    }

    .pagination-buttons {
        display: flex;
        gap: 5px;
    }

    .pagination-btn {
        padding: 5px 10px;
        border: 1px solid var(--light-gray);
        background-color: var(--pure-white);
        color: var(--dark-gray);
        border-radius: 4px;
        cursor: pointer;
        font-size: 11px;
        transition: all 0.2s ease;
    }

    .pagination-btn:hover:not(:disabled) {
        background-color: var(--primary-green);
        color: var(--pure-white);
        border-color: var(--primary-green);
    }

    .pagination-btn:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }

    .record-counter {
        font-weight: 600;
        color: var(--primary-green);
        margin-left: 5px;
    }

    /* Scrollbar styling */
    .previous-remarks-container::-webkit-scrollbar {
        width: 6px;
    }

    .previous-remarks-container::-webkit-scrollbar-track {
        background: var(--light-gray);
        border-radius: 3px;
    }

    .previous-remarks-container::-webkit-scrollbar-thumb {
        background: var(--primary-green);
        border-radius: 3px;
    }

    .previous-remarks-container::-webkit-scrollbar-thumb:hover {
        background: var(--dark-green);
    }

    /* File info display - Compact */
    .file-info {
        margin-top: 5px;
        padding: 6px;
        background: var(--light-green);
        border-radius: 4px;
        font-size: 11px;
        color: var(--dark-green);
        display: none;
    }

    .file-info.show {
        display: block;
    }

    /* Text-muted small */
    .text-muted {
        font-size: 10px;
        color: var(--dark-gray);
        margin-top: 2px;
        display: block;
    }

    /* Responsive */
    @media (max-width: 768px) {
        .page-header {
            flex-direction: column;
            text-align: center;
        }

        .form-row {
            flex-direction: column;
        }

        .form-col {
            width: 100%;
        }

        .submit-section {
            flex-direction: column;
        }

        .btn-submit, .btn-cancel {
            width: 100%;
            justify-content: center;
        }
        
        .pagination-controls {
            flex-direction: column;
            gap: 10px;
        }
    }
</style>

<script type="text/javascript">
$(document).ready(function() {
    // Initialize Bootstrap Select with smaller size
    $('.selectpicker').selectpicker({
        size: 5,
        dropupAuto: false
    });
    
    // Store the assigned admin for later use
    var assignedAdminId = '<?php echo $edit && isset($complaints['Assigned_Admin']) ? $complaints['Assigned_Admin'] : ''; ?>';
    
    // Hide Case History section if no records found
    var showHistory = <?php echo $showHistory ? 'true' : 'false'; ?>;
    var hasRemarks = <?php echo !empty($previousRemarks) ? 'true' : 'false'; ?>;
    
    if (!showHistory || !hasRemarks) {
        // Hide the entire Case History section
        $('.section-card:contains("Case History")').hide();
    }
    
    // Previous Responses Pagination
    var currentIndex = 0;
    var totalRecords = <?php echo count($previousRemarks); ?>;
    
    function updatePagination() {
        // Hide all remarks
        $('.remark-item').removeClass('active');
        
        // Show current remark
        $('.remark-item[data-index="' + currentIndex + '"]').addClass('active');
        
        // Update counter
        $('.current-counter').text(currentIndex + 1);
        $('.total-counter').text(totalRecords);
        
        // Update button states
        $('.prev-btn').prop('disabled', currentIndex === 0);
        $('.next-btn').prop('disabled', currentIndex === totalRecords - 1);
    }
    
    // Next button click
    $('.next-btn').click(function() {
        if (currentIndex < totalRecords - 1) {
            currentIndex++;
            updatePagination();
        }
    });
    
    // Previous button click
    $('.prev-btn').click(function() {
        if (currentIndex > 0) {
            currentIndex--;
            updatePagination();
        }
    });
    
    // Initialize first record
    if (totalRecords > 0) {
        updatePagination();
    }
    
    // Display file info when file is selected
    $('#file').on('change', function() {
        var fileName = $(this).val().split('\\').pop();
        if (this.files.length > 0) {
            var fileSize = this.files[0].size / 1024 / 1024; // in MB
            
            if (fileName) {
                var fileInfo = '<i class="fas fa-check-circle"></i> Selected: ' + fileName + 
                              ' (' + fileSize.toFixed(2) + ' MB)';
                
                if ($('#file-info').length === 0) {
                    $(this).parent().after('<div id="file-info" class="file-info show">' + fileInfo + '</div>');
                } else {
                    $('#file-info').html(fileInfo).addClass('show');
                }
            }
        }
    });
    
    // When department selection changes
    $('select[name="Department"]').change(function() {
        var selectedDepartment = $(this).val();
        var $adminSelect = $('select[name="Assigned_Admin"]');
        var $adminInfo = $('#admin_info');
        
        // Clear and disable the admin dropdown if no department selected
        if (!selectedDepartment || selectedDepartment === '') {
            $adminSelect.html('<option value="">Select Department First</option>');
            $adminSelect.prop('disabled', true);
            $adminSelect.selectpicker('refresh');
            $adminInfo.hide().html('');
            return;
        }
        
        // Show loading state
        $adminSelect.html('<option value="">Loading admins...</option>');
        $adminSelect.prop('disabled', true);
        $adminSelect.selectpicker('refresh');
        
        $adminInfo.show().html(`
            <div class="admin-info-card">
                <div class="admin-info-icon">
                    <i class="fas fa-spinner fa-spin"></i>
                </div>
                <div class="admin-info-content">
                    <div class="admin-info-title">Checking Department</div>
                    <div class="admin-info-text">Loading available admins for <strong>${selectedDepartment}</strong> department...</div>
                </div>
            </div>
        `);
        
        // Make AJAX call to fetch admins from the selected department
        $.ajax({
            url: 'get_admins_by_department.php',
            type: 'POST',
            data: { department: selectedDepartment },
            dataType: 'json',
            timeout: 10000,
            success: function(response) {
                console.log('Response received:', response);
                
                // Clear current options
                $adminSelect.html('');
                
                // Check if response has admins array
                var admins = response.admins || [];
                
                // Check if we have admins
                if (admins && admins.length > 0) {
                    // ADMINS FOUND
                    $adminSelect.append('<option value="">-- Select a Responsible Person --</option>');
                    
                    // Separate super admins and regular admins
                    var superAdmins = admins.filter(function(admin) {
                        return admin.admin_type === 'super';
                    });
                    
                    var regularAdmins = admins.filter(function(admin) {
                        return admin.admin_type !== 'super';
                    });
                    
                    // Add Super Admins first if any
                    if (superAdmins.length > 0) {
                        var optgroupSuper = '<optgroup label="Super Administrators">';
                        $.each(superAdmins, function(index, admin) {
                            var selected = (assignedAdminId && assignedAdminId == admin.id) ? 'selected' : '';
                            optgroupSuper += '<option value="' + admin.id + '" ' + selected + '>' + 
                                           admin.full_name + ' (Super)</option>';
                        });
                        optgroupSuper += '</optgroup>';
                        $adminSelect.append(optgroupSuper);
                    }
                    
                    // Add Regular Admins
                    if (regularAdmins.length > 0) {
                        var optgroupRegular = '<optgroup label="Administrators">';
                        $.each(regularAdmins, function(index, admin) {
                            var selected = (assignedAdminId && assignedAdminId == admin.id) ? 'selected' : '';
                            optgroupRegular += '<option value="' + admin.id + '" ' + selected + '>' + 
                                             admin.full_name + '</option>';
                        });
                        optgroupRegular += '</optgroup>';
                        $adminSelect.append(optgroupRegular);
                    }
                    
                    // Enable the dropdown
                    $adminSelect.prop('disabled', false);
                    
                    // Show success message
                    var selectedAdminName = '';
                    if (assignedAdminId) {
                        var selectedAdmin = admins.find(function(admin) {
                            return admin.id == assignedAdminId;
                        });
                        if (selectedAdmin) {
                            selectedAdminName = selectedAdmin.full_name;
                        }
                    }
                    
                    $adminInfo.html(`
                        <div class="admin-info-card" style="border-left-color: var(--primary-green);">
                            <div class="admin-info-icon" style="color: var(--primary-green);">
                                <i class="fas fa-check-circle"></i>
                            </div>
                            <div class="admin-info-content">
                                <div class="admin-info-title">Users Available</div>
                                <div class="admin-info-text">
                                    <strong>${admins.length} User(s) found</strong> in ${selectedDepartment} department
                                    <br>
                                    <span class="admin-badge badge-super">${superAdmins.length} Super</span>
                                    <span class="admin-badge badge-regular">${regularAdmins.length} Regular</span>
                                    ${assignedAdminId ? '<br><strong>Current: ' + selectedAdminName + '</strong>' : ''}
                                </div>
                            </div>
                        </div>
                    `);
                    
                } else {
                    // NO ADMINS FOUND
                    $adminSelect.html('<option value="">⛔ No Users available in ' + selectedDepartment + '</option>');
                    $adminSelect.prop('disabled', true);
                    
                    // Show warning message
                    $adminInfo.html(`
                        <div class="admin-info-card" style="border-left-color: var(--danger-color);">
                            <div class="admin-info-icon" style="color: var(--danger-color);">
                                <i class="fas fa-exclamation-triangle"></i>
                            </div>
                            <div class="admin-info-content">
                                <div class="admin-info-title" style="color: var(--danger-color);">No Users Available</div>
                                <div class="admin-info-text">
                                    <strong>No admin users found</strong> for ${selectedDepartment}
                                    <br>
                                    <small>Select different department or contact admin</small>
                                </div>
                            </div>
                        </div>
                    `);
                }
                
                // Refresh the selectpicker
                $adminSelect.selectpicker('refresh');
            },
            error: function(xhr, status, error) {
                console.error('Error fetching admins:', error);
                
                // ERROR - Show error message
                $adminSelect.html('<option value="">Error loading admins</option>');
                $adminSelect.prop('disabled', true);
                $adminSelect.selectpicker('refresh');
                
                var errorMsg = status === 'timeout' ? 'Request timed out.' : 'Error loading admins.';
                
                $adminInfo.html(`
                    <div class="admin-info-card" style="border-left-color: var(--danger-color);">
                        <div class="admin-info-icon" style="color: var(--danger-color);">
                            <i class="fas fa-times-circle"></i>
                        </div>
                        <div class="admin-info-content">
                            <div class="admin-info-title" style="color: var(--danger-color);">Error</div>
                            <div class="admin-info-text">
                                <strong>${errorMsg}</strong>
                                <br>
                                Please refresh and try again.
                            </div>
                        </div>
                    </div>
                `);
            }
        });
    });
    
    // When admin is selected
    $('select[name="Assigned_Admin"]').change(function() {
        var selectedAdminId = $(this).val();
        var selectedAdminText = $(this).find('option:selected').text();
        var selectedDept = $('select[name="Department"]').val();
        
        if (selectedAdminId && selectedAdminId !== '' && selectedAdminText !== '-- Select a Responsible person --') {
            $('#admin_info').html(`
                <div class="admin-info-card" style="border-left-color: var(--primary-green);">
                    <div class="admin-info-icon" style="color: var(--primary-green);">
                        <i class="fas fa-user-check"></i>
                    </div>
                    <div class="admin-info-content">
                        <div class="admin-info-title">User Selected</div>
                        <div class="admin-info-text">
                            <strong>${selectedAdminText}</strong> assigned
                        </div>
                    </div>
                </div>
            `);
        }
    });
    
    // Initialize - disable admin dropdown on page load
    $('select[name="Assigned_Admin"]').prop('disabled', true);
    $('select[name="Assigned_Admin"]').selectpicker('refresh');
    
    // If department was previously selected (e.g., in edit mode), load admins
    var selectedDept = '<?php echo $edit && isset($complaints['Department']) ? $complaints['Department'] : ''; ?>';
    if (selectedDept && selectedDept !== '') {
        $('select[name="Department"]').val(selectedDept);
        $('select[name="Department"]').trigger('change');
    }
    
    // Form validation
    $("#contact_form").validate({
        rules: {
            MyComment: {
                required: true,
                minlength: 5,
                maxlength: 1000
            },
            Department: {
                required: true
            },
            Assigned_Admin: {
                required: true
            },
            Status: {
                required: true
            }
        },
        messages: {
            MyComment: {
                required: "Your Comment is Required",
                minlength: "Min 5 chars"
            },
            Department: {
                required: "Select department"
            },
            Assigned_Admin: {
                required: "Select a Responsible Person"   
            },
            Status: {
                required: "Select status"
            }
        },
        errorElement: "span",
        errorClass: "help-block",
        highlight: function(element) {
            $(element).closest('.form-group-custom').addClass('has-error');
        },
        unhighlight: function(element) {
            $(element).closest('.form-group-custom').removeClass('has-error');
        },
        errorPlacement: function(error, element) {
            if (element.hasClass('selectpicker')) {
                error.insertAfter(element.next('.dropdown-toggle'));
            } else {
                error.insertAfter(element);
            }
        },
        submitHandler: function(form) {
            // Additional validation before submit
            var dept = $('select[name="Department"]').val();
            var admin = $('select[name="Assigned_Admin"]').val();
            
            if (!dept || dept === '') {
                alert('Please select a department');
                return false;
            }
            
            if ($('select[name="Assigned_Admin"]').prop('disabled')) {
                alert('No admin available for selected department');
                return false;
            }
            
            if (!admin || admin === '') {
                alert('Please select an admin');
                return false;
            }
            
            $('.btn-submit').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Saving...');
            form.submit();
        }
    });
});
</script>

<div id="page-wrapper">
    <div class="form-container">
        <!-- Header Section -->
        <div class="page-header">
            <h1>
                <?php 
                // Get originated from name
                $Originated_From = $complaints['Originated_From'] ?? '';
                $Originated_Name = "";

                if (!empty($Originated_From)) {
                    $result = mysqli_query($connection, "SELECT * FROM admin_accounts WHERE id = '$Originated_From'");
                    $num = mysqli_num_rows($result);

                    if ($num > 0) {
                        $rows = mysqli_fetch_array($result);
                        $Originated_Name = $rows['Full_Name'];
                    }
                }
                ?>
                <i class="fas fa-plus-circle"></i>
                <?php echo 'Add a Response to Case #' . $ComplaintID . ' Initiated By: ' . htmlspecialchars($Originated_Name ?: 'Unknown'); ?>
            </h1>
            <div class="action-buttons">
                <a href="Complaints.php" class="btn-custom btn-custom-primary">
                    <i class="fas fa-arrow-left"></i>
                    Back to Complaints
                </a>
                <a href="AddResponce.php?ComplaintID=<?php echo $ComplaintID; ?>" class="btn-custom btn-custom-success">
                    <i class="fas fa-sync-alt"></i>
                    Refresh
                </a>
            </div>
        </div>
        
        <!-- Alert Messages -->
        <?php if(isset($_SESSION['success'])): ?>
            <div class="alert-custom alert-custom-success">
                <i class="fas fa-check-circle"></i>
                <div><?php echo $_SESSION['success']; unset($_SESSION['success']); ?></div>
            </div>
        <?php endif; ?>
        
        <?php if(isset($_SESSION['failure'])): ?>
            <div class="alert-custom alert-custom-danger">
                <i class="fas fa-exclamation-circle"></i>
                <div><?php echo $_SESSION['failure']; unset($_SESSION['failure']); ?></div>
            </div>
        <?php endif; ?>
        
        <!-- Main Form Card -->
        <div class="form-card">
            <div class="form-card-header">
                <i class="fas fa-file-alt"></i>
                <h3>Response Form for Complaint #<?php echo $ComplaintID; ?></h3>
            </div>
            <div class="form-card-body">
                
                    <!-- Hidden Fields -->
                    
                    <!-- First Row: Two Columns -->
                    <div class="row">
                       <!-- Left Column - Case Info (Display Only) -->
                        <div class="col-lg-6">
                            <div class="section-card">
                                <div class="section-header">
                                    <i class="fas fa-user"></i>
                                    <h4>Client Information</h4>
                                </div>
                                <div class="section-body">
                                    <div class="form-group-custom" style="display: flex; align-items: center; margin-bottom: 10px;">
                                        <label class="form-label" style="width: 120px; margin-bottom: 0; flex-shrink: 0;">
                                            <i class="fas fa-heading"></i> Heading:
                                        </label>
                                        <div class="input-group-custom" style="flex: 1;">
                                            <input type="text" class="form-control-custom" value="<?php echo $edit && isset($complaints['Heading']) ? htmlspecialchars($complaints['Heading']) : 'N/A'; ?>" readonly style="padding-left: 32px;">
                                        </div>
                                    </div>
                                    
                                    <div class="form-group-custom" style="display: flex; align-items: center; margin-bottom: 10px;">
                                        <label class="form-label" style="width: 120px; margin-bottom: 0; flex-shrink: 0;">
                                            <i class="fas fa-user"></i> Name:
                                        </label>
                                        <div class="input-group-custom" style="flex: 1;">
                                            <input type="text" class="form-control-custom" value="<?php echo $edit && isset($complaints['Name']) ? htmlspecialchars($complaints['Name']) : 'N/A'; ?>" readonly style="padding-left: 32px;">
                                        </div>
                                    </div>
                                    
                                    <div class="form-group-custom" style="display: flex; align-items: center; margin-bottom: 10px;">
                                        <label class="form-label" style="width: 120px; margin-bottom: 0; flex-shrink: 0;">
                                            <i class="fas fa-hashtag"></i> Property #:
                                        </label>
                                        <div class="input-group-custom" style="flex: 1;">
                                            <input type="text" class="form-control-custom" value="<?php echo $edit && isset($complaints['Property_Number']) ? htmlspecialchars($complaints['Property_Number']) : 'N/A'; ?>" readonly style="padding-left: 32px;">
                                        </div>
                                    </div>
                                    
                                    <div class="form-group-custom" style="display: flex; align-items: center; margin-bottom: 10px;">
                                        <label class="form-label" style="width: 120px; margin-bottom: 0; flex-shrink: 0;">
                                            <i class="fas fa-phone"></i> Phone:
                                        </label>
                                        <div class="input-group-custom" style="flex: 1;">
                                            <input type="text" class="form-control-custom" value="<?php echo $edit && isset($complaints['phone']) ? htmlspecialchars($complaints['phone']) : 'N/A'; ?>" readonly style="padding-left: 32px;">
                                        </div>
                                    </div>
                                    
                                    <div class="form-group-custom" style="display: flex; align-items: center; margin-bottom: 10px;">
                                        <label class="form-label" style="width: 120px; margin-bottom: 0; flex-shrink: 0;">
                                            <i class="fas fa-envelope"></i> Email:
                                        </label>
                                        <div class="input-group-custom" style="flex: 1;">
                                            <input type="text" class="form-control-custom" value="<?php echo $edit && isset($complaints['email']) ? htmlspecialchars($complaints['email']) : 'N/A'; ?>" readonly style="padding-left: 32px;">
                                        </div>
                                    </div>
                                    
                                    <div class="form-group-custom" style="display: flex; align-items: center; margin-bottom: 0;">
                                        <label class="form-label" style="width: 120px; margin-bottom: 0; flex-shrink: 0;">
                                            <i class="fas fa-map-marker-alt"></i> Address:
                                        </label>
                                        <div class="input-group-custom" style="flex: 1;">
                                            <input type="text" class="form-control-custom" value="<?php echo $edit && isset($complaints['address']) ? htmlspecialchars($complaints['address']) : 'N/A'; ?>" readonly style="padding-left: 32px;">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Right Column - Problem Description (Display Only) -->
                        <div class="col-lg-6">
                            <div class="section-card">
                                <div class="section-header">
                                    <i class="fas fa-exclamation-triangle"></i>
                                    <h4>Problem Description</h4>
                                </div>
                                <div class="section-body">
                                    <div class="form-group-custom">
                                        <div class="input-group-custom">
                                            <?php 
                                            // Determine textarea rows based on attachment presence
                                            $hasAttachment = !empty($complaints['File_Name']);
                                            $textareaRows = $hasAttachment ? 10 : 13;
                                            ?>
                                            <textarea name="problem" placeholder="Describe the problem" readonly
                                                      class="form-control-custom" id="problem" rows="<?php echo $textareaRows; ?>"><?php echo $edit && isset($complaints['Problem']) ? htmlspecialchars($complaints['Problem']) : ''; ?></textarea>
                                        </div>
                                    </div>
                                    <?php if (!empty($complaints['File_Name'])): ?>
                                        <div class="form-group-custom" style="margin-top: 10px;">
                                            <label class="form-label">
                                                <i class="fas fa-paperclip"></i> Attachment
                                            </label>
                                            <div class="current-file">
                                                <a href="Uploads/<?php echo htmlspecialchars($complaints['File_Name']); ?>" target="_blank">
                                                    <i class="fas fa-download"></i> Download Attachment
                                                </a>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Second Row: Case History Section -->
                    <div class="row mt-3">
                        <div class="col-12">
                            <div class="section-card">
                                <div class="section-header">
                                    <i class="fas fa-history"></i>
                                    <h4>Case History</h4>
                                </div>
                                <div class="section-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group-custom" style="display: flex; align-items: center; margin-bottom: 10px;">
                                                <label class="form-label" style="width: 180px; margin-bottom: 0; flex-shrink: 0;">
                                                    <i class="fas fa-user-tie"></i> Originated From:
                                                </label>
                                                <div class="input-group-custom" style="flex: 1;">
                                                    <i class="fas fa-user-tie input-icon"></i>
                                                    <input type="text" class="form-control-custom" value="<?php echo htmlspecialchars($Originated_Name ?: 'Unknown'); ?>" readonly style="padding-left: 32px;">
                                                </div>
                                            </div>
                                            
                                            <div class="form-group-custom" style="display: flex; align-items: center; margin-bottom: 0;">
                                                <label class="form-label" style="width: 180px; margin-bottom: 0; flex-shrink: 0;">
                                                    <i class="fas fa-user-tie"></i> Forwarded From:
                                                </label>
                                                <div class="input-group-custom" style="flex: 1;">
                                                    <i class="fas fa-user-tie input-icon"></i>
                                                    <input type="text" class="form-control-custom" id="Forwarded_From" name="Forwarded_From" value="<?php echo htmlspecialchars($forwardedFrom ?: 'No previous forwarding'); ?>" readonly style="padding-left: 32px;">
                                                
												</div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="form-group-custom">
                                                <label class="form-label">
                                                    <i class="fas fa-history"></i>
                                                    Previous Responses
                                                    <?php if (!empty($previousRemarks)): ?>
                                                        <span class="record-counter">(<?php echo count($previousRemarks); ?> total)</span>
                                                    <?php endif; ?>
                                                </label>
                                                <?php if ($showHistory && !empty($previousRemarks)): ?>
                                                    <div class="previous-remarks-container">
                                                        <?php foreach ($previousRemarks as $index => $remark): ?>
                                                            <div class="remark-item" data-index="<?php echo $index; ?>">
                                                                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
                                                                    <strong style="color: var(--primary-green);">
                                                                        <i class="fas fa-user-circle"></i> 
                                                                        <?php echo htmlspecialchars($remark['FullName'] ?: 'System'); ?>
                                                                        <?php if (!empty($remark['FromName'])): ?>
                                                                            <small style="font-weight: normal; color: var(--dark-gray);">
                                                                                (Forwarded by: <?php echo htmlspecialchars($remark['FromName']); ?>)
                                                                            </small>
                                                                        <?php endif; ?>
                                                                    </strong>
                                                                    <small style="color: var(--dark-gray);">
                                                                        <i class="fas fa-calendar-alt"></i> 
                                                                        <?php echo date('d-m-Y', strtotime($remark['Date'])); ?>
                                                                    </small>
                                                                </div>
                                                                
                                                                <!-- Hidden fields for form submission if needed -->
                                                                <input type="hidden" name="previous_user_ids[]" value="<?php echo $remark['UserID']; ?>">
                                                                <?php if (!empty($remark['From'])): ?>
                                                                    <input type="hidden" name="previous_from_ids[]" value="<?php echo $remark['From']; ?>">
                                                                <?php endif; ?>
                                                                
                                                                <?php if (!empty($remark['Responce'])): ?>
                                                                    <div style="margin-top: 5px; padding-left: 10px; border-left: 2px solid var(--primary-green);">
                                                                        <small><strong>Response:</strong></small> 
                                                                        <span style="font-size: 12px; margin-left: 5px;"><?php echo nl2br(htmlspecialchars($remark['Responce'])); ?></span>
                                                                    </div>
                                                                <?php endif; ?>
                                                                
                                                                <?php if (!empty($remark['Remarks'])): ?>
                                                                    <div style="margin-top: 5px; padding-left: 10px; border-left: 2px solid var(--warning-color);">
                                                                        <small><strong>Remarks:</strong></small> 
                                                                        <span style="font-size: 12px; margin-left: 5px;"><?php echo nl2br(htmlspecialchars($remark['Remarks'])); ?></span>
                                                                    </div>
                                                                <?php endif; ?>
                                                                
                                                                <?php if (!empty($remark['Status'])): ?>
                                                                    <div style="margin-top: 5px;">
                                                                        <span class="admin-badge" style="background: var(--light-gray);">
                                                                            Status: <?php echo htmlspecialchars($remark['Status']); ?>
                                                                        </span>
                                                                    </div>
                                                                <?php endif; ?>
                                                                
                                                                <!-- Display attachment if exists -->
                                                                <?php 
                                                                $attachment = isset($remark['Attachment']) ? $remark['Attachment'] : '';
                                                                if (!empty($attachment)): 
                                                                ?>
                                                                    <div style="margin-top: 8px; padding-left: 10px;">
                                                                        <label class="form-label" style="display: inline-block; margin-right: 5px; font-size: 10px;">
                                                                            <i class="fas fa-paperclip" style="color: var(--primary-green);"></i> Attachment:
                                                                        </label>
                                                                        <div class="current-file" style="display: inline-block;">
                                                                            <a href="Uploads/<?php echo htmlspecialchars($attachment); ?>" target="_blank" style="font-size: 11px;">
                                                                                <i class="fas fa-download"></i> Download
                                                                            </a>
                                                                        </div>
                                                                    </div>
                                                                <?php endif; ?>
                                                            </div>
                                                        <?php endforeach; ?>
                                                    </div>
                                                    
                                                    <!-- Pagination Controls -->
                                                    <div class="pagination-controls">
                                                        <div class="pagination-info">
                                                            Showing <span class="current-counter">1</span> of <span class="total-counter"><?php echo count($previousRemarks); ?></span> responses
                                                        </div>
                                                        <div class="pagination-buttons">
                                                            <button type="button" class="pagination-btn prev-btn" disabled>
                                                                <i class="fas fa-chevron-left"></i> Previous
                                                            </button>
                                                            <button type="button" class="pagination-btn next-btn">
                                                                Next <i class="fas fa-chevron-right"></i>
                                                            </button>
                                                        </div>
                                                    </div>
                                                <?php else: ?>
                                                    <div class="input-group-custom">
                                                        <i class="fas fa-history input-icon"></i>
                                                        <textarea class="form-control-custom" rows="3" readonly>No previous history found for this case.</textarea>
                                                    </div>
                                                    <input type="hidden" name="no_history" value="1">
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                 <form action="" method="post" id="contact_form" enctype="multipart/form-data">	
                    <!-- Third Row: Case Management -->
                    <div class="row mt-3">
                        <div class="col-12">
                            <div class="section-card">
                                <div class="section-header">
                                    <i class="fas fa-cog"></i>
                                    <h4>Your Response</h4>
                                </div>
                                <div class="section-body">
                                    <div class="row">
                                        <div class="col-md-4">
                                            <div class="form-group-custom">
                                                <label class="form-label required-field">
                                                    <i class="fas fa-comment"></i>
                                                    Your Comment / Response
                                                </label>
                                                <div class="input-group-custom">
                                                    <textarea name="MyComment" placeholder="Enter your response here" required
                                                              class="form-control-custom" id="MyComment" rows="5"><?php echo isset($_POST['MyComment']) ? htmlspecialchars($_POST['MyComment']) : ''; ?></textarea>
                                                </div>
												<input type="hidden" name="ComplaintID" value="<?php echo $ComplaintID; ?>">
                                                <input type="hidden" class="form-control-custom" id="Forwarded_From" name="Forwarded_From" value="<?php echo htmlspecialchars($forwardedFrom ?: 'No previous forwarding'); ?>" readonly style="padding-left: 32px;">
                                                <input type="hidden" class="form-control-custom" name="Originated_From" value="<?php echo htmlspecialchars($Originated_Name ?: 'Unknown'); ?>" readonly style="padding-left: 32px;">
                                          
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-4">
                                            <div class="form-group-custom">
                                                <label class="form-label">
                                                    <i class="fas fa-edit"></i>
                                                    Additional Remarks (Optional)
                                                </label>
                                                <div class="input-group-custom">
                                                    <textarea name="Remarks" placeholder="Add any additional remarks here if necessary"
                                                              class="form-control-custom" rows="5"><?php echo isset($_POST['Remarks']) ? htmlspecialchars($_POST['Remarks']) : ''; ?></textarea>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-4"><br><br>
                                            <div class="form-group-custom">
                                                <label class="form-label">
                                                    <i class="fas fa-paperclip"></i>
                                                    Attachment (Optional)
                                                </label>
                                                <div class="file-input-wrapper">
                                                    <input type="file" name="file" id="file" accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx,.txt">
                                                </div>
                                                <small class="text-muted">Max 5MB (PDF, DOC, JPG, PNG, etc.)</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Fourth Row: Assignment & Additional Details -->
					<div class="row mt-3">
						<div class="col-12">
							<div class="section-card">
								<div class="section-header">
									<i class="fas fa-cog"></i>
									<h4>Assignment & Additional Details</h4>
								</div>
								<div class="section-body">
									<div class="row">
										<div class="col-md-4">
											<div class="form-group-custom">
												<label class="form-label required-field">
													<i class="fas fa-briefcase"></i>
													Redirect to Department
												</label>
												<div class="input-group-custom">
													<i class="fas fa-briefcase input-icon"></i>
													<select name="Department" class="form-control-custom select-custom" required>
														<option value="">-- Select Department --</option>
														<option value="SYSTEM ADMIN">SYSTEM ADMIN</option>
														<option value="PROCUREMENT">PROCUREMENT</option>
														<option value="ESTATES">ESTATES</option>
														<option value="ADMIN">ADMIN</option>
														<option value="ADMINISTRATION">ADMINISTRATION</option>
														<option value="MAINTENANCE">MAINTENANCE</option>
														<option value="ACCOUNTS">ACCOUNTS</option>
														<option value="SURVEY">SURVEY</option>
														<option value="SECURITY">SECURITY</option>
														<option value="STORES">STORES</option>
														<option value="ICT">ICT</option>
													</select>
												</div>
											</div>
										</div>
										
										<div class="col-md-4">
											<div class="form-group-custom">
												<label class="form-label required-field">
													<i class="fas fa-user-tie"></i>
													Assign To
												</label>
												<div class="input-group-custom">
													<i class="fas fa-user-tie input-icon"></i>
													<select name="Assigned_Admin" class="form-control-custom select-custom" required>
														<option value="">Select Department First</option>
													</select>
												</div>
											</div>
										</div>
										
										<div class="col-md-4">
											<div class="form-group-custom">
												<label class="form-label required-field">
													<i class="fas fa-info-circle"></i>
													Status
												</label>
												<div class="input-group-custom">
													<i class="fas fa-info-circle input-icon"></i>
													<select name="Status" class="form-control-custom select-custom" required>
														<option value="">-- Select Status --</option>
														<option value="In Progress">In Progress</option>
														<option value="Appended">Appended</option>
														<option value="Rejected">Rejected</option>
														<option value="Completed">Completed</option>
														<option value="Redirected">Redirected</option>
														<option value="Pending">Pending</option>
													</select>
												</div>
											</div>
										</div>
									</div>
									
									<!-- Admin Info Display Area (for showing available admins) -->
									<div id="admin_info" class="mt-2"></div>
								</div>
							</div>
						</div>
					</div>
										
										<!-- Submit Section -->
										<div class="submit-section">
											<a href="Complaints.php" class="btn-cancel">
												<i class="fas fa-times"></i>
												Cancel
											</a>
											<button type="submit" class="btn-submit">
												<i class="fas fa-paper-plane"></i>
												Submit Response
											</button>
										</div>
									</form>
								</div>
							</div>
						</div>
					</div>

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