Mini Shell

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

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

// Load PHPMailer
require $rootPath . '/PHPMailer/src/PHPMailer.php';
require $rootPath . '/PHPMailer/src/SMTP.php';
require $rootPath . '/PHPMailer/src/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Get complaint ID from URL
$ComplaintID = filter_input(INPUT_GET, 'ComplaintID', FILTER_VALIDATE_INT);

if (!$ComplaintID) {
    $_SESSION['failure'] = "No complaint ID provided for editing.";
    header('Location: Complaints.php');
    exit();
}

// Fetch existing complaint data
$query = "SELECT * FROM complaints WHERE ComplaintID = '$ComplaintID'";
$result = mysqli_query($conn, $query);

if (!$result || mysqli_num_rows($result) == 0) {
    $_SESSION['failure'] = "Complaint with ID $ComplaintID not found.";
    header('Location: Complaints.php');
    exit();
}

$complaint = mysqli_fetch_assoc($result);

// Initialize variables with existing data
$Name = $complaint['Name'] ?? '';
$Property_Number = $complaint['Property_Number'] ?? '';
$phone = $complaint['phone'] ?? '';
$Status = $complaint['Status'] ?? '';
$email = $complaint['email'] ?? '';
$address = $complaint['address'] ?? '';
$problem = $complaint['Problem'] ?? '';
$Department = $complaint['Department'] ?? '';
$Assigned_Admin = $complaint['Assigned_To'] ?? '';
$Heading = $complaint['Heading'] ?? '';
$AttentionDepartment = $complaint['Attentioned_Dept'] ?? '';
$AttentionAssigned_Admin = $complaint['Atentioned_User'] ?? '';
$currentFileName = $complaint['File_Name'] ?? '';

$errors = array();

// Get current session user ID
$currentUserId = $_SESSION['id'];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
 
    // Check if connection is established
    if (!isset($conn)) {
        $_SESSION['failure'] = "Database connection failed!";
        header('location: Edit_File.php?ComplaintID=' . $ComplaintID);
        exit();
    }
    
    date_default_timezone_set('Africa/Blantyre');
    $MesaageTime = date('d-m-Y H:i', time());

    // Sanitize input data
    $Name = mysqli_real_escape_string($conn, trim($_POST["Name"]));
    $Property_Number = mysqli_real_escape_string($conn, trim($_POST["Property_Number"]));
    $phone = mysqli_real_escape_string($conn, trim($_POST['phone']));    
    $Status = mysqli_real_escape_string($conn, trim($_POST['Status']));
    $email = mysqli_real_escape_string($conn, trim($_POST['email']));
    $address = mysqli_real_escape_string($conn, trim($_POST['address']));
    $problem = mysqli_real_escape_string($conn, trim($_POST['problem']));
    $Department = mysqli_real_escape_string($conn, trim($_POST['Department']));  
    $Assigned_Admin = mysqli_real_escape_string($conn, trim($_POST['Assigned_Admin']));
    $Heading = mysqli_real_escape_string($conn, trim($_POST['Heading']));
    $Send_Email = isset($_POST['Send_Email']) ? 'yes' : 'no';
    
    // Attention fields
    $AttentionDepartment = !empty($_POST['AttentionDepartment']) ? mysqli_real_escape_string($conn, trim($_POST['AttentionDepartment'])) : '';
    $AttentionAssigned_Admin = !empty($_POST['AttentionAssigned_Admin']) ? mysqli_real_escape_string($conn, trim($_POST['AttentionAssigned_Admin'])) : '';

    // Validate required fields
    if (empty($Department)) $errors[] = "Department is required";
    if (empty($Assigned_Admin)) $errors[] = "Assigned HOD is required";
    if (empty($problem)) $errors[] = "Problem description is required";
    
    // Validate attention fields
    if (!empty($AttentionDepartment) && empty($AttentionAssigned_Admin)) {
        $errors[] = "Attention Assigned Admin is required when Attention Department is selected";
    }
    
    // Validate email if Send_Email is checked
    if ($Send_Email == 'yes') {
        if (empty($email)) {
            $errors[] = "Email address is required when 'Notify Client' is checked";
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = "Invalid email format";
        }
    }
    
    // Validate AttentionAssigned_Admin belongs to AttentionDepartment
    if (!empty($AttentionDepartment) && !empty($AttentionAssigned_Admin)) {
        $attention_user_query = mysqli_query($conn, "SELECT Full_Name, Position, UserDepartment, HOD FROM admin_accounts WHERE id = '$AttentionAssigned_Admin' AND Status = 'Active'");
        
        if ($attention_user_query && mysqli_num_rows($attention_user_query) > 0) {
            $attention_user_data = mysqli_fetch_assoc($attention_user_query);
            $Attention_User_Department = $attention_user_data['UserDepartment'];
            $IsAttentionHOD = $attention_user_data['HOD'];
            
            // Verify department match for attention user
            if (strtoupper(trim($Attention_User_Department)) != strtoupper(trim($AttentionDepartment))) {
                $errors[] = "Attention Assigned Admin does not belong to the selected Attention Department!";
            }
            
            // Verify they are HOD
            if ($IsAttentionHOD != '1') {
                $errors[] = "Attention Assigned Admin is not a Head of Department! Only HODs can be assigned as attention users.";
            }
        } else {
            $errors[] = "Invalid or inactive Attention Assigned Admin selected!";
        }
    }
    
    if (empty($errors)) {
        
        // Get user details - verify they are HOD and belong to correct department
        $user_query = mysqli_query($conn, "SELECT Full_Name, Position, UserDepartment, HOD FROM admin_accounts WHERE id = '$Assigned_Admin' AND Status = 'Active'");
        
        if ($user_query && mysqli_num_rows($user_query) > 0) {
            $user_data = mysqli_fetch_assoc($user_query);
            $User_Name = $user_data['Full_Name'];
            $User_Department = $user_data['UserDepartment'];
            $IsHOD = $user_data['HOD'];
            $User_Position = !empty($user_data['Position']) ? $user_data['Position'] : 'Head of Department';

            // Verify department match
            if (strtoupper(trim($User_Department)) != strtoupper(trim($Department))) {
                $_SESSION['failure'] = "Selected person does not belong to the chosen department! Selected HOD is from $User_Department department, but you selected $Department department.";
                header('location: Edit_File.php?ComplaintID=' . $ComplaintID);
                exit();
            }
            
            // Verify they are HOD
            if ($IsHOD != '1') {
                $_SESSION['failure'] = "Selected person is not a Head of Department! Only HODs can be assigned.";
                header('location: Edit_File.php?ComplaintID=' . $ComplaintID);
                exit();
            }
            
            date_default_timezone_set('Africa/Blantyre');
            $MessageTime = date('d-m-Y H:i', time());

            // File Upload Handling - REPLACE old file if new one is uploaded
            $file_name = $currentFileName; // Keep existing file by default
            
            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;
                if ($size > $max_size) {
                    $_SESSION['failure'] = "File size too large. Maximum size is 5MB.";
                    header('location: Edit_File.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: Edit_File.php?ComplaintID=' . $ComplaintID);
                    exit();
                }
                
                // Delete old file if it exists
                if (!empty($currentFileName)) {
                    $oldFilePath = "Uploads/" . $currentFileName;
                    if (file_exists($oldFilePath)) {
                        unlink($oldFilePath);
                    }
                }
                
                // 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: Edit_File.php?ComplaintID=' . $ComplaintID);
                    exit();
                }
            }  
            
            // Update complaint in database
            $query = "UPDATE complaints SET 
                      Heading = '$Heading',
                      Name = '$Name',
                      Property_Number = '$Property_Number',
                      phone = '$phone',
                      email = '$email',
                      Problem = '$problem',
                      Department = '$Department',
                      Assigned_To = '$Assigned_Admin',
                      Status = '$Status',
                      Attentioned_Dept = '$AttentionDepartment',
                      Atentioned_User = '$AttentionAssigned_Admin',
                      File_Name = '$file_name'
                      WHERE ComplaintID = '$ComplaintID'";
            
            $update_sql = mysqli_query($conn, $query);
 
            if ($update_sql) {
                // Send email if requested and email is provided (and email has changed or new email)
                if ($Send_Email == 'yes' && !empty($email)) {
                    try {
                        // ============= SMTP CONFIGURATION =============
                        $smtp_host = "localhost";
                        $smtp_port = 25;
                        $smtp_username = "";
                        $smtp_password = "";
                        $smtp_secure = "";
                        // =============================================
                        
                        // Create PHPMailer instance
                        $mail = new PHPMailer(true);
                        
                        // Server settings
                        $mail->isSMTP();
                        $mail->Host       = $smtp_host;
                        $mail->Port       = $smtp_port;
                        $mail->SMTPAuth   = !empty($smtp_username);
                        $mail->SMTPSecure = $smtp_secure;
                        
                        if (!empty($smtp_username)) {
                            $mail->Username = $smtp_username;
                            $mail->Password = $smtp_password;
                        }
                        
                        // Timeout settings
                        $mail->Timeout = 30;
                        $mail->SMTPDebug = 0;
                        
                        // Recipients
                        $mail->setFrom('noreply@' . $_SERVER['HTTP_HOST'], 'MHC IMS');
                        $mail->addAddress($email, $Name ?: 'Valued Customer');
                        
                        // Content
                        $mail->isHTML(true);
                        $mail->Subject = "Case #$ComplaintID: Your Case Has Been Updated - MHC";
                        
                        // Email body with styling
                        $mail->Body = "
                        <!DOCTYPE html>
                        <html>
                        <head>
                            <meta charset='UTF-8'>
                            <style>
                                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                                .container { max-width: 600px; margin: 0 auto; }
                                .header { background: #28a745; color: white; padding: 20px; border-radius: 5px 5px 0 0; }
                                .content { padding: 20px; background: #f9f9f9; }
                                .field { background: white; padding: 15px; margin-bottom: 10px; border-left: 4px solid #28a745; }
                                .label { font-weight: bold; color: #555; display: block; margin-bottom: 5px; }
                                .case-number { font-size: 20px; color: #28a745; font-weight: bold; padding: 10px; background: #e8f5e9; border-radius: 4px; text-align: center; }
                                .highlight { background: #f8f9fa; padding: 10px; border-radius: 4px; }
                                .footer { padding: 15px; text-align: center; color: #666; font-size: 12px; background: #eee; border-radius: 0 0 5px 5px; }
                            </style>
                        </head>
                        <body>
                            <div class='container'>
                                <div class='header'>
                                    <h2>CASE UPDATED</h2>
                                </div>
                                
                                <div class='content'>
                                    <p>Dear " . ($Name ? htmlspecialchars($Name) : 'Valued Customer') . ",</p>
                                    <p>Your case has been updated. Here are the current details:</p>
                                    
                                    <div class='field'>
                                        <span class='label'>📋 CASE NUMBER:</span>
                                        <div class='case-number'>#" . htmlspecialchars($ComplaintID) . "</div>
                                    </div>
                                    
                                    <div class='field'>
                                        <span class='label'>📝 CASE HEADING:</span>
                                        <div>" . htmlspecialchars($Heading) . "</div>
                                    </div>
                                    
                                    <div class='field'>
                                        <span class='label'>📌 CURRENT STATUS:</span>
                                        <div><strong>" . htmlspecialchars($Status) . "</strong></div>
                                    </div>
                                    
                                    <div class='field'>
                                        <span class='label'>🏢 ASSIGNED DEPARTMENT:</span>
                                        <div>" . htmlspecialchars($Department) . "</div>
                                    </div>
                                    
                                    <p style='background: #e8f5e9; padding: 10px; border-radius: 4px;'>
                                        <strong>You can track your case status by quoting case number: #" . htmlspecialchars($ComplaintID) . "</strong>
                                    </p>
                                </div>
                                
                                <div class='footer'>
                                    <p>This email was sent automatically from MHC. Please do not reply to this email.</p>
                                    <p>&copy; " . date('Y') . " MHC. All rights reserved.</p>
                                </div>
                            </div>
                        </body>
                        </html>";
                        
                        // Alternative plain text version
                        $mail->AltBody = "CASE UPDATED - CASE #$ComplaintID\n\n" .
                                        "Dear " . ($Name ? $Name : 'Valued Customer') . ",\n\n" .
                                        "Your case has been updated.\n\n" .
                                        "═══════════════════════════════\n" .
                                        "CASE NUMBER: #$ComplaintID\n" .
                                        "CASE HEADING: $Heading\n" .
                                        "CURRENT STATUS: $Status\n" .
                                        "ASSIGNED DEPARTMENT: $Department\n" .
                                        "═══════════════════════════════\n\n" .
                                        "You can track your case status by quoting case number: #$ComplaintID\n\n" .
                                        "═══════════════════════════════\n" .
                                        "This email was sent automatically from MHC.\n" .
                                        "© " . date('Y') . " MHC. All rights reserved.";
                        
                        // Send email
                        $mail->send();
                        
                        // Log email success
                        error_log("Case update notification email sent for case #$ComplaintID to $email");
                        
                    } catch (Exception $e) {
                        // Log email error but don't stop the process
                        error_log("Failed to send case update notification email for case #$ComplaintID: " . $e->getMessage());
                        $_SESSION['warning'] = "Case #$ComplaintID updated but email notification could not be sent. Error: " . $e->getMessage();
                    }
                }
                
                // Success message
                $fileMsg = ($file_name != $currentFileName && !empty($file_name)) ? " File replaced." : "";
                $_SESSION['success'] = "Case #$ComplaintID updated successfully!" . $fileMsg . 
                                      ($Send_Email == 'yes' && !empty($email) ? " Email notification sent to $email." : "");
                
                header('location: Complaints.php');
                exit();
            } else {
                $_SESSION['failure'] = "Error updating case: " . mysqli_error($conn);
                header('location: Edit_File.php?ComplaintID=' . $ComplaintID);
                exit();
            }
        } else {
            $_SESSION['failure'] = "Invalid or inactive user selected!";
            header('location: Edit_File.php?ComplaintID=' . $ComplaintID);
            exit();
        }
        
    } else {
        $_SESSION['failure'] = implode("<br>", $errors);
        header('location: Edit_File.php?ComplaintID=' . $ComplaintID);
        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 header
include_once 'include/AdminHeader.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 - Same as add_complaint.php */
    :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);
    }

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

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

    .form-container {
        max-width: 1400px;
        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;
    }

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

    .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-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 #dc3545;
    }

    .alert-custom-warning {
        background: #fff3cd;
        color: #856404;
        border-left: 4px solid #ffc107;
    }

    .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-card {
        background: var(--soft-white);
        border-radius: 8px;
        margin-bottom: 12px;
        overflow: hidden;
        border: 1px solid var(--light-gray);
        height: 100%;
    }

    .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-row {
        display: flex;
        align-items: flex-start;
        margin-bottom: 12px;
    }
    
    .form-group-row .label-col {
        flex: 0 0 110px;
        padding-right: 10px;
    }
    
    .form-group-row .field-col {
        flex: 1;
    }
    
    .form-group-row .form-label {
        margin-bottom: 0;
        padding-top: 8px;
        color: var(--dark-gray);
        font-weight: 500;
        font-size: 12px;
        text-transform: uppercase;
        letter-spacing: 0.2px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    .form-group-row .form-label i {
        color: var(--primary-green);
        margin-right: 4px;
        font-size: 11px;
        width: 14px;
        text-align: center;
    }
    
    .input-group-custom {
        position: relative;
        display: flex;
        align-items: center;
        width: 100%;
    }

    .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-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;
    }

    .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;
        margin-right: 4px;
        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-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;
    }

    .has-error .form-control-custom {
        border-color: #dc3545;
        background-color: #fff8f8;
    }

    .help-block {
        display: block;
        margin-top: 3px;
        color: #dc3545;
        font-size: 11px;
        font-weight: 500;
        padding-left: 32px;
    }

    .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;
    }

    .checkbox-group {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 3px 0;
    }

    .checkbox-group input[type="checkbox"] {
        width: 14px;
        height: 14px;
        cursor: pointer;
        accent-color: var(--primary-green);
    }

    .checkbox-group label {
        color: var(--dark-gray);
        font-size: 12px;
        cursor: pointer;
    }

    .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 {
        margin-top: 5px;
        padding: 5px 10px;
        background: var(--light-green);
        border-radius: 4px;
        font-size: 12px;
    }

    .current-file a {
        color: var(--primary-green);
        text-decoration: none;
    }

    .current-file a:hover {
        text-decoration: underline;
    }

    .row {
        margin-left: -6px;
        margin-right: -6px;
    }
    
    [class*="col-"] {
        padding-left: 6px;
        padding-right: 6px;
    }

    @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;
        }
        
        .form-group-row {
            flex-direction: column;
        }
        
        .form-group-row .label-col {
            flex: 0 0 auto;
            width: 100%;
            padding-right: 0;
            margin-bottom: 3px;
        }
        
        .form-group-row .form-label {
            white-space: normal;
        }
    }
    
    .required-field::after {
        content: " *";
        color: #dc3545;
        font-weight: bold;
    }
</style>

<script type="text/javascript">
$(document).ready(function() {
    // Initialize Bootstrap Select
    $('.selectpicker').selectpicker({
        size: 5,
        dropupAuto: false
    });
    
    // Store existing assigned admin ID
    var existingAssignedAdmin = '<?php echo $Assigned_Admin; ?>';
    var existingAttentionUser = '<?php echo $AttentionAssigned_Admin; ?>';
    
    // Display file info when file is selected
    $('#file').on('change', function() {
        var fileName = $(this).val().split('\\').pop();
        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)<br><small class="text-muted">This will REPLACE the existing file</small>';
            
            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 main department selection changes
    $('select[name="Department"]').change(function() {
        var selectedDepartment = $(this).val();
        var selectedDepartmentName = $(this).find('option:selected').text();
        var $userSelect = $('select[name="Assigned_Admin"]');
        var $userInfo = $('#user_info');
        
        if (!selectedDepartment || selectedDepartment === '') {
            $userSelect.html('<option value="">Select Department First</option>');
            $userSelect.prop('disabled', true);
            $userSelect.selectpicker('refresh');
            $userInfo.hide().html('');
            return;
        }
        
        $userSelect.html('<option value="">Loading HODs...</option>');
        $userSelect.prop('disabled', true);
        $userSelect.selectpicker('refresh');
        
        $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 HODs</div>
                    <div class="user-info-text">Loading available HODs for <strong>${selectedDepartmentName}</strong> department...</div>
                </div>
            </div>
        `);
        
        $.ajax({
            url: 'get_hod_by_department.php',
            type: 'POST',
            data: { department: selectedDepartment },
            dataType: 'json',
            timeout: 10000,
            success: function(response) {
                $userSelect.html('');
                var hods = response.hods || [];
                
                if (hods && hods.length > 0) {
                    $userSelect.append('<option value="">-- Select HOD --</option>');
                    
                    $.each(hods, function(index, hod) {
                        var displayText = hod.display_name || (hod.full_name + ' (' + (hod.position || 'HOD') + ')');
                        var selected = (existingAssignedAdmin && existingAssignedAdmin == hod.id) ? 'selected' : '';
                        $userSelect.append('<option value="' + hod.id + '" ' + selected + '>' + displayText + '</option>');
                    });
                    
                    $userSelect.prop('disabled', false);
                    
                    $userInfo.html(`
                        <div class="user-info-card" style="border-left-color: var(--primary-green);">
                            <div class="user-info-icon" style="color: var(--primary-green);">
                                <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>${hods.length} Head(s) of Department found</strong> in ${selectedDepartmentName} department
                                </div>
                            </div>
                        </div>
                    `);
                } else {
                    $userSelect.html('<option value="">⛔ No HOD available in ' + selectedDepartmentName + '</option>');
                    $userSelect.prop('disabled', true);
                    
                    $userInfo.html(`
                        <div class="user-info-card" style="border-left-color: #dc3545;">
                            <div class="user-info-icon" style="color: #dc3545;">
                                <i class="fas fa-exclamation-triangle"></i>
                            </div>
                            <div class="user-info-content">
                                <div class="user-info-title" style="color: #dc3545;">No HOD Available</div>
                                <div class="user-info-text">
                                    <strong>No Head of Department found</strong> for ${selectedDepartmentName} department.
                                </div>
                            </div>
                        </div>
                    `);
                }
                
                $userSelect.selectpicker('refresh');
            },
            error: function(xhr, status, error) {
                $userSelect.html('<option value="">Error loading HODs</option>');
                $userSelect.prop('disabled', true);
                $userSelect.selectpicker('refresh');
                
                $userInfo.html(`
                    <div class="user-info-card" style="border-left-color: #dc3545;">
                        <div class="user-info-icon" style="color: #dc3545;">
                            <i class="fas fa-times-circle"></i>
                        </div>
                        <div class="user-info-content">
                            <div class="user-info-title" style="color: #dc3545;">Error</div>
                            <div class="user-info-text">
                                Error loading HODs. Please refresh and try again.
                            </div>
                        </div>
                    </div>
                `);
            }
        });
    });
    
    // When Attention Department selection changes
    $('select[name="AttentionDepartment"]').change(function() {
        var selectedAttentionDept = $(this).val();
        var selectedAttentionDeptName = $(this).find('option:selected').text();
        var $attentionUserSelect = $('select[name="AttentionAssigned_Admin"]');
        var $attentionInfo = $('#attention_user_info');
        
        if (!selectedAttentionDept || selectedAttentionDept === '') {
            $attentionUserSelect.html('<option value="">Select Department First</option>');
            $attentionUserSelect.prop('disabled', true);
            $attentionUserSelect.selectpicker('refresh');
            $attentionInfo.hide().html('');
            return;
        }
        
        $attentionUserSelect.html('<option value="">Loading HODs...</option>');
        $attentionUserSelect.prop('disabled', true);
        $attentionUserSelect.selectpicker('refresh');
        
        $attentionInfo.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 HODs for Attention</div>
                    <div class="user-info-text">Loading available HODs for <strong>${selectedAttentionDeptName}</strong> department...</div>
                </div>
            </div>
        `);
        
        $.ajax({
            url: 'get_hod_by_department.php',
            type: 'POST',
            data: { department: selectedAttentionDept },
            dataType: 'json',
            timeout: 10000,
            success: function(response) {
                $attentionUserSelect.html('');
                var hods = response.hods || [];
                
                if (hods && hods.length > 0) {
                    $attentionUserSelect.append('<option value="">-- Select HOD for Attention --</option>');
                    
                    $.each(hods, function(index, hod) {
                        var displayText = hod.display_name || (hod.full_name + ' (' + (hod.position || 'HOD') + ')');
                        var selected = (existingAttentionUser && existingAttentionUser == hod.id) ? 'selected' : '';
                        $attentionUserSelect.append('<option value="' + hod.id + '" ' + selected + '>' + displayText + '</option>');
                    });
                    
                    $attentionUserSelect.prop('disabled', false);
                    
                    $attentionInfo.html(`
                        <div class="user-info-card" style="border-left-color: var(--primary-green);">
                            <div class="user-info-icon" style="color: var(--primary-green);">
                                <i class="fas fa-crown"></i>
                            </div>
                            <div class="user-info-content">
                                <div class="user-info-title">Attention HODs Available</div>
                                <div class="user-info-text">
                                    <strong>${hods.length} Head(s) of Department found</strong> in ${selectedAttentionDeptName} department
                                </div>
                            </div>
                        </div>
                    `);
                } else {
                    $attentionUserSelect.html('<option value="">⛔ No HOD available in ' + selectedAttentionDeptName + '</option>');
                    $attentionUserSelect.prop('disabled', true);
                    
                    $attentionInfo.html(`
                        <div class="user-info-card" style="border-left-color: #dc3545;">
                            <div class="user-info-icon" style="color: #dc3545;">
                                <i class="fas fa-exclamation-triangle"></i>
                            </div>
                            <div class="user-info-content">
                                <div class="user-info-title" style="color: #dc3545;">No HOD Available</div>
                                <div class="user-info-text">
                                    <strong>No Head of Department found</strong> for ${selectedAttentionDeptName} department.
                                </div>
                            </div>
                        </div>
                    `);
                }
                
                $attentionUserSelect.selectpicker('refresh');
            },
            error: function(xhr, status, error) {
                $attentionUserSelect.html('<option value="">Error loading HODs</option>');
                $attentionUserSelect.prop('disabled', true);
                $attentionUserSelect.selectpicker('refresh');
                
                $attentionInfo.html(`
                    <div class="user-info-card" style="border-left-color: #dc3545;">
                        <div class="user-info-icon" style="color: #dc3545;">
                            <i class="fas fa-times-circle"></i>
                        </div>
                        <div class="user-info-content">
                            <div class="user-info-title" style="color: #dc3545;">Error</div>
                            <div class="user-info-text">
                                Error loading HODs. Please refresh and try again.
                            </div>
                        </div>
                    </div>
                `);
            }
        });
    });
    
    // Initialize - trigger department change to load HODs
    var currentDept = '<?php echo $Department; ?>';
    if (currentDept && currentDept !== '') {
        $('select[name="Department"]').val(currentDept);
        $('select[name="Department"]').trigger('change');
    }
    
    var currentAttentionDept = '<?php echo $AttentionDepartment; ?>';
    if (currentAttentionDept && currentAttentionDept !== '') {
        $('select[name="AttentionDepartment"]').val(currentAttentionDept);
        $('select[name="AttentionDepartment"]').trigger('change');
    }
    
    // Form validation
    $("#contact_form").validate({
        rules: {
            Heading: {
                required: true,
                minlength: 3,
                maxlength: 200
            },
            Name: {
                minlength: 3,
                maxlength: 100
            },
            phone: {
                minlength: 10,
                maxlength: 15,
                digits: true
            },
            email: {
                email: true,
                maxlength: 100
            },
            address: {
                maxlength: 200
            },
            Department: {
                required: true
            },
            Assigned_Admin: {
                required: true
            },
            AttentionAssigned_Admin: {
                required: function(element) {
                    return $('select[name="AttentionDepartment"]').val() !== '';
                }
            },
            problem: {
                required: true,
                minlength: 10,
                maxlength: 1000
            },
            Property_Number: {
                maxlength: 50
            }
        },
        messages: {
            Heading: {
                required: "Required",
                minlength: "Min 3 chars"
            },
            Name: {
                minlength: "Min 3 chars"
            },
            phone: {
                minlength: "Min 10 digits",
                digits: "Digits only"
            },
            email: {
                email: "Invalid email"
            },
            address: {
                maxlength: "Max 200 chars"
            },
            Department: {
                required: "Select department"
            },
            Assigned_Admin: {
                required: "Select HOD"
            },
            AttentionAssigned_Admin: {
                required: "Attention User is required when Attention Department is selected"
            },
            problem: {
                required: "Required",
                minlength: "Min 10 chars"
            }
        },
        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) {
            var dept = $('select[name="Department"]').val();
            var user = $('select[name="Assigned_Admin"]').val();
            var sendEmail = $('#Send_Email').is(':checked');
            var email = $('#email').val();
            
            var attentionDept = $('select[name="AttentionDepartment"]').val();
            var attentionUser = $('select[name="AttentionAssigned_Admin"]').val();
            
            if (attentionDept && attentionDept !== '' && (!attentionUser || attentionUser === '')) {
                alert('Attention User is required when Attention Department is selected');
                return false;
            }
            
            if (sendEmail && (!email || email.trim() === '')) {
                alert('Email address is required when "Notify Client" is checked');
                return false;
            }
            
            if (!dept || dept === '') {
                alert('Please select a department');
                return false;
            }
            
            if ($('select[name="Assigned_Admin"]').prop('disabled')) {
                alert('No HOD available for selected department');
                return false;
            }
            
            if (!user || user === '') {
                alert('Please select an HOD');
                return false;
            }
            
            $('.btn-submit').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Updating...');
            form.submit();
        }
    });
});
</script>

<div id="page-wrapper">
    <div class="form-container">
        <!-- Header Section -->
        <div class="page-header">
            <h1>
                <i class="fas fa-edit"></i>
                Edit Case #<?php echo $ComplaintID; ?> - <?php echo htmlspecialchars($Heading); ?>
            </h1>
            <div class="action-buttons">
                <a href="Complaints.php" class="btn-custom btn-custom-primary">
                    <i class="fas fa-arrow-left"></i>
                    Back to List
                </a>
                <a href="Edit_File.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['warning'])): ?>
            <div class="alert-custom alert-custom-warning">
                <i class="fas fa-exclamation-triangle"></i>
                <div><?php echo $_SESSION['warning']; unset($_SESSION['warning']); ?></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-edit"></i>
                <h3>Edit Case Details</h3>
            </div>
            <div class="form-card-body">
                <form action="" method="post" id="contact_form" enctype="multipart/form-data">    
                    <!-- Status Field (Visible) -->
                    <input type="hidden" name="Status" value="<?php echo htmlspecialchars($Status); ?>">
                    
                    <!-- First Row: Two Columns -->
                    <div class="row">
                        <!-- Left Column - Case Information -->
                        <div class="col-lg-6">
                            <div class="section-card">
                                <div class="section-header">
                                    <i class="fas fa-user"></i>
                                    <h4>Case Information</h4>
                                </div>
                                <div class="section-body">
                                    <!-- Heading -->
                                    <div class="form-group-row">
                                        <div class="label-col">
                                            <label class="form-label required-field">
                                                <i class="fas fa-heading"></i>
                                                Heading
                                            </label>
                                        </div>
                                        <div class="field-col">
                                            <div class="input-group-custom">
                                                <i class="fas fa-heading input-icon"></i>
                                                <input type="text" name="Heading" placeholder="Enter case heading" 
                                                       class="form-control-custom" autocomplete="off" id="Heading" 
                                                       value="<?php echo htmlspecialchars($Heading); ?>">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Customer Name -->
                                    <div class="form-group-row">
                                        <div class="label-col">
                                            <label class="form-label">
                                                <i class="fas fa-user"></i>
                                                Client Name
                                            </label>
                                        </div>
                                        <div class="field-col">
                                            <div class="input-group-custom">
                                                <i class="fas fa-user input-icon"></i>
                                                <input type="text" name="Name" placeholder="Full name (optional)" 
                                                       class="form-control-custom" autocomplete="off" id="Name" 
                                                       value="<?php echo htmlspecialchars($Name); ?>">
                                            </div>
                                            <small class="text-muted">Optional</small>
                                        </div>
                                    </div>
                                    
                                    <!-- Property Number -->
                                    <div class="form-group-row">
                                        <div class="label-col">
                                            <label class="form-label">
                                                <i class="fas fa-hashtag"></i>
                                                Property #
                                            </label>
                                        </div>
                                        <div class="field-col">
                                            <div class="input-group-custom">
                                                <i class="fas fa-home input-icon"></i>
                                                <input type="text" name="Property_Number" placeholder="Property number" 
                                                       class="form-control-custom" autocomplete="off" id="Property_Number" 
                                                       value="<?php echo htmlspecialchars($Property_Number); ?>">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Phone -->
                                    <div class="form-group-row">
                                        <div class="label-col">
                                            <label class="form-label">
                                                <i class="fas fa-phone"></i>
                                                Client Phone
                                            </label>
                                        </div>
                                        <div class="field-col">
                                            <div class="input-group-custom">
                                                <i class="fas fa-phone input-icon"></i>
                                                <input type="text" name="phone" placeholder="Phone number (optional)" 
                                                       class="form-control-custom" autocomplete="off" id="phone" 
                                                       value="<?php echo htmlspecialchars($phone); ?>">
                                            </div>
                                            <small class="text-muted">Optional</small>
                                        </div>
                                    </div>
                                    
                                    <!-- Email -->
                                    <div class="form-group-row">
                                        <div class="label-col">
                                            <label class="form-label">
                                                <i class="fas fa-envelope"></i>
                                                Client Email
                                            </label>
                                        </div>
                                        <div class="field-col">
                                            <div class="input-group-custom">
                                                <i class="fas fa-envelope input-icon"></i>
                                                <input type="email" name="email" placeholder="Email address (optional)" 
                                                       class="form-control-custom" id="email" 
                                                       value="<?php echo htmlspecialchars($email); ?>">
                                            </div>
                                            <small class="text-muted">Optional unless sending notification</small>
                                        </div>
                                    </div>
                                    
                                    <!-- Address -->
                                    <div class="form-group-row">
                                        <div class="label-col">
                                            <label class="form-label">
                                                <i class="fas fa-map-marker-alt"></i>
                                                Client Address
                                            </label>
                                        </div>
                                        <div class="field-col">
                                            <div class="input-group-custom">
                                                <i class="fas fa-map-marker-alt input-icon"></i>
                                                <textarea name="address" placeholder="Customer address (optional)" 
                                                          class="form-control-custom" id="address" rows="2"><?php echo htmlspecialchars($address); ?></textarea>
                                            </div>
                                            <small class="text-muted">Optional</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Right Column - Problem Description -->
                        <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-row">
                                        <div class="field-col" style="margin-left: 0; padding-left: 0;">
                                            <div class="input-group-custom">
                                                <textarea name="problem" placeholder="Describe the problem in detail" 
                                                          class="form-control-custom" id="problem" rows="15"><?php echo htmlspecialchars($problem); ?></textarea>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Second Row: Full Width - Assignment and 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">
                                    <!-- Status Display -->
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group-row">
                                                <div class="label-col">
                                                    <label class="form-label required-field">
                                                        <i class="fas fa-tag"></i>
                                                        Current Status
                                                    </label>
                                                </div>
                                                <div class="field-col">
                                                    <div class="input-group-custom">
                                                        <i class="fas fa-tag input-icon"></i>
                                                        <select name="Status" class="form-control-custom select-custom" required>
                                                            <option value="New" <?php echo $Status == 'New' ? 'selected' : ''; ?>>New</option>
                                                            <option value="In Progress" <?php echo $Status == 'In Progress' ? 'selected' : ''; ?>>In Progress</option>
                                                            <option value="Completed" <?php echo $Status == 'Completed' ? 'selected' : ''; ?>>Completed</option>
                                                            <option value="On Hold" <?php echo $Status == 'On Hold' ? 'selected' : ''; ?>>On Hold</option>
                                                            <option value="Cancelled" <?php echo $Status == 'Cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Department and Assign To - Side by side -->
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group-row">
                                                <div class="label-col">
                                                    <label class="form-label required-field">
                                                        <i class="fas fa-briefcase"></i>
                                                        Addressed To
                                                    </label>
                                                </div>
                                                <div class="field-col">
                                                    <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 = ($Department == $dept['id']) ? 'selected' : '';
                                                                echo "<option value=\"" . htmlspecialchars($dept['id']) . "\" $selected>" . htmlspecialchars($dept['Name']) . "</option>";
                                                            }
                                                            ?>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="form-group-row">
                                                <div class="label-col">
                                                    <label class="form-label required-field">
                                                        <i class="fas fa-crown"></i>
                                                        Name & Title
                                                    </label>
                                                </div>
                                                <div class="field-col">
                                                    <div class="input-group-custom">
                                                        <i class="fas fa-crown 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>
                                    </div>
                                    
                                    <!-- Attention Department and Attention User -->
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group-row">
                                                <div class="label-col">
                                                    <label class="form-label">
                                                        <i class="fas fa-bell"></i>
                                                        Attention To
                                                    </label>
                                                </div>
                                                <div class="field-col">
                                                    <div class="input-group-custom">
                                                        <i class="fas fa-bell input-icon"></i>
                                                        <select name="AttentionDepartment" class="form-control-custom select-custom">
                                                            <option value="">-- Select Department (Optional) --</option>
                                                            <?php
                                                            foreach ($department_options as $dept) {
                                                                $selected = ($AttentionDepartment == $dept['id']) ? 'selected' : '';
                                                                echo "<option value=\"" . htmlspecialchars($dept['id']) . "\" $selected>" . htmlspecialchars($dept['Name']) . "</option>";
                                                            }
                                                            ?>
                                                        </select>
                                                    </div>
                                                    <small class="text-muted">Optional - select to notify another department</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="form-group-row">
                                                <div class="label-col">
                                                    <label class="form-label">
                                                        <i class="fas fa-crown"></i>
                                                        Attention HOD
                                                    </label>
                                                </div>
                                                <div class="field-col">
                                                    <div class="input-group-custom">
                                                        <i class="fas fa-crown input-icon"></i>
                                                        <select name="AttentionAssigned_Admin" class="form-control-custom select-custom">
                                                            <option value="">Select Department First</option>
                                                        </select>
                                                    </div>
                                                    <small class="text-muted">Required if Attention Department is selected</small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- User Info Display -->
                                    <div id="user_info"></div>
                                    
                                    <!-- Attention User Info Display -->
                                    <div id="attention_user_info"></div>
                                    
                                    <!-- Attachment and Date - Side by side -->
                                    <div class="row mt-2">
                                        <div class="col-md-6">
                                            <div class="form-group-row">
                                                <div class="label-col">
                                                    <label class="form-label">
                                                        <i class="fas fa-paperclip"></i>
                                                        Attachment
                                                    </label>
                                                </div>
                                                <div class="field-col">
                                                    <div class="file-input-wrapper">
                                                        <input type="file" name="file" id="file" accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx,.txt">
                                                    </div>
                                                    <?php if (!empty($currentFileName)): ?>
                                                        <div class="current-file">
                                                            <i class="fas fa-file"></i> Current file: 
                                                            <a href="Uploads/<?php echo htmlspecialchars($currentFileName); ?>" target="_blank">
                                                                <?php echo htmlspecialchars($currentFileName); ?>
                                                            </a>
                                                            <br><small class="text-muted">Upload a new file to replace this one</small>
                                                        </div>
                                                    <?php endif; ?>
                                                    <small class="text-muted">Max 5MB. Allowed: jpg, png, pdf, doc, xls, txt</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="checkbox-group" style="margin-left: 110px;">
                                                <input type="checkbox" id="Send_Email" name="Send_Email" value="yes">
                                                <label for="Send_Email">
                                                    <i class="fas fa-envelope" style="color: var(--primary-green);"></i>
                                                    Notify client via email about this update
                                                </label>
                                            </div>
                                            <small class="text-muted" style="margin-left: 110px; display: block;">
                                                <i class="fas fa-info-circle"></i> 
                                                Email will be sent to: <span id="email_display"><?php echo !empty($email) ? htmlspecialchars($email) : 'the email address provided above'; ?></span>
                                            </small>
                                        </div>
                                    </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-save"></i>
                            Update Case
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
// Update email display when email field changes
$(document).ready(function() {
    $('#email').on('input', function() {
        var email = $(this).val();
        if (email && email.trim() !== '') {
            $('#email_display').text(email);
        } else {
            $('#email_display').text('the email address provided above');
        }
    });
});
</script>

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