Mini Shell

Direktori : /home/mhcadmin/public_html/Portal/
Upload File :
Current File : /home/mhcadmin/public_html/Portal/AddResponce.php

<?php
session_start();
$rootPath = dirname(__FILE__);
require_once $rootPath . '/config/config.php';
require_once $rootPath . '/include/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 = [];

// Get current session user info
$currentUserId = $_SESSION['id'] ?? 0;
$currentUserDept = '';
$currentUserDeptName = '';

if ($currentUserId) {
    $userQuery = "SELECT UserDepartment, Position, Full_Name FROM admin_accounts WHERE id = '$currentUserId' AND Status = 'Active'";
    $userResult = mysqli_query($conn, $userQuery);
    if ($userResult && mysqli_num_rows($userResult) > 0) {
        $userData = mysqli_fetch_assoc($userResult);
        $currentUserDept = $userData['UserDepartment'];
        
        // Get department name
        $deptNameQuery = "SELECT Name FROM Department WHERE id = '$currentUserDept' AND Deleted = 'No'";
        $deptNameResult = mysqli_query($conn, $deptNameQuery);
        if ($deptNameResult && mysqli_num_rows($deptNameResult) > 0) {
            $deptNameData = mysqli_fetch_assoc($deptNameResult);
            $currentUserDeptName = $deptNameData['Name'];
        }
    }
}

// ============================================
// MARK NOTIFICATIONS AS SEEN
// ============================================
if ($ComplaintID && $currentUserId) {
    // Update responce_trend table where UserID matches current user and View_Status is 'New'
    $updateResponceTrend = "UPDATE responce_trend 
                           SET View_Status = 'Seen' 
                           WHERE ComplaintID = '$ComplaintID' 
                           AND UserID = '$currentUserId' 
                           AND View_Status = 'New'";
    $responceTrendResult = mysqli_query($conn, $updateResponceTrend);
    
    if ($responceTrendResult && mysqli_affected_rows($conn) > 0) {
        // Optional: Log or track that notifications were marked as seen
        error_log("Marked " . mysqli_affected_rows($conn) . " notifications as seen for user $currentUserId on complaint $ComplaintID");
    }
    
    // Update complaints table where Assigned_To matches current user and View_Status is 'New'
    $updateComplaints = "UPDATE complaints 
                        SET View_Status = 'Seen' 
                        WHERE ComplaintID = '$ComplaintID' 
                        AND Assigned_To = '$currentUserId' 
                        AND View_Status = 'New'";
    $complaintsResult = mysqli_query($conn, $updateComplaints);
    
    if ($complaintsResult && mysqli_affected_rows($conn) > 0) {
        // Optional: Log or track that complaint was marked as seen
        error_log("Marked complaint $ComplaintID as seen by assigned user $currentUserId");
    }
}

// Check for history if ComplaintID exists
if ($ComplaintID) {
    $historyQuery = "SELECT rt.*, 
                     aa.Full_Name as UserName, aa.Position as UserPosition,
                     from_admin.Full_Name as FromUserName, from_admin.Position as FromPosition
                     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($conn, $historyQuery);
    
    if ($historyResult && mysqli_num_rows($historyResult) > 0) {
        $showHistory = true;
        $allRecords = [];
        
        while ($row = mysqli_fetch_assoc($historyResult)) {
            $allRecords[] = $row;
        }
        
        if (!empty($allRecords)) {
            $lastRecord = $allRecords[0];
            
            if (!empty($lastRecord['From']) && $lastRecord['From'] != 0) {
                $forwardedFrom = $lastRecord['FromUserName'] ?? '';
                if (!empty($lastRecord['FromPosition'])) {
                    $forwardedFrom .= ' (' . $lastRecord['FromPosition'] . ')';
                }
                if (empty($forwardedFrom) || strpos($forwardedFrom, '(') === false) {
                    $userQuery = "SELECT Full_Name, Position FROM admin_accounts WHERE id = '" . $lastRecord['From'] . "'";
                    $userResult = mysqli_query($conn, $userQuery);
                    if ($userResult && mysqli_num_rows($userResult) > 0) {
                        $userData = mysqli_fetch_assoc($userResult);
                        $forwardedFrom = $userData['Full_Name'];
                        if (!empty($userData['Position'])) {
                            $forwardedFrom .= ' (' . $userData['Position'] . ')';
                        }
                    } else {
                        $forwardedFrom = 'Unknown (ID: ' . $lastRecord['From'] . ')';
                    }
                }
            } elseif (!empty($lastRecord['UserID'])) {
                $forwardedFrom = $lastRecord['UserName'] ?? '';
                if (!empty($lastRecord['UserPosition'])) {
                    $forwardedFrom .= ' (' . $lastRecord['UserPosition'] . ')';
                }
                if (empty($forwardedFrom) || strpos($forwardedFrom, '(') === false) {
                    $userQuery = "SELECT Full_Name, Position FROM admin_accounts WHERE id = '" . $lastRecord['UserID'] . "'";
                    $userResult = mysqli_query($conn, $userQuery);
                    if ($userResult && mysqli_num_rows($userResult) > 0) {
                        $userData = mysqli_fetch_assoc($userResult);
                        $forwardedFrom = $userData['Full_Name'];
                        if (!empty($userData['Position'])) {
                            $forwardedFrom .= ' (' . $userData['Position'] . ')';
                        }
                    } else {
                        $forwardedFrom = 'Unknown (ID: ' . $lastRecord['UserID'] . ')';
                    }
                }
            }
        }
        
        foreach ($allRecords as $index => $record) {
            $userName = $record['UserName'] ?? '';
            $userPosition = $record['UserPosition'] ?? '';
            $formattedUserName = $userName;
            if (!empty($userPosition)) {
                $formattedUserName .= ' (' . $userPosition . ')';
            }
            
            if (empty($userName) && !empty($record['UserID'])) {
                $nameQuery = "SELECT Full_Name, Position FROM admin_accounts WHERE id = '" . $record['UserID'] . "'";
                $nameResult = mysqli_query($conn, $nameQuery);
                if ($nameResult && mysqli_num_rows($nameResult) > 0) {
                    $nameData = mysqli_fetch_assoc($nameResult);
                    $formattedUserName = $nameData['Full_Name'];
                    if (!empty($nameData['Position'])) {
                        $formattedUserName .= ' (' . $nameData['Position'] . ')';
                    }
                } else {
                    $formattedUserName = 'Unknown User (ID: ' . $record['UserID'] . ')';
                }
            } elseif (empty($userName)) {
                $formattedUserName = 'System';
            }
            
            $fromName = $record['FromUserName'] ?? '';
            $fromPosition = $record['FromPosition'] ?? '';
            $formattedFromName = '';
            
            if (!empty($fromName)) {
                $formattedFromName = $fromName;
                if (!empty($fromPosition)) {
                    $formattedFromName .= ' (' . $fromPosition . ')';
                }
            } elseif (!empty($record['From'])) {
                $fromQuery = "SELECT Full_Name, Position FROM admin_accounts WHERE id = '" . $record['From'] . "'";
                $fromResult = mysqli_query($conn, $fromQuery);
                if ($fromResult && mysqli_num_rows($fromResult) > 0) {
                    $fromData = mysqli_fetch_assoc($fromResult);
                    $formattedFromName = $fromData['Full_Name'];
                    if (!empty($fromData['Position'])) {
                        $formattedFromName .= ' (' . $fromData['Position'] . ')';
                    }
                }
            }
            
            $previousRemarks[] = [
                'UserID' => $record['UserID'],
                'From' => $record['From'],
                'FromName' => $formattedFromName,
                'FullName' => $formattedUserName,
                'Responce' => $record['Responce'],
                'Remarks' => $record['Remarks'],
                'Status' => $record['Status'],
                'Date' => $record['Responce_Date'],
                'Attachment' => $record['Attachment'] ?? ''
            ];
        }
    }
}

// Handle POST request
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (!isset($conn)) {
        $_SESSION['failure'] = "Database connection failed!";
        header('location: AddResponce.php?ComplaintID=' . $ComplaintID);
        exit();
    }
    
    $ComplaintID = mysqli_real_escape_string($conn, trim($_POST['ComplaintID']));
    $MyComment = mysqli_real_escape_string($conn, trim($_POST['MyComment'])); 
    $Remarks = mysqli_real_escape_string($conn, trim($_POST['Remarks'] ?? '')); 
    $Department = mysqli_real_escape_string($conn, trim($_POST['Department']));  
    $Assigned_User = mysqli_real_escape_string($conn, trim($_POST['Assigned_User']));
    $Status = mysqli_real_escape_string($conn, trim($_POST['Status']));
    $Forwarded_From = mysqli_real_escape_string($conn, trim($_POST['Forwarded_From']));
    $Originated_From = mysqli_real_escape_string($conn, trim($_POST['Originated_From']));
    
    $From = "";
    if (empty($Forwarded_From)) {
        $From = $Originated_From; 
    } else {
        $From = $Forwarded_From; 
    }
    
    $errors = array();
    if (empty($MyComment)) $errors[] = "Your Comment is required";
    if (empty($Department)) $errors[] = "Department is required";
    if (empty($Assigned_User)) $errors[] = "Assigned Person is required";
    if (empty($Status)) $errors[] = "Status is required";
    
    if (empty($errors)) {
        $originalQuery = "SELECT Department FROM complaints WHERE ComplaintID = '$ComplaintID'";
        $originalResult = mysqli_query($conn, $originalQuery);
        $originalDepartment = '';
        if ($originalResult && mysqli_num_rows($originalResult) > 0) {
            $originalData = mysqli_fetch_assoc($originalResult);
            $originalDepartment = $originalData['Department'];
        }
        
        // Check if this is a redirect (department changed from original)
        $isRedirect = ($originalDepartment && $Department && $Department !== $originalDepartment);
        
        if ($isRedirect) {
            $hodCheck = mysqli_query($conn, "SELECT HOD FROM admin_accounts WHERE id = '$Assigned_User' AND Status = 'Active'");
            if ($hodCheck && mysqli_num_rows($hodCheck) > 0) {
                $hodData = mysqli_fetch_assoc($hodCheck);
                if ($hodData['HOD'] != '1') {
                    $_SESSION['failure'] = "When redirecting to another department, you must assign to a Head of Department (HOD)!";
                    header('location: AddResponce.php?ComplaintID=' . $ComplaintID);
                    exit();
                }
            }
        }
        
        date_default_timezone_set('Africa/Blantyre');
        $Responce_Date = date('Y-m-d', time());

        $file_name = '';
        
        if(isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
            $name = $_FILES['file']['name'];
            $size = $_FILES['file']['size'];
            $temp = $_FILES['file']['tmp_name'];
            
            $max_size = 5 * 1024 * 1024;
            if ($size > $max_size) {
                $_SESSION['failure'] = "File size too large. Maximum size is 5MB.";
                header('location: AddResponce.php?ComplaintID=' . $ComplaintID);
                exit();
            }
            
            $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();
            }
            
            $fname = date("YmdHis") . '_' . preg_replace("/[^a-zA-Z0-9.]/", "_", $name);
            $upload_dir = "Uploads/";
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $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();
            }
        }
        
        $currentUserID = $_SESSION['id'] ?? 1;
        $fromID = $currentUserID;
        
        // Note: The complaints table update for View_Status is already handled above when loading the page
        // We don't need to update it again here
        
        $query = "INSERT INTO responce_trend (ComplaintID, `From`, UserID, Responce, Remarks, Status, Responce_Date, Attachment, View_Status) 
                  VALUES ('$ComplaintID', '$fromID', '$Assigned_User', '$MyComment', '$Remarks', '$Status', '$Responce_Date', '$file_name', 'New')";
        
        $responce_sql = mysqli_query($conn, $query);
        
        if ($responce_sql) {
            $query = "UPDATE complaints SET Status = '$Status', Department = '$Department', Assigned_To = '$Assigned_User' WHERE ComplaintID = '$ComplaintID'";
            $update_sql = mysqli_query($conn, $query);
            
            $responce_id = mysqli_insert_id($conn);
            
            $userQuery = "SELECT Full_Name, Position FROM admin_accounts WHERE id = '$Assigned_User'";
            $userResult = mysqli_query($conn, $userQuery);
            $userName = '';
            $userPosition = '';
            if ($userResult && mysqli_num_rows($userResult) > 0) {
                $userData = mysqli_fetch_assoc($userResult);
                $userName = $userData['Full_Name'];
                $userPosition = $userData['Position'];
            }
            
            $userDisplay = $userName;
            if (!empty($userPosition)) {
                $userDisplay .= ' (' . $userPosition . ')';
            }
            
            $deptNameQuery = "SELECT Name FROM Department WHERE id = '$Department'";
            $deptNameResult = mysqli_query($conn, $deptNameQuery);
            $deptDisplayName = $Department;
            if ($deptNameResult && mysqli_num_rows($deptNameResult) > 0) {
                $deptData = mysqli_fetch_assoc($deptNameResult);
                $deptDisplayName = $deptData['Name'];
            }
            
            $redirectMsg = $isRedirect ? " and redirected to $deptDisplayName department" : "";
            $_SESSION['success'] = "Response #$responce_id added successfully! Case forwarded to " . ($userDisplay ?: 'User') . "$redirectMsg!";
            
            header('location: Complaints.php');
            exit();
        } else {
            $_SESSION['failure'] = "Error saving response: " . mysqli_error($conn);
            header('location: AddResponce.php?ComplaintID=' . $ComplaintID);
            exit();
        }
    } else {
        $_SESSION['failure'] = implode("<br>", $errors);
        header('location: AddResponce.php?ComplaintID=' . $ComplaintID);
        exit();
    }
}

if($edit && $ComplaintID) {
    $db->where('ComplaintID', $ComplaintID);
    $complaints = $db->getOne("complaints");
    if(empty($complaints)) {
        $_SESSION['failure'] = "Complaint with ID " . $ComplaintID . " not found.";
        header('Location: Complaints.php');
        exit();
    }
} else if($edit && !$ComplaintID) {
    $_SESSION['failure'] = "No complaint ID provided for editing.";
    header('Location: Complaints.php');
    exit();
}

// Get all departments from Department table
$departments_query = "SELECT id, Name FROM Department WHERE Deleted = 'No' ORDER BY Name";
$departments_result = mysqli_query($conn, $departments_query);
$department_options = [];
if ($departments_result && mysqli_num_rows($departments_result) > 0) {
    while ($row = mysqli_fetch_assoc($departments_result)) {
        $department_options[] = $row;
    }
}

include_once 'include/AdminHeader.php'; 
?>

<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>
<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>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

<style>
    :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; }
    .form-container { max-width: 1200px; margin: 0 auto; }
    
    .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;
    }
    
    .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-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);
    }
    
    .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-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);
    }
    
    .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 h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
    }
    
    .form-card-body { padding: 15px; }
    
    .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-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;
    }
    
    .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);
    }
    
    textarea.form-control-custom {
        resize: vertical;
        min-height: 60px;
    }
    
    .select-custom {
        width: 100%;
        padding: 8px 10px 8px 32px;
        font-size: 13px;
        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;
    }
    
    .user-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;
    }
    
    .user-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);
    }
    
    .user-info-content { flex: 1; }
    .user-info-title { font-weight: 600; color: var(--black); margin-bottom: 2px; font-size: 13px; }
    .user-info-text { color: var(--dark-gray); font-size: 12px; line-height: 1.4; }
    .user-badge {
        display: inline-block;
        padding: 3px 8px;
        border-radius: 12px;
        font-size: 10px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.2px;
        background: var(--light-gray);
        color: var(--dark-gray);
    }
    
    .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-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;
    }
    
    .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-wrapper input[type="file"] {
        width: 100%;
        padding: 8px 10px;
        background: var(--soft-white);
        border: 1px dashed var(--primary-green);
        border-radius: 6px;
        font-size: 12px;
        cursor: pointer;
    }
    
    .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; }
    
    .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-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;
    }
    
    .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 {
        font-size: 10px;
        color: var(--dark-gray);
        margin-top: 2px;
        display: block;
    }
    
    .current-file {
        padding: 5px 10px;
        background: var(--soft-white);
        border-radius: 4px;
        font-size: 12px;
    }
    
    .current-file a {
        color: var(--primary-green);
        text-decoration: none;
    }
    
    @media (max-width: 768px) {
        .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() {
    $('.selectpicker').selectpicker({ size: 5, dropupAuto: false });
    
    var assignedUserId = '<?php echo $edit && isset($complaints['Assigned_To']) ? $complaints['Assigned_To'] : ''; ?>';
    var originalDepartment = '<?php echo $edit && isset($complaints['Department']) ? $complaints['Department'] : ''; ?>';
    var currentUserDept = '<?php echo $currentUserDept; ?>';
    
    var showHistory = <?php echo $showHistory ? 'true' : 'false'; ?>;
    var hasRemarks = <?php echo !empty($previousRemarks) ? 'true' : 'false'; ?>;
    
    if (!showHistory || !hasRemarks) {
        $('.section-card:contains("Case History")').hide();
    }
    
    var currentIndex = 0;
    var totalRecords = <?php echo count($previousRemarks); ?>;
    
    function updatePagination() {
        $('.remark-item').removeClass('active');
        $('.remark-item[data-index="' + currentIndex + '"]').addClass('active');
        $('.current-counter').text(currentIndex + 1);
        $('.total-counter').text(totalRecords);
        $('.prev-btn').prop('disabled', currentIndex === 0);
        $('.next-btn').prop('disabled', currentIndex === totalRecords - 1);
    }
    
    $('.next-btn').click(function() {
        if (currentIndex < totalRecords - 1) {
            currentIndex++;
            updatePagination();
        }
    });
    
    $('.prev-btn').click(function() {
        if (currentIndex > 0) {
            currentIndex--;
            updatePagination();
        }
    });
    
    if (totalRecords > 0) {
        updatePagination();
    }
    
    $('#file').on('change', function() {
        var fileName = $(this).val().split('\\').pop();
        if (this.files.length > 0) {
            var fileSize = this.files[0].size / 1024 / 1024;
            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');
                }
            }
        }
    });
    
    function loadUsersForDepartment(departmentId, departmentName, isRedirectMode) {
        var $userSelect = $('select[name="Assigned_User"]');
        var $userInfo = $('#user_info');
        
        $userSelect.html('<option value="">Loading users...</option>');
        $userSelect.prop('disabled', true);
        $userSelect.selectpicker('refresh');
        
        if (isRedirectMode) {
            $userInfo.show().html(`
                <div class="user-info-card">
                    <div class="user-info-icon"><i class="fas fa-spinner fa-spin"></i></div>
                    <div class="user-info-content">
                        <div class="user-info-title">Redirecting to ${departmentName}</div>
                        <div class="user-info-text">Looking for Head of Department in ${departmentName} department...</div>
                    </div>
                </div>
            `);
        } else {
            $userInfo.show().html(`
                <div class="user-info-card">
                    <div class="user-info-icon"><i class="fas fa-spinner fa-spin"></i></div>
                    <div class="user-info-content">
                        <div class="user-info-title">Loading Users</div>
                        <div class="user-info-text">Loading available users for <strong>${departmentName}</strong> department...</div>
                    </div>
                </div>
            `);
        }
        
        // Determine which endpoint to call based on redirect mode
        var ajaxUrl = isRedirectMode ? 'get_hod_by_department.php' : 'get_all_users_by_department.php';
        
        console.log('Calling: ' + ajaxUrl + ' for department: ' + departmentId + ' (Redirect Mode: ' + isRedirectMode + ')');
        
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: { department: departmentId },
            dataType: 'json',
            timeout: 10000,
            success: function(response) {
                console.log('Response received:', response);
                $userSelect.html('');
                
                var users = [];
                if (isRedirectMode) {
                    users = response.hods || [];
                    console.log('HODs found:', users.length);
                } else {
                    users = response.users || [];
                    console.log('Users found:', users.length);
                }
                
                if (users && users.length > 0) {
                    if (isRedirectMode) {
                        // REDIRECT MODE - Show only HODs
                        $userSelect.append('<option value="">-- Select HOD --</option>');
                        $.each(users, function(index, user) {
                            var displayName = user.full_name;
                            if (user.position && user.position.trim() !== '') {
                                displayName += ' (' + user.position + ')';
                            }
                            var selected = (assignedUserId && assignedUserId == user.id) ? 'selected' : '';
                            $userSelect.append('<option value="' + user.id + '" ' + selected + '>' + displayName + '</option>');
                        });
                        $userSelect.prop('disabled', false);
                        
                        if (users.length === 1) {
                            $userSelect.val(users[0].id);
                            $userSelect.selectpicker('refresh');
                            var hodDisplayName = users[0].full_name;
                            if (users[0].position && users[0].position.trim() !== '') {
                                hodDisplayName += ' (' + users[0].position + ')';
                            }
                            $userInfo.html(`
                                <div class="user-info-card" style="border-left-color: var(--primary-green);">
                                    <div class="user-info-icon"><i class="fas fa-crown"></i></div>
                                    <div class="user-info-content">
                                        <div class="user-info-title">Redirecting to HOD</div>
                                        <div class="user-info-text"><strong>${hodDisplayName}</strong> auto-selected for ${departmentName}</div>
                                    </div>
                                </div>
                            `);
                        } else {
                            $userInfo.html(`
                                <div class="user-info-card" style="border-left-color: var(--primary-green);">
                                    <div class="user-info-icon"><i class="fas fa-crown"></i></div>
                                    <div class="user-info-content">
                                        <div class="user-info-title">HODs Available</div>
                                        <div class="user-info-text"><strong>${users.length} HOD(s) found</strong> in ${departmentName}</div>
                                    </div>
                                </div>
                            `);
                        }
                    } else {
                        // NORMAL MODE - Show ALL users from the department
                        $userSelect.append('<option value="">-- Select a Responsible Person --</option>');
                        $.each(users, function(index, user) {
                            var displayName = user.full_name;
                            if (user.position && user.position.trim() !== '') {
                                displayName += ' (' + user.position + ')';
                            }
                            var selected = (assignedUserId && assignedUserId == user.id) ? 'selected' : '';
                            var hodLabel = user.is_hod == '1' ? ' (HOD)' : '';
                            $userSelect.append('<option value="' + user.id + '" ' + selected + '>' + displayName + hodLabel + '</option>');
                        });
                        $userSelect.prop('disabled', false);
                        
                        var hodCount = users.filter(function(user) { return user.is_hod == '1'; }).length;
                        var regularCount = users.length - hodCount;
                        
                        $userInfo.html(`
                            <div class="user-info-card" style="border-left-color: var(--primary-green);">
                                <div class="user-info-icon"><i class="fas fa-users"></i></div>
                                <div class="user-info-content">
                                    <div class="user-info-title">Users Available</div>
                                    <div class="user-info-text"><strong>${users.length} User(s)</strong> in ${departmentName} (${hodCount} HOD, ${regularCount} Staff)</div>
                                </div>
                            </div>
                        `);
                    }
                    $userSelect.selectpicker('refresh');
                } else {
                    // NO USERS FOUND
                    if (isRedirectMode) {
                        $userSelect.html('<option value="">⛔ No HOD available in ' + departmentName + '</option>');
                    } else {
                        $userSelect.html('<option value="">⛔ No Users available in ' + departmentName + '</option>');
                    }
                    $userSelect.prop('disabled', true);
                    $userSelect.selectpicker('refresh');
                    $userInfo.html(`
                        <div class="user-info-card" style="border-left-color: var(--danger-color);">
                            <div class="user-info-icon"><i class="fas fa-exclamation-triangle"></i></div>
                            <div class="user-info-content">
                                <div class="user-info-title">No Users Available</div>
                                <div class="user-info-text">No users found for ${departmentName}</div>
                            </div>
                        </div>
                    `);
                }
            },
            error: function(xhr, status, error) {
                console.error('Error fetching users:', error);
                console.error('Status:', status);
                console.error('Response:', xhr.responseText);
                $userSelect.html('<option value="">Error loading users</option>');
                $userSelect.prop('disabled', true);
                $userSelect.selectpicker('refresh');
                $userInfo.html(`
                    <div class="user-info-card" style="border-left-color: var(--danger-color);">
                        <div class="user-info-icon"><i class="fas fa-times-circle"></i></div>
                        <div class="user-info-content">
                            <div class="user-info-title">Error</div>
                            <div class="user-info-text">Error loading users. Please refresh and try again.</div>
                        </div>
                    </div>
                `);
            }
        });
    }
    
    // When department selection changes
    $('select[name="Department"]').change(function() {
        var selectedDepartmentId = $(this).val();
        var selectedDepartmentName = $(this).find('option:selected').text();
        
        // Determine if this is a redirect (department changed from original)
        // Only treat as redirect if originalDepartment exists AND selectedDepartment is different
        var isRedirect = false;
        if (originalDepartment && originalDepartment !== '') {
            isRedirect = (selectedDepartmentId && selectedDepartmentId !== originalDepartment);
        }
        
        console.log('Department changed:');
        console.log('- Selected: ' + selectedDepartmentId + ' (' + selectedDepartmentName + ')');
        console.log('- Original: ' + originalDepartment);
        console.log('- Is Redirect: ' + isRedirect);
        
        // Clear and disable the user dropdown if no department selected
        if (!selectedDepartmentId || selectedDepartmentId === '') {
            $('select[name="Assigned_User"]').html('<option value="">Select Department First</option>');
            $('select[name="Assigned_User"]').prop('disabled', true);
            $('select[name="Assigned_User"]').selectpicker('refresh');
            $('#user_info').hide().html('');
            return;
        }
        
        // Load users for the selected department
        loadUsersForDepartment(selectedDepartmentId, selectedDepartmentName, isRedirect);
    });
    
    // When user is selected
    $('select[name="Assigned_User"]').change(function() {
        var selectedUserId = $(this).val();
        var selectedUserText = $(this).find('option:selected').text();
        var selectedDept = $('select[name="Department"]').val();
        var selectedDeptName = $('select[name="Department"]').find('option:selected').text();
        
        var isRedirect = false;
        if (originalDepartment && originalDepartment !== '') {
            isRedirect = (selectedDept && selectedDept !== originalDepartment);
        }
        
        if (selectedUserId && selectedUserId !== '' && 
            selectedUserText !== '-- Select a Responsible Person --' && 
            selectedUserText !== '-- Select HOD --') {
            
            var icon = isRedirect ? 'fa-crown' : 'fa-user-check';
            var title = isRedirect ? 'HOD Selected' : 'User Selected';
            
            $('#user_info').html(`
                <div class="user-info-card" style="border-left-color: var(--primary-green);">
                    <div class="user-info-icon"><i class="fas ${icon}"></i></div>
                    <div class="user-info-content">
                        <div class="user-info-title">${title}</div>
                        <div class="user-info-text"><strong>${selectedUserText}</strong> assigned for ${selectedDeptName}</div>
                    </div>
                </div>
            `);
        }
    });
    
    // Initialize - disable user dropdown on page load
    $('select[name="Assigned_User"]').prop('disabled', true);
    $('select[name="Assigned_User"]').selectpicker('refresh');
    
    // Set default department and trigger load
    var defaultDept = '<?php echo $edit && isset($complaints['Department']) ? $complaints['Department'] : $currentUserDept; ?>';
    console.log('Default Department ID: ' + defaultDept);
    
    if (defaultDept && defaultDept !== '') {
        $('select[name="Department"]').val(defaultDept);
        $('select[name="Department"]').trigger('change');
    } else {
        $('select[name="Assigned_User"]').prop('disabled', true);
        $('select[name="Assigned_User"]').selectpicker('refresh');
    }
    
    // Form validation
    $("#contact_form").validate({
        rules: {
            MyComment: { required: true, minlength: 5, maxlength: 1000 },
            Department: { required: true },
            Assigned_User: { required: true },
            Status: { required: true }
        },
        messages: {
            MyComment: { required: "Your Comment is Required", minlength: "Min 5 chars" },
            Department: { required: "Select department" },
            Assigned_User: { required: "Select a Responsible Person" },
            Status: { required: "Select status" }
        },
        errorElement: "span",
        errorClass: "help-block",
        submitHandler: function(form) {
            var dept = $('select[name="Department"]').val();
            var user = $('select[name="Assigned_User"]').val();
            
            if (!dept || dept === '') {
                alert('Please select a department');
                return false;
            }
            if ($('select[name="Assigned_User"]').prop('disabled')) {
                alert('No user available for selected department');
                return false;
            }
            if (!user || user === '') {
                alert('Please select a user');
                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">
        <div class="page-header">
            <h1>
                <?php 
                $Originated_From = $complaints['Originated_From'] ?? '';
                $Originated_Name = "";
                $Originated_Position = "";
                if (!empty($Originated_From)) {
                    $result = mysqli_query($conn, "SELECT Full_Name, Position FROM admin_accounts WHERE id = '$Originated_From'");
                    if ($result && mysqli_num_rows($result) > 0) {
                        $rows = mysqli_fetch_array($result);
                        $Originated_Name = $rows['Full_Name'];
                        $Originated_Position = $rows['Position'];
                    }
                }
                $Originated_Display = $Originated_Name;
                if (!empty($Originated_Position)) {
                    $Originated_Display .= ' (' . $Originated_Position . ')';
                }
                ?>
                <i class="fas fa-plus-circle"></i>
                <?php echo 'Add a Response to Case #' . $ComplaintID . ' Initiated By: ' . htmlspecialchars($Originated_Display ?: '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>
        
        <?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; ?>
        
        <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">
                
                <div class="row">
                    <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;"><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></div>
                                </div>
                                <div class="form-group-custom" style="display: flex; align-items: center; margin-bottom: 10px;">
                                    <label class="form-label" style="width: 120px;"><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></div>
                                </div>
                                <div class="form-group-custom" style="display: flex; align-items: center; margin-bottom: 10px;">
                                    <label class="form-label" style="width: 120px;"><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></div>
                                </div>
                                <div class="form-group-custom" style="display: flex; align-items: center; margin-bottom: 10px;">
                                    <label class="form-label" style="width: 120px;"><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></div>
                                </div>
                                <div class="form-group-custom" style="display: flex; align-items: center; margin-bottom: 10px;">
                                    <label class="form-label" style="width: 120px;"><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></div>
                                </div>
                                <div class="form-group-custom" style="display: flex; align-items: center;">
                                    <label class="form-label" style="width: 120px;"><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></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-6">
                        <div class="section-card">
                            <div class="section-header"><i class="fas fa-exclamation-triangle"></i><h4>Task Description</h4></div>
                            <div class="section-body">
                                <div class="form-group-custom">
                                    <?php 
                                    $hasAttachment = !empty($complaints['File_Name']);
                                    $textareaRows = $hasAttachment ? 10 : 13;
                                    ?>
                                    <textarea class="form-control-custom" readonly rows="<?php echo $textareaRows; ?>"><?php echo $edit && isset($complaints['Problem']) ? htmlspecialchars($complaints['Problem']) : ''; ?></textarea>
                                </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>
                
                <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;"><i class="fas fa-user-tie"></i> Originated From:</label>
                                            <div class="input-group-custom" style="flex: 1;"><input type="text" class="form-control-custom" value="<?php echo htmlspecialchars($Originated_Display ?: 'Unknown'); ?>" readonly></div>
                                        </div>
                                        <div class="form-group-custom" style="display: flex; align-items: center;">
                                            <label class="form-label" style="width: 180px;"><i class="fas fa-user-tie"></i> Forwarded From:</label>
                                            <div class="input-group-custom" style="flex: 1;"><input type="text" class="form-control-custom" id="Forwarded_From" name="Forwarded_From" value="<?php echo htmlspecialchars($forwardedFrom ?: 'No previous forwarding'); ?>" readonly></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;"> (Forwarded by: <?php echo htmlspecialchars($remark['FromName']); ?>)</small><?php endif; ?></strong>
                                                                <small><i class="fas fa-calendar-alt"></i> <?php echo date('d-m-Y', strtotime($remark['Date'])); ?></small>
                                                            </div>
                                                            <?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;"><?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;"><?php echo nl2br(htmlspecialchars($remark['Remarks'])); ?></span></div>
                                                            <?php endif; ?>
                                                            <?php if (!empty($remark['Status'])): ?>
                                                                <div style="margin-top: 5px;"><span class="user-badge">Status: <?php echo htmlspecialchars($remark['Status']); ?></span></div>
                                                            <?php endif; ?>
                                                            <?php if (!empty($remark['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"></i> Attachment:</label>
                                                                    <div class="current-file" style="display: inline-block;"><a href="Uploads/<?php echo htmlspecialchars($remark['Attachment']); ?>" target="_blank" style="font-size: 11px;"><i class="fas fa-download"></i> Download</a></div>
                                                                </div>
                                                            <?php endif; ?>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>
                                                <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: ?>
                                                <textarea class="form-control-custom" rows="3" readonly>No previous history found for this case.</textarea>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <form action="" method="post" id="contact_form" enctype="multipart/form-data">	
                    <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>
                                                <textarea name="MyComment" placeholder="Enter your response here" required class="form-control-custom" rows="5"><?php echo isset($_POST['MyComment']) ? htmlspecialchars($_POST['MyComment']) : ''; ?></textarea>
                                                <input type="hidden" name="ComplaintID" value="<?php echo $ComplaintID; ?>">
                                                <input type="hidden" name="Forwarded_From" value="<?php echo htmlspecialchars($forwardedFrom ?: ''); ?>">
                                                <input type="hidden" name="Originated_From" value="<?php echo htmlspecialchars($Originated_Name ?: ''); ?>">
                                            </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>
                                                <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 class="col-md-4">
                                            <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>
                    
                    <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>
                                                        <?php foreach ($department_options as $dept) {
                                                            $selected = ($edit && isset($complaints['Department']) && $complaints['Department'] == $dept['id']) ? 'selected' : '';
                                                            if (!$edit && !isset($complaints['Department']) && $currentUserDept == $dept['id']) {
                                                                $selected = 'selected';
                                                            }
                                                            echo "<option value=\"" . htmlspecialchars($dept['id']) . "\" $selected>" . htmlspecialchars($dept['Name']) . "</option>";
                                                        } ?>
                                                    </select>
                                                </div>
                                                <small class="text-muted">Default is your department. Change only if redirecting to another department.</small>
                                            </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_User" class="form-control-custom select-custom" required>
                                                        <option value="">Select Department First</option>
                                                    </select>
                                                </div>
                                                <small class="text-muted">Select department to see available users</small>
                                            </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" <?php echo ($edit && isset($complaints['Status']) && $complaints['Status'] == 'In Progress') ? 'selected' : ''; ?>>In Progress</option>
                                                        <option value="Appended" <?php echo ($edit && isset($complaints['Status']) && $complaints['Status'] == 'Appended') ? 'selected' : ''; ?>>Appended</option>
                                                        <option value="Rejected" <?php echo ($edit && isset($complaints['Status']) && $complaints['Status'] == 'Rejected') ? 'selected' : ''; ?>>Rejected</option>
                                                        <option value="Completed" <?php echo ($edit && isset($complaints['Status']) && $complaints['Status'] == 'Completed') ? 'selected' : ''; ?>>Completed</option>
                                                        <option value="Redirected" <?php echo ($edit && isset($complaints['Status']) && $complaints['Status'] == 'Redirected') ? 'selected' : ''; ?>>Redirected</option>
                                                        <option value="Pending" <?php echo ($edit && isset($complaints['Status']) && $complaints['Status'] == 'Pending') ? 'selected' : ''; ?>>Pending</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div id="user_info" class="mt-2"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <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 'include/footer.php'; 
?>