Mini Shell

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

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

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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
 
    // Check if connection is established
    if (!isset($conn) || $conn->connect_error) {
        $_SESSION['failure'] = "Database connection failed!";
        header('location: add_complaint.php');
        exit();
    }
    
    // Sanitize input data using mysqli
    $Name = $conn->real_escape_string(trim($_POST["Name"]));
    $Property_Number = $conn->real_escape_string(trim($_POST["Property_Number"]));
    $phone = $conn->real_escape_string(trim($_POST['phone']));	
    $Status = $conn->real_escape_string(trim($_POST['Status']));
    $email = $conn->real_escape_string(trim($_POST['email']));
    $address = $conn->real_escape_string(trim($_POST['address']));
    $problem = $conn->real_escape_string(trim($_POST['problem']));
    $Department = $conn->real_escape_string(trim($_POST['Department']));  
    $Date_Reported = $conn->real_escape_string(trim($_POST['Date_Reported'])); 
    $Assigned_Admin = $conn->real_escape_string(trim($_POST['Assigned_Admin']));
    $Heading = $conn->real_escape_string(trim($_POST['Heading']));
    $Send_Email = isset($_POST['Send_Email']) ? 'yes' : 'no';

    // Validate required fields
    if (empty($Name)) $errors[] = "Customer name is required";
    if (empty($Department)) $errors[] = "Department is required";
    if (empty($Assigned_Admin)) $errors[] = "Assigned admin is required";
    if (empty($problem)) $errors[] = "Problem description is required";
    if (empty($Date_Reported)) $errors[] = "Date reported is required";
    
    if (empty($errors)) {
        
        // Get admin details using mysqli
        $admin_query = $conn->query("SELECT Full_Name, UserDepartment, admin_type FROM admin_accounts WHERE id = '$Assigned_Admin'");
        
        if ($admin_query && $admin_query->num_rows > 0) {
            $admin_data = $admin_query->fetch_assoc();
            $Admin_Name = $admin_data['Full_Name'];
            $Admin_Department = $admin_data['UserDepartment'];
            $Admin_Type = $admin_data['admin_type'];

            // Verify department match
            if ($Admin_Department != $Department) {
                $_SESSION['failure'] = "Selected Person does not belong to the chosen department!";
                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 = '';
            
            // Check if file was uploaded and no error
            if(isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
                $name = $_FILES['file']['name'];
                $size = $_FILES['file']['size'];
                $temp = $_FILES['file']['tmp_name'];
                
                // Validate file size (max 5MB)
                $max_size = 5 * 1024 * 1024; // 5MB in bytes
                if ($size > $max_size) {
                    $_SESSION['failure'] = "File size too large. Maximum size is 5MB.";
                    header('location: 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 = $conn->query($check_query);
                
                if($check_result && $check_result->num_rows > 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 = $conn->query($chk2_query);
                        
                        if($chk2_result && $chk2_result->num_rows == 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();
                }
            } else {
                // No file uploaded or error in upload
                $file_name = "";
            }
            
            // Insert into complaints table using mysqli
            $query = "INSERT INTO complaints (Heading, Name, Property_Number, phone, email, Problem, Department, Assigned_To, Status, Date_Reported, File_Name) 
                      VALUES ('$Heading', '$Name', '$Property_Number', '$phone', '$email', '$problem', '$Department', '$Assigned_Admin', 'NEW', '$Date_Reported', '$file_name')";
            
            $complaint_sql = $conn->query($query);
 
            if ($complaint_sql) {
                $complaint_id = $conn->insert_id;
                
                $_SESSION['success'] = "Case #$complaint_id added successfully and assigned to $Admin_Name ($Admin_Type) from $Department department!";
                
                // Store assignment info
                $_SESSION['last_assignment'] = array(
                    'complaint_id' => $complaint_id,
                    'admin_id' => $Assigned_Admin,
                    'admin_name' => $Admin_Name,
                    'department' => $Department,
                    'date' => $Date_Reported
                );
                
                header('location: Complaints.php');
                exit();
            } else {
                $_SESSION['failure'] = "Error saving complaint: " . $conn->error;
                header('location: add_complaint.php');
                exit();
            }
        } else {
            $_SESSION['failure'] = "Invalid admin 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;

// Include header
include_once 'includes/header.php'; 
?>
<!-- Add jQuery if not already included -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>

<!-- Add Bootstrap Select if needed -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js"></script>

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

<style>
    /* COMPACT FORM STYLES */
    :root {
        --primary-green: #2ecc71;
        --dark-green: #27ae60;
        --light-green: #d4edda;
        --soft-white: #f8f9fa;
        --pure-white: #ffffff;
        --light-gray: #e9ecef;
        --medium-gray: #ced4da;
        --dark-gray: #495057;
        --charcoal: #343a40;
        --black: #212529;
        --shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    .alert-custom-danger {
        background: #f8d7da;
        color: #721c24;
        border-left: 4px solid #dc3545;
    }

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

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

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

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

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

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

    /* New styles for inline labels and fields */
    .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;
    }
    
    .form-group-row .form-label.required-field:after {
        content: " *";
        color: #dc3545;
        font-weight: bold;
    }
    
    .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 Styles - Compact */
    .select-custom {
        width: 100%;
        padding: 8px 10px 8px 32px;
        font-size: 13px;
        color: var(--black);
        background: var(--pure-white);
        border: 1px solid var(--light-gray);
        border-radius: 6px;
        appearance: none;
        background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
        background-repeat: no-repeat;
        background-position: right 10px center;
        background-size: 14px;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /* Checkbox Styling - Compact */
    .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 display - Compact */
    .file-info {
        margin-top: 5px;
        padding: 6px;
        background: var(--light-green);
        border-radius: 4px;
        font-size: 11px;
        color: var(--dark-green);
        display: none;
    }

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

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

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

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

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

        .form-col {
            width: 100%;
        }

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

        .btn-submit, .btn-cancel {
            width: 100%;
            justify-content: center;
        }
        
        .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
    });
    
    // Display file info when file is selected
    $('#file').on('change', function() {
        if (this.files.length > 0) {
            var fileName = $(this).val().split('\\').pop();
            var fileSize = this.files[0].size / 1024 / 1024; // in MB
            
            var fileInfo = '<i class="fas fa-check-circle"></i> Selected: ' + fileName + 
                          ' (' + fileSize.toFixed(2) + ' MB)';
            
            if ($('#file-info').length === 0) {
                $(this).parent().after('<div id="file-info" class="file-info show">' + fileInfo + '</div>');
            } else {
                $('#file-info').html(fileInfo).addClass('show');
            }
        }
    });
    
    // When department selection changes
    $('select[name="Department"]').change(function() {
        var selectedDepartment = $(this).val();
        var $adminSelect = $('select[name="Assigned_Admin"]');
        var $adminInfo = $('#admin_info');
        
        // Clear and disable the admin dropdown if no department selected
        if (!selectedDepartment || selectedDepartment === '') {
            $adminSelect.html('<option value="">Select Department First</option>');
            $adminSelect.prop('disabled', true);
            $adminSelect.selectpicker('refresh');
            $adminInfo.hide().html('');
            return;
        }
        
        // Show loading state
        $adminSelect.html('<option value="">Loading admins...</option>');
        $adminSelect.prop('disabled', true);
        $adminSelect.selectpicker('refresh');
        
        $adminInfo.show().html(`
            <div class="admin-info-card">
                <div class="admin-info-icon">
                    <i class="fas fa-spinner fa-spin"></i>
                </div>
                <div class="admin-info-content">
                    <div class="admin-info-title">Checking Department</div>
                    <div class="admin-info-text">Loading available admins for <strong>${selectedDepartment}</strong> department...</div>
                </div>
            </div>
        `);
        
        // Log the department being requested
        console.log('Requesting admins for department:', selectedDepartment);
        
        // Make AJAX call to fetch admins from the selected department
        $.ajax({
            url: 'get_admins_by_department.php',
            type: 'POST',
            data: { department: selectedDepartment },
            dataType: 'json',
            timeout: 10000,
            beforeSend: function() {
                console.log('Sending AJAX request to get_admins_by_department.php');
            },
            success: function(response) {
                console.log('✅ AJAX Success - Full response:', response);
                
                // Clear current options
                $adminSelect.html('');
                
                // Check if response has debug info
                if (response.debug) {
                    console.log('📋 Debug info from server:', response.debug);
                }
                
                // Check if response has error or not successful
                if (!response.success) {
                    var errorMsg = response.message || 'Unknown error';
                    console.error('❌ Server returned error:', errorMsg);
                    
                    $adminSelect.html('<option value="">Error: ' + errorMsg + '</option>');
                    $adminSelect.prop('disabled', true);
                    $adminSelect.selectpicker('refresh');
                    
                    // Build debug info HTML
                    var debugHtml = '';
                    if (response.debug) {
                        debugHtml = '<br><small>Debug: ' + JSON.stringify(response.debug) + '</small>';
                    }
                    
                    $adminInfo.html(`
                        <div class="admin-info-card" style="border-left-color: #dc3545;">
                            <div class="admin-info-icon" style="color: #dc3545;">
                                <i class="fas fa-exclamation-triangle"></i>
                            </div>
                            <div class="admin-info-content">
                                <div class="admin-info-title" style="color: #dc3545;">Error</div>
                                <div class="admin-info-text">
                                    <strong>${errorMsg}</strong>
                                    ${debugHtml}
                                </div>
                            </div>
                        </div>
                    `);
                    return;
                }
                
                // Check if we have admins
                var admins = response.admins || [];
                console.log('👥 Admins found:', admins.length, admins);
                
                if (admins && admins.length > 0) {
                    // ADMINS FOUND
                    $adminSelect.append('<option value="">-- Select Admin --</option>');
                    
                    // Separate super admins and regular admins
                    var superAdmins = admins.filter(function(admin) {
                        return admin.admin_type === 'super';
                    });
                    
                    var regularAdmins = admins.filter(function(admin) {
                        return admin.admin_type !== 'super';
                    });
                    
                    console.log('👑 Super admins:', superAdmins.length, '👔 Regular admins:', regularAdmins.length);
                    
                    // Add Super Admins first if any
                    if (superAdmins.length > 0) {
                        var optgroupSuper = '<optgroup label="Super Administrators">';
                        $.each(superAdmins, function(index, admin) {
                            optgroupSuper += '<option value="' + admin.id + '">' + 
                                           admin.full_name + ' (Super)</option>';
                        });
                        optgroupSuper += '</optgroup>';
                        $adminSelect.append(optgroupSuper);
                    }
                    
                    // Add Regular Admins
                    if (regularAdmins.length > 0) {
                        var optgroupRegular = '<optgroup label="Administrators">';
                        $.each(regularAdmins, function(index, admin) {
                            optgroupRegular += '<option value="' + admin.id + '">' + 
                                             admin.full_name + '</option>';
                        });
                        optgroupRegular += '</optgroup>';
                        $adminSelect.append(optgroupRegular);
                    }
                    
                    // Enable the dropdown
                    $adminSelect.prop('disabled', false);
                    
                    // Show success message
                    $adminInfo.html(`
                        <div class="admin-info-card" style="border-left-color: var(--primary-green);">
                            <div class="admin-info-icon" style="color: var(--primary-green);">
                                <i class="fas fa-check-circle"></i>
                            </div>
                            <div class="admin-info-content">
                                <div class="admin-info-title">Admins Available</div>
                                <div class="admin-info-text">
                                    <strong>${admins.length} admin(s) found</strong> in ${selectedDepartment} department
                                    <br>
                                    <span class="admin-badge badge-super">${superAdmins.length} Super</span>
                                    <span class="admin-badge badge-regular">${regularAdmins.length} Regular</span>
                                </div>
                            </div>
                        </div>
                    `);
                    
                } else {
                    // NO ADMINS FOUND
                    console.log('⚠️ No admins found for department:', selectedDepartment);
                    
                    $adminSelect.html('<option value="">⛔ No admins available in ' + selectedDepartment + '</option>');
                    $adminSelect.prop('disabled', true);
                    
                    // Show warning message with debug info if available
                    var debugInfo = '';
                    if (response.debug) {
                        debugInfo = '<br><small>Debug: Total in dept: ' + (response.debug.total_admins_in_dept || 'unknown') + 
                                   ', Active: ' + (response.debug.active_admins_in_dept || 'unknown') + '</small>';
                    }
                    
                    $adminInfo.html(`
                        <div class="admin-info-card" style="border-left-color: #dc3545;">
                            <div class="admin-info-icon" style="color: #dc3545;">
                                <i class="fas fa-exclamation-triangle"></i>
                            </div>
                            <div class="admin-info-content">
                                <div class="admin-info-title" style="color: #dc3545;">No Admins Available</div>
                                <div class="admin-info-text">
                                    <strong>No active admin users found</strong> for ${selectedDepartment} department.
                                    ${debugInfo}
                                    <br>
                                    <small>Make sure admins have Status='Active' and UserDepartment='${selectedDepartment}'</small>
                                </div>
                            </div>
                        </div>
                    `);
                }
                
                // Refresh the selectpicker
                $adminSelect.selectpicker('refresh');
            },
            error: function(xhr, status, error) {
                console.error('❌ AJAX Error - Full details:', {
                    status: status,
                    error: error,
                    responseText: xhr.responseText,
                    statusCode: xhr.status,
                    readyState: xhr.readyState
                });
                
                // Try to parse response if it's JSON
                var errorMsg = 'Error loading admins.';
                var responseText = xhr.responseText;
                var debugInfo = '';
                
                if (responseText) {
                    try {
                        var jsonResponse = JSON.parse(responseText);
                        if (jsonResponse.message) {
                            errorMsg = jsonResponse.message;
                        }
                        if (jsonResponse.debug) {
                            debugInfo = '<br><small>Debug: ' + JSON.stringify(jsonResponse.debug) + '</small>';
                            console.log('📋 Debug info from error:', jsonResponse.debug);
                        }
                        console.log('Parsed error response:', jsonResponse);
                    } catch(e) {
                        // Not JSON, show raw response if available
                        if (responseText.length > 0) {
                            errorMsg = 'Server returned: ' + responseText.substring(0, 200);
                            console.log('Raw response text:', responseText);
                        }
                    }
                }
                
                $adminSelect.html('<option value="">Error loading admins</option>');
                $adminSelect.prop('disabled', true);
                $adminSelect.selectpicker('refresh');
                
                var errorHtml = status === 'timeout' ? 'Request timed out.' : errorMsg;
                
                $adminInfo.html(`
                    <div class="admin-info-card" style="border-left-color: #dc3545;">
                        <div class="admin-info-icon" style="color: #dc3545;">
                            <i class="fas fa-times-circle"></i>
                        </div>
                        <div class="admin-info-content">
                            <div class="admin-info-title" style="color: #dc3545;">Error</div>
                            <div class="admin-info-text">
                                <strong>${errorHtml}</strong>
                                ${debugInfo}
                                <br>
                                Please check browser console (F12) for more details.
                            </div>
                        </div>
                    </div>
                `);
            },
            complete: function() {
                console.log('🏁 AJAX request completed');
            }
        });
    });
    
    // When admin is selected
    $('select[name="Assigned_Admin"]').on('changed.bs.select', function() {
        var selectedAdminId = $(this).val();
        var selectedAdminText = $(this).find('option:selected').text();
        
        if (selectedAdminId && selectedAdminId !== '' && selectedAdminText !== '-- Select Admin --') {
            console.log('Admin selected:', selectedAdminId, selectedAdminText);
            $('#admin_info').html(`
                <div class="admin-info-card" style="border-left-color: var(--primary-green);">
                    <div class="admin-info-icon" style="color: var(--primary-green);">
                        <i class="fas fa-user-check"></i>
                    </div>
                    <div class="admin-info-content">
                        <div class="admin-info-title">Admin Selected</div>
                        <div class="admin-info-text">
                            <strong>${selectedAdminText}</strong> assigned
                        </div>
                    </div>
                </div>
            `);
        }
    });
    
    // Initialize - disable admin dropdown on page load
    $('select[name="Assigned_Admin"]').prop('disabled', true);
    $('select[name="Assigned_Admin"]').selectpicker('refresh');
    
    // If department was previously selected (e.g., after form validation error), load admins
    var selectedDept = $('select[name="Department"]').val();
    if (selectedDept && selectedDept !== '') {
        console.log('Loading admins for pre-selected department:', selectedDept);
        $('select[name="Department"]').trigger('change');
    }
    
    // Form validation
    $("#contact_form").validate({
        rules: {
            Heading: {
                required: true,
                minlength: 3,
                maxlength: 200
            },
            Name: {
                required: true,
                minlength: 3,
                maxlength: 100
            },
            phone: {
                required: true,
                minlength: 10,
                maxlength: 15,
                digits: true
            },
            email: {
                email: true,
                maxlength: 100
            },
            Department: {
                required: true
            },
            Assigned_Admin: {
                required: true
            },
            Date_Reported: {
                required: true,
                date: true
            },
            problem: {
                required: true,
                minlength: 10,
                maxlength: 1000
            },
            address: {
                maxlength: 200
            },
            Property_Number: {
                maxlength: 50
            }
        },
        messages: {
            Heading: {
                required: "Required",
                minlength: "Min 3 chars"
            },
            Name: {
                required: "Required",
                minlength: "Min 3 chars"
            },
            phone: {
                required: "Required",
                minlength: "Min 10 digits",
                digits: "Digits only"
            },
            email: {
                email: "Invalid email"
            },
            Department: {
                required: "Select department"
            },
            Assigned_Admin: {
                required: "Select admin"
            },
            Date_Reported: {
                required: "Select date"
            },
            problem: {
                required: "Required",
                minlength: "Min 10 chars"
            }
        },
        errorElement: "span",
        errorClass: "help-block",
        highlight: function(element) {
            $(element).closest('.form-group-row').addClass('has-error');
        },
        unhighlight: function(element) {
            $(element).closest('.form-group-row').removeClass('has-error');
        },
        errorPlacement: function(error, element) {
            if (element.hasClass('selectpicker')) {
                error.insertAfter(element.next('.dropdown-toggle'));
            } else {
                error.insertAfter(element);
            }
        },
        submitHandler: function(form) {
            // Additional validation before submit
            var dept = $('select[name="Department"]').val();
            var admin = $('select[name="Assigned_Admin"]').val();
            
            if (!dept || dept === '') {
                alert('Please select a department');
                return false;
            }
            
            // Check if admin dropdown is disabled (no admins available)
            if ($('select[name="Assigned_Admin"]').prop('disabled')) {
                alert('No admin available for selected department');
                return false;
            }
            
            if (!admin || admin === '') {
                alert('Please select an admin');
                return false;
            }
            
            // Disable submit button to prevent double submission
            $('.btn-submit').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Saving...');
            
            console.log('Form submitted with:', {department: dept, admin: admin});
            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="add_complaint.php" class="btn-custom btn-custom-success">
                    <i class="fas fa-sync-alt"></i>
                    Refresh
                </a>
            </div>
        </div>
        
        <!-- Alert Messages -->
        <?php if(isset($_SESSION['success'])): ?>
            <div class="alert-custom alert-custom-success">
                <i class="fas fa-check-circle"></i>
                <div><?php echo $_SESSION['success']; unset($_SESSION['success']); ?></div>
            </div>
        <?php endif; ?>
        
        <?php if(isset($_SESSION['failure'])): ?>
            <div class="alert-custom alert-custom-danger">
                <i class="fas fa-exclamation-circle"></i>
                <div><?php echo $_SESSION['failure']; unset($_SESSION['failure']); ?></div>
            </div>
        <?php endif; ?>
        
        <!-- Main Form Card -->
        <div class="form-card">
            <div class="form-card-header">
                <i class="fas fa-file-alt"></i>
                <h3>New Case 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>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 isset($_POST['Heading']) ? htmlspecialchars($_POST['Heading']) : ''; ?>">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Customer Name -->
                                    <div class="form-group-row">
                                        <div class="label-col">
                                            <label class="form-label required-field">
                                                <i class="fas fa-user"></i>
                                                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" 
                                                       class="form-control-custom" autocomplete="off" id="Name" 
                                                       value="<?php echo isset($_POST['Name']) ? htmlspecialchars($_POST['Name']) : ''; ?>">
                                            </div>
                                        </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 -->
                                    <div class="form-group-row">
                                        <div class="label-col">
                                            <label class="form-label required-field">
                                                <i class="fas fa-phone"></i>
                                                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" 
                                                       class="form-control-custom" autocomplete="off" id="phone" 
                                                       value="<?php echo isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : ''; ?>">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Email -->
                                    <div class="form-group-row">
                                        <div class="label-col">
                                            <label class="form-label">
                                                <i class="fas fa-envelope"></i>
                                                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" 
                                                       class="form-control-custom" id="email" 
                                                       value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Address -->
                                    <div class="form-group-row">
                                        <div class="label-col">
                                            <label class="form-label">
                                                <i class="fas fa-map-marker-alt"></i>
                                                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" 
                                                          class="form-control-custom" id="address" rows="2"><?php echo isset($_POST['address']) ? htmlspecialchars($_POST['address']) : ''; ?></textarea>
                                            </div>
                                        </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>Problem Description</h4>
                                </div>
                                <div class="section-body">
                                    <div class="form-group-row">
                                        <div class="field-col">
                                            <div class="input-group-custom">
                                                <i class="fas fa-exclamation-triangle input-icon"></i>
                                                <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>
                                                        Department
                                                    </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>
                                                            <option value="SYSTEM ADMIN" <?php echo (isset($_POST['Department']) && $_POST['Department'] == 'SYSTEM ADMIN') ? 'selected' : ''; ?>>SYSTEM ADMIN</option>
                                                            <option value="PROCUREMENT" <?php echo (isset($_POST['Department']) && $_POST['Department'] == 'PROCUREMENT') ? 'selected' : ''; ?>>PROCUREMENT</option>
                                                            <option value="ESTATES" <?php echo (isset($_POST['Department']) && $_POST['Department'] == 'ESTATES') ? 'selected' : ''; ?>>ESTATES</option>
                                                            <option value="ADMIN" <?php echo (isset($_POST['Department']) && $_POST['Department'] == 'ADMIN') ? 'selected' : ''; ?>>ADMIN</option>
                                                            <option value="ADMINISTRATION" <?php echo (isset($_POST['Department']) && $_POST['Department'] == 'ADMINISTRATION') ? 'selected' : ''; ?>>ADMINISTRATION</option>
                                                            <option value="MAINTENANCE" <?php echo (isset($_POST['Department']) && $_POST['Department'] == 'MAINTENANCE') ? 'selected' : ''; ?>>MAINTENANCE</option>
                                                            <option value="ACCOUNTS" <?php echo (isset($_POST['Department']) && $_POST['Department'] == 'ACCOUNTS') ? 'selected' : ''; ?>>ACCOUNTS</option>
                                                            <option value="SURVEY" <?php echo (isset($_POST['Department']) && $_POST['Department'] == 'SURVEY') ? 'selected' : ''; ?>>SURVEY</option>
                                                            <option value="SECURITY" <?php echo (isset($_POST['Department']) && $_POST['Department'] == 'SECURITY') ? 'selected' : ''; ?>>SECURITY</option>
                                                            <option value="STORES" <?php echo (isset($_POST['Department']) && $_POST['Department'] == 'STORES') ? 'selected' : ''; ?>>STORES</option>
                                                            <option value="ICT" <?php echo (isset($_POST['Department']) && $_POST['Department'] == 'ICT') ? 'selected' : ''; ?>>ICT</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-user-tie"></i>
                                                        Assign To
                                                    </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>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Admin Info Display -->
                                    <div id="admin_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</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-calendar-alt"></i>
                                                        Date
                                                    </label>
                                                </div>
                                                <div class="field-col">
                                                    <div class="input-group-custom">
                                                        <i class="fas fa-calendar-alt input-icon"></i>
                                                        <input name="Date_Reported" class="form-control-custom" 
                                                               type="date" required
                                                               value="<?php echo isset($_POST['Date_Reported']) ? $_POST['Date_Reported'] : date('Y-m-d'); ?>">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Notify Client Checkbox -->
                                    <div class="row mt-2">
                                        <div class="col-12">
                                            <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"></i>
                                                    Alert the client via email that their case has been received and is being handled
                                                </label>
                                            </div>
                                        </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>

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