Mini Shell

Direktori : /home/mhcadmin/www/Portal/
Upload File :
Current File : /home/mhcadmin/www/Portal/add_complaint.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;

// Initialize variables
$Name = $Property_Number = $phone = $Status = $email = $address = $problem = $Department 
= $Date_Reported = $Assigned_Admin = $Heading = $AttentionDepartment = $AttentionAssigned_Admin = "";
$errors = array();

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

// Get current user's department ID and name
$currentUserDeptId = '';
$currentUserDeptName = '';

$user_query = mysqli_query($conn, "SELECT UserDepartment FROM admin_accounts WHERE id = '$currentUserId' AND Status = 'Active'");
if ($user_query && mysqli_num_rows($user_query) > 0) {
    $user_data = mysqli_fetch_assoc($user_query);
    $currentUserDeptId = $user_data['UserDepartment'];
    
    // Get department name from Department table
    $dept_query = mysqli_query($conn, "SELECT Name FROM Department WHERE id = '$currentUserDeptId' AND Deleted = 'No'");
    if ($dept_query && mysqli_num_rows($dept_query) > 0) {
        $dept_data = mysqli_fetch_assoc($dept_query);
        $currentUserDeptName = $dept_data['Name'];
    }
}

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

    // Sanitize input data (fields can now be empty)
    $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']));  
    $Date_Reported = $MesaageTime; 
    $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';
    
    // NEW: Sanitize attention department and attention assigned admin
    $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 (Name, phone, address are no longer required)
    if (empty($Department)) $errors[] = "Department is required";
    if (empty($Assigned_Admin)) $errors[] = "Assigned HOD is required";
    if (empty($problem)) $errors[] = "Problem description is required";
    if (empty($Date_Reported)) $errors[] = "Date reported is required";
    
    // NEW: Validate that AttentionAssigned_Admin is required if AttentionDepartment is selected
    if (!empty($AttentionDepartment) && empty($AttentionAssigned_Admin)) {
        $errors[] = "Attention Assigned Admin is required when Attention Department is selected";
    }
    
    // Validate email if Send_Email is checked (email is only required if sending email)
    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";
        }
    }
    
    // NEW: Validate AttentionAssigned_Admin belongs to AttentionDepartment if both are provided
    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'];
            $Attention_User_Position = !empty($attention_user_data['Position']) ? $attention_user_data['Position'] : 'Head of Department';
            
            // 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: add_complaint.php');
                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: add_complaint.php');
                exit();
            }
            
            date_default_timezone_set('Africa/Blantyre');
            $MessageTime = date('d-m-Y H:i', time());

            // File Upload Handling
            $file_name = '';
            
            if(isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
                $name = $_FILES['file']['name'];
                $size = $_FILES['file']['size'];
                $type = $_FILES['file']['type'];
                $temp = $_FILES['file']['tmp_name'];
                
                // Validate file size (max 5MB)
                $max_size = 5 * 1024 * 1024; // 5MB in bytes
                if ($size > $max_size) {
                    $_SESSION['failure'] = "File size too large. Maximum size is 5MB.";
                    header('location: add_complaint.php');
                    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: add_complaint.php');
                    exit();
                }
                
                // Create unique filename with timestamp
                $fname = date("YmdHis") . '_' . preg_replace("/[^a-zA-Z0-9.]/", "_", $name);
                
                // Check if file with same name exists
                $check_query = "SELECT * FROM complaints WHERE File_Name = '$fname'";
                $check_result = mysqli_query($conn, $check_query);
                
                if($check_result && mysqli_num_rows($check_result) > 0) {
                    $i = 1;
                    $c = 0;
                    while($c == 0) {
                        $i++;
                        $pathinfo = pathinfo($name);
                        $filename = $pathinfo['filename'];
                        $extension = isset($pathinfo['extension']) ? $pathinfo['extension'] : '';
                        
                        $tname = $filename . "_" . $i . "." . $extension;
                        $fname = date("YmdHis") . '_' . preg_replace("/[^a-zA-Z0-9.]/", "_", $tname);
                        
                        $chk2_query = "SELECT * FROM complaints WHERE File_Name = '$fname'";
                        $chk2_result = mysqli_query($conn, $chk2_query);
                        
                        if($chk2_result && mysqli_num_rows($chk2_result) == 0) {
                            $c = 1;
                        }
                    }
                }
                
                // 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: add_complaint.php');
                    exit();
                }
            }  
            
            if (!isset($_FILES['file'])) {
                $file_name = "";
            }
            
            // MODIFIED: Insert into complaints table with new attention fields
            $query = "INSERT INTO complaints (Heading, Name, Property_Number, phone, email, Problem, Department, Assigned_To, Status, Date_Reported, File_Name, Originated_From, Attentioned_Dept, Atentioned_User) 
                      VALUES ('$Heading', '$Name', '$Property_Number', '$phone', '$email', '$problem', '$Department', '$Assigned_Admin', 'NEW', '$Date_Reported', '$file_name', '$currentUserId', '$AttentionDepartment', '$AttentionAssigned_Admin')";
            
            $complaint_sql = mysqli_query($conn, $query);
 
            if ($complaint_sql) {
                $complaint_id = mysqli_insert_id($conn);
                
                // Send email if requested and email is provided
                if ($Send_Email == 'yes' && !empty($email)) {
                    try {
                        // ============= SMTP CONFIGURATION =============
                        $smtp_host = "localhost";       // SMTP server
                        $smtp_port = 25;                 // SMTP port
                        $smtp_username = "";             // Leave empty for localhost
                        $smtp_password = "";             // Leave empty for localhost
                        $smtp_secure = "";               // Empty, "ssl", or "tls"
                        // =============================================
                        
                        // 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 = "File #$complaint_id: We've Received Your Application - 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>APPLICATION RECEIVED</h2>
                                </div>
                                
                                <div class='content'>
                                    <p>Dear " . ($Name ? htmlspecialchars($Name) : 'Valued Customer') . ",</p>
                                    <p>Thank you for contacting MHC. We have received your application and want to assure you that our team is looking into it.</p>
                                    
                                    <div class='field'>
                                        <span class='label'>📋 CASE NUMBER:</span>
                                        <div class='case-number'>#" . htmlspecialchars($complaint_id) . "</div>
                                    </div>
                                    
                                    <div class='field'>
                                        <span class='label'>⏭️ WHAT HAPPENS NEXT:</span>
                                        <ol style='margin-top: 5px;'>
                                            <li>Our team will review your Application thoroughly</li>
                                            <li>You'll receive feedback once we have a resolution</li>
                                            <li>You can track your case status by quoting case number: #" . htmlspecialchars($complaint_id) . "</li>
                                        </ol>
                                    </div>
                                    
                                    <p style='background: #e8f5e9; padding: 10px; border-radius: 4px;'>
                                        <strong>We appreciate your patience while we work on your case.</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 = "COMPLAINT RECEIVED - CASE #$complaint_id\n\n" .
                                        "Dear " . ($Name ? $Name : 'Valued Customer') . ",\n\n" .
                                        "Thank you for contacting MHC IMS. We have received your Application and want to assure you that our team is looking into it.\n\n" .
                                        "═══════════════════════════════\n" .
                                        "CASE NUMBER: #$complaint_id\n" .
                                        "═══════════════════════════════\n\n" .
                                        
                                        "WHAT HAPPENS NEXT:\n" .
                                        "------------------\n" .
                                        "1. Our team will review your complaint thoroughly\n" .
                                        "2. You'll receive feedback once we have a resolution\n" .
                                        "3. You can track your case status by quoting case number: #$complaint_id\n\n" .
                                        "We appreciate your patience while we work on your case.\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 notification email sent for case #$complaint_id to $email");
                        
                    } catch (Exception $e) {
                        // Log email error but don't stop the process
                        error_log("Failed to send case notification email for case #$complaint_id: " . $e->getMessage());
                        $_SESSION['warning'] = "File #$complaint_id saved but email notification could not be sent. Error: " . $e->getMessage();
                    }
                }
                
                // Updated success message
                $_SESSION['success'] = "File Sent successfully!" . 
                                      ($Send_Email == 'yes' && !empty($email) ? " Email notification sent to $email." : "");
                
                // Store assignment info
                $_SESSION['last_assignment'] = array(
                    'complaint_id' => $complaint_id,
                    'hod_id' => $Assigned_Admin,
                    'hod_name' => $User_Name,
                    'hod_position' => $User_Position,
                    'department' => $Department,
                    'date' => $Date_Reported,
                    'originated_by' => $currentUserId,
                    'attention_dept' => $AttentionDepartment,
                    'attention_user' => $AttentionAssigned_Admin
                );
                
                header('location: Complaints.php');
                exit();
            } else {
                $_SESSION['failure'] = "Error saving complaint: " . mysqli_error($conn);
                header('location: add_complaint.php');
                exit();
            }
        } else {
            $_SESSION['failure'] = "Invalid or inactive user selected!";
            header('location: add_complaint.php');
            exit();
        }
        
    } else {
        $_SESSION['failure'] = implode("<br>", $errors);
        header('location: add_complaint.php');
        exit();
    }
}

// We are using same form for adding and editing. This is a create form so declare $edit = false.
$edit = false;

// MODIFIED: Get all departments from Department table with their IDs
$departments_query = "SELECT id, Name FROM Department WHERE Deleted = 'No' ORDER BY Name";
$departments_result = mysqli_query($conn, $departments_query);
$departments = [];
$department_options = [];
if ($departments_result && mysqli_num_rows($departments_result) > 0) {
    while ($row = mysqli_fetch_assoc($departments_result)) {
        $departments[] = $row;
        $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 before */
    :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-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; }
    .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; }
    .row { margin-left: -6px; margin-right: -6px; }
    [class*="col-"] { padding-left: 6px; padding-right: 6px; }
    .required-field::after { content: " *"; color: #dc3545; font-weight: bold; }
    @media (max-width: 768px) { .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; } }
</style>

<script type="text/javascript">
$(document).ready(function() {
    // Initialize Bootstrap Select with smaller size
    $('.selectpicker').selectpicker({
        size: 5,
        dropupAuto: false
    });
    
    // Store the default department ID (from PHP)
    var defaultDeptId = '<?php echo $currentUserDeptId; ?>';
    var defaultDeptName = '<?php echo addslashes($currentUserDeptName); ?>';
    
    console.log('Default Department ID:', defaultDeptId);
    console.log('Default Department Name:', defaultDeptName);
    
    // Function to load users for a department based on mode
    // isRedirectMode: true = only HODs, false = all users
    function loadUsers(departmentId, targetSelect, infoDiv, isRedirectMode = false) {
        var departmentName = $('select[name="' + (targetSelect.attr('name') === 'Assigned_Admin' ? 'Department' : 'AttentionDepartment') + '"] option:selected').text();
        
        // Clear and disable the dropdown
        targetSelect.html('<option value="">Loading...</option>');
        targetSelect.prop('disabled', true);
        targetSelect.selectpicker('refresh');
        
        if (!departmentId || departmentId === '') {
            infoDiv.show().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 Department Selected</div>
                        <div class="user-info-text">Please select a department first</div>
                    </div>
                </div>
            `);
            return;
        }
        
        // Show loading state
        infoDiv.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 ${isRedirectMode ? 'HODs' : 'Users'}</div>
                    <div class="user-info-text">Loading ${isRedirectMode ? 'available HODs' : 'all users'} for <strong>${departmentName}</strong> department...</div>
                </div>
            </div>
        `);
        
        // Determine which endpoint to call based on mode
        var ajaxUrl = isRedirectMode ? 'get_hod_by_department.php' : 'get_all_users_by_department.php';
        
        console.log('Calling: ' + ajaxUrl + ' for department: ' + departmentId + ' (Mode: ' + (isRedirectMode ? 'Redirect - HODs only' : 'Normal - All users') + ')');
        
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: { department: departmentId },
            dataType: 'json',
            timeout: 10000,
            success: function(response) {
                console.log('Response received:', response);
                
                // Clear current options
                targetSelect.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
                        targetSelect.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 + ')';
                            }
                            targetSelect.append('<option value="' + user.id + '">' + displayName + ' <span class="user-badge">HOD</span></option>');
                        });
                        targetSelect.prop('disabled', false);
                        
                        infoDiv.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 (Redirect Mode)</div>
                                    <div class="user-info-text"><strong>${users.length} Head(s) of Department found</strong> in ${departmentName}</div>
                                </div>
                            </div>
                        `);
                    } else {
                        // NORMAL MODE - Show ALL users from the department
                        targetSelect.append('<option value="">-- Select Responsible Person --</option>');
                        $.each(users, function(index, user) {
                            var displayName = user.full_name;
                            if (user.position && user.position.trim() !== '') {
                                displayName += ' (' + user.position + ')';
                            }
                            var hodLabel = user.is_hod == '1' ? ' <span class="user-badge">HOD</span>' : '';
                            targetSelect.append('<option value="' + user.id + '">' + displayName + hodLabel + '</option>');
                        });
                        targetSelect.prop('disabled', false);
                        
                        var hodCount = users.filter(function(user) { return user.is_hod == '1'; }).length;
                        var regularCount = users.length - hodCount;
                        
                        infoDiv.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">All Users Available</div>
                                    <div class="user-info-text"><strong>${users.length} User(s)</strong> in ${departmentName} (${hodCount} HOD, ${regularCount} Staff)</div>
                                </div>
                            </div>
                        `);
                    }
                    targetSelect.selectpicker('refresh');
                } else {
                    // NO USERS FOUND
                    if (isRedirectMode) {
                        targetSelect.html('<option value="">⛔ No HOD available in ' + departmentName + '</option>');
                        infoDiv.html(`
                            <div class="user-info-card" style="border-left-color: #dc3545;">
                                <div class="user-info-icon"><i class="fas fa-exclamation-triangle"></i></div>
                                <div class="user-info-content">
                                    <div class="user-info-title">No HOD Available</div>
                                    <div class="user-info-text">No Head of Department found in ${departmentName} department.</div>
                                </div>
                            </div>
                        `);
                    } else {
                        targetSelect.html('<option value="">⛔ No Users available in ' + departmentName + '</option>');
                        infoDiv.html(`
                            <div class="user-info-card" style="border-left-color: #dc3545;">
                                <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 in ${departmentName} department.</div>
                                </div>
                            </div>
                        `);
                    }
                    targetSelect.prop('disabled', true);
                    targetSelect.selectpicker('refresh');
                }
            },
            error: function(xhr, status, error) {
                console.error('Error fetching users:', error);
                console.error('Status:', status);
                console.error('Response:', xhr.responseText);
                targetSelect.html('<option value="">Error loading users</option>');
                targetSelect.prop('disabled', true);
                targetSelect.selectpicker('refresh');
                infoDiv.html(`
                    <div class="user-info-card" style="border-left-color: #dc3545;">
                        <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 main department selection changes
    $('select[name="Department"]').change(function() {
        var selectedDepartment = $(this).val();
        var $userSelect = $('select[name="Assigned_Admin"]');
        var $userInfo = $('#user_info');
        
        // Determine if this is a redirect (department changed from default)
        var isRedirectMode = (selectedDepartment && defaultDeptId && selectedDepartment !== defaultDeptId);
        
        console.log('Department changed:');
        console.log('- Selected: ' + selectedDepartment);
        console.log('- Default: ' + defaultDeptId);
        console.log('- Is Redirect Mode: ' + isRedirectMode);
        
        if (isRedirectMode) {
            // Show warning that only HODs will be available
            $userInfo.show().html(`
                <div class="user-info-card" style="border-left-color: #ffc107;">
                    <div class="user-info-icon" style="color: #ffc107;">
                        <i class="fas fa-exclamation-triangle"></i>
                    </div>
                    <div class="user-info-content">
                        <div class="user-info-title">Redirect Mode Active</div>
                        <div class="user-info-text">You are redirecting to another department. Only HODs will be available for selection.</div>
                    </div>
                </div>
            `);
        }
        
        // Load users based on mode
        loadUsers(selectedDepartment, $userSelect, $userInfo, isRedirectMode);
    });
    
    // When Attention Department selection changes (always only HODs for attention)
    $('select[name="AttentionDepartment"]').change(function() {
        var selectedAttentionDept = $(this).val();
        var $attentionUserSelect = $('select[name="AttentionAssigned_Admin"]');
        var $attentionInfo = $('#attention_user_info');
        
        // Attention department always uses HODs only (redirect mode)
        loadUsers(selectedAttentionDept, $attentionUserSelect, $attentionInfo, true);
    });
    
    // When HOD/User is selected for main department
    $('select[name="Assigned_Admin"]').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 isRedirectMode = (selectedDept && defaultDeptId && selectedDept !== defaultDeptId);
        
        if (selectedUserId && selectedUserId !== '' && 
            selectedUserText !== '-- Select Responsible Person --' && 
            selectedUserText !== '-- Select HOD --') {
            
            var icon = isRedirectMode ? 'fa-crown' : 'fa-user-check';
            var title = isRedirectMode ? 'HOD Selected (Redirect)' : 'User Selected';
            var badge = isRedirectMode ? '<span class="user-badge">HOD</span>' : '';
            
            $('#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> ${badge} assigned for ${selectedDeptName}</div>
                    </div>
                </div>
            `);
        }
    });
    
    // When Attention HOD is selected
    $('select[name="AttentionAssigned_Admin"]').change(function() {
        var selectedUserId = $(this).val();
        var selectedUserText = $(this).find('option:selected').text();
        var selectedDept = $('select[name="AttentionDepartment"]').val();
        var selectedDeptName = $('select[name="AttentionDepartment"]').find('option:selected').text();
        
        if (selectedUserId && selectedUserId !== '' && selectedUserText !== '-- Select HOD --') {
            $('#attention_user_info').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">Attention HOD Selected</div>
                        <div class="user-info-text"><strong>${selectedUserText}</strong> assigned as attention HOD for ${selectedDeptName} department</div>
                    </div>
                </div>
            `);
        }
    });
    
    // Initialize - Set default department to user's department
    if (defaultDeptId && defaultDeptId !== '') {
        var $deptSelect = $('select[name="Department"]');
        
        // Set the value directly
        $deptSelect.val(defaultDeptId);
        
        // Show info about default department
        $('#user_info').html(`
            <div class="user-info-card">
                <div class="user-info-icon">
                    <i class="fas fa-user-check"></i>
                </div>
                <div class="user-info-content">
                    <div class="user-info-title">Default Department Set</div>
                    <div class="user-info-text">
                        Your department: <strong>${defaultDeptName}</strong>. All users from this department are available for assignment.
                    </div>
                </div>
            </div>
        `);
        
        // Trigger change to load ALL users from default department (NOT redirect mode)
        // isRedirectMode = false because this is the default department
        var $userSelect = $('select[name="Assigned_Admin"]');
        var $userInfo = $('#user_info');
        loadUsers(defaultDeptId, $userSelect, $userInfo, false);
        
    } else {
        // Initialize - disable user dropdowns on page load if no default
        $('select[name="Assigned_Admin"]').prop('disabled', true);
        $('select[name="Assigned_Admin"]').selectpicker('refresh');
        $('select[name="AttentionAssigned_Admin"]').prop('disabled', true);
        $('select[name="AttentionAssigned_Admin"]').selectpicker('refresh');
        
        // Show message if no department found
        $('#user_info').html(`
            <div class="user-info-card" style="border-left-color: #ffc107;">
                <div class="user-info-icon" style="color: #ffc107;">
                    <i class="fas fa-exclamation-triangle"></i>
                </div>
                <div class="user-info-content">
                    <div class="user-info-title">No Department Assigned</div>
                    <div class="user-info-text">
                        You don't have a department assigned. Please select a department first.
                    </div>
                </div>
            </div>
        `);
    }
    
    // If attention department was previously selected (e.g., after form validation error), load attention HODs
    var selectedAttentionDept = $('select[name="AttentionDepartment"]').val();
    if (selectedAttentionDept && selectedAttentionDept !== '') {
        $('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() !== '';
                }
            },
            Date_Reported: {
                required: true,
                date: true
            },
            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 a responsible person"
            },
            AttentionAssigned_Admin: {
                required: "Attention User is required when Attention Department is selected"
            },
            Date_Reported: {
                required: "Select date"
            },
            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) {
            // Additional validation before submit
            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 user available for selected department');
                return false;
            }
            
            if (!user || user === '') {
                alert('Please select a responsible person');
                return false;
            }
            
            $('.btn-submit').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Saving...');
            
            form.submit();
        }
    });
});
</script>

<div id="page-wrapper">
    <div class="form-container">
        <!-- Header Section -->
        <div class="page-header">
            <h1>
                <i class="fas fa-plus-circle"></i>
                Add New Case
            </h1>
            <div class="action-buttons">
                <a href="Complaints.php" class="btn-custom btn-custom-primary">
                    <i class="fas fa-arrow-left"></i>
                    Back
                </a>
                <a href="" 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-file-alt"></i>
                <h3>New File Details</h3>
            </div>
            <div class="form-card-body">
                <form action="" method="post" id="contact_form" enctype="multipart/form-data">    
                    <!-- Hidden Status Field -->
                    <input type="hidden" name="Status" value="NEW">
                    
                    <!-- 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>File 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 isset($_POST['Heading']) ? htmlspecialchars($_POST['Heading']) : ''; ?>">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Customer Name - OPTIONAL -->
                                    <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 isset($_POST['Name']) ? htmlspecialchars($_POST['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 isset($_POST['Property_Number']) ? htmlspecialchars($_POST['Property_Number']) : ''; ?>">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Phone - OPTIONAL -->
                                    <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 isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : ''; ?>">
                                            </div>
                                            <small class="text-muted">Optional</small>
                                        </div>
                                    </div>
                                    
                                    <!-- Email - OPTIONAL -->
                                    <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 isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>">
                                            </div>
                                            <small class="text-muted">Optional unless sending notification</small>
                                        </div>
                                    </div>
                                    
                                    <!-- Address - OPTIONAL -->
                                    <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 isset($_POST['address']) ? htmlspecialchars($_POST['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 isset($_POST['problem']) ? htmlspecialchars($_POST['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">
                                    <!-- 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 = (isset($_POST['Department']) && $_POST['Department'] == $dept['id']) ? 'selected' : '';
                                                                echo "<option value=\"" . htmlspecialchars($dept['id']) . "\" $selected>" . htmlspecialchars($dept['Name']) . "</option>";
                                                            }
                                                            ?>
                                                        </select>
                                                    </div>
                                                    <small class="text-muted">Default is your department. Changing this will redirect to another department (HODs only)</small>
                                                </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-user-tie"></i>
                                                        Name & Title
                                                    </label>
                                                </div>
                                                <div class="field-col">
                                                    <div class="input-group-custom">
                                                        <i class="fas fa-user-tie input-icon"></i>
                                                        <select name="Assigned_Admin" class="form-control-custom select-custom" required>
                                                            <option value="">Select Department First</option>
                                                        </select>
                                                    </div>
                                                    <small class="text-muted">For your department: all staff available. For other departments: HODs only</small>
                                                </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 = (isset($_POST['AttentionDepartment']) && $_POST['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 (HODs only)</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 (HODs only)</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>
                                                    <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" 
                                                       <?php echo (isset($_POST['Send_Email']) && $_POST['Send_Email'] == 'yes') ? 'checked' : ''; ?>>
                                                <label for="Send_Email">
                                                    <i class="fas fa-envelope" style="color: var(--primary-green);"></i>
                                                    Alert the client via email to acknowledge receipt of their file 
                                                </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 isset($_POST['email']) && !empty($_POST['email']) ? htmlspecialchars($_POST['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>
                            Save 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'; 
?>