<?php
include('usersession.php');
include_once('complaint_hierarchy.php');

if(isset($_SESSION['ecimsuser']) && !empty($_SESSION['ecimsuser'])) {

$sqlu = "SELECT * FROM users WHERE uid = '".$_SESSION['ecimsuser']."'";
$queryu = $conn->query($sqlu);
$ecimsuser = $queryu->fetch_assoc();

/* Auto building from user login */
$userBuilding = '';
if(isset($ecimsuser['b_list']) && $ecimsuser['b_list'] != '') {
    $userBuilding = $ecimsuser['b_list'];
} elseif(isset($ecimsuser['bid']) && $ecimsuser['bid'] != '') {
    $userBuilding = $ecimsuser['bid'];
} elseif(isset($ecimsuser['building_id']) && $ecimsuser['building_id'] != '') {
    $userBuilding = $ecimsuser['building_id'];
}

function complaint_register_category_image($name)
{
    $name = strtolower($name);

    if(strpos($name, 'plumbing') !== false) {
        return 'assets/images/lodge-plumbing-complaints.jpeg';
    }

    if(strpos($name, 'carpenter') !== false || strpos($name, 'carpentry') !== false || strpos($name, 'carpentering') !== false) {
        return 'assets/images/lodge-carpentry-complaints.jpeg';
    }

    if(strpos($name, 'misc') !== false) {
        return 'assets/images/lodge-misc-complaints.svg';
    }

    return '';
}

/* AJAX: hierarchy node selected */
if(isset($_POST['action']) && $_POST['action'] == 'get_node_data') {

    $node_id = (int)$_POST['node_id'];
    $level = (int)($_POST['level'] ?? 2);
    $nodeHtml = '';
    $compHtml = '';

    $children = complaint_child_nodes($conn, $node_id);

    if($children && $children->num_rows > 0) {
        while($row = $children->fetch_assoc()) {
            // Category artwork belongs only to step 2, never to location/item nodes.
            $image = ($level === 2) ? complaint_register_category_image($row['name']) : '';
            $imageHtml = $image ? '<img src="'.$image.'" alt="'.complaint_html($row['name']).'">' : '';
            $nodeHtml .= '
            <label class="select-card '.($image ? 'has-image' : '').'">
                <input type="radio" name="node_level_'.$level.'" class="node_radio" value="'.$row['id'].'" data-level="'.$level.'" required>
                <span>'.($image ? $imageHtml : '<strong>'.complaint_html($row['name']).'</strong>').'</span>
            </label>';
        }
        $compHtml = '<div class="empty-box">Please select the next option.</div>';
    } else {
        $complaints = $conn->query("SELECT cid, details FROM complaint_list WHERE node_id='$node_id' ORDER BY code ASC, details ASC");
        if($complaints && $complaints->num_rows > 0) {
            while($row = $complaints->fetch_assoc()) {
                $compHtml .= '
                <label class="select-card complaint-card">
                    <input type="radio" name="c_list" class="complaint_radio" value="'.$row['cid'].'">
                    <span>'.complaint_html($row['details']).'</span>
                </label>';
            }
        } else {
            $compHtml = '<div class="empty-box">No complaint found under this option.</div>';
        }
    }

    echo json_encode([
        'nodes' => $nodeHtml,
        'complaints' => $compHtml,
        'has_children' => ($children && $children->num_rows > 0)
    ]);
    exit;
}

$err = '';
$msg = '';

if(isset($_POST['submit'])) {

    $date = date("d/m/Y");
    $d = date("dmy");
    $time = date("g:i a");
    $curtime = date("H:i");

    $uid = mysqli_real_escape_string($conn, $ecimsuser['uid']);
    $b_list = $_SESSION['building_id'];
    $c_list = (int)($_POST['c_list'] ?? 0);
    $selected_node_id = (int)($_POST['selected_node_id'] ?? 0);
    $custom_complaint = trim($_POST['custom_complaint'] ?? '');

    if($b_list == '') {
        $err = "Building/address not found in user login data.";
    } elseif($c_list <= 0 && $custom_complaint === '') {
        $err = "Please select a complaint or type your complaint.";
    } else {
        if($c_list <= 0 && $custom_complaint !== '') {
            $path = complaint_node_path($conn, $selected_node_id);
            if($path === '') {
                $err = "Please select the complete complaint category first.";
            } else {
                $customEscaped = mysqli_real_escape_string($conn, $custom_complaint);
                $existingCustom = $conn->query("
                    SELECT cid
                    FROM complaint_list
                    WHERE node_id='".$selected_node_id."'
                      AND LOWER(TRIM(details))=LOWER('".$customEscaped."')
                    LIMIT 1
                ");

                if($existingCustom && $existingCustom->num_rows > 0) {
                    $c_list = (int)$existingCustom->fetch_assoc()['cid'];
                } else {
                    $complaint_type = (strpos($path, 'E/M') === 0) ? 'EM' : 'BR';
                    $priority = complaint_node_priority($conn, $selected_node_id, '3');
                    $subdivision = complaint_node_subdivision($conn, $selected_node_id);
                    list($cc_id, $cs_id) = complaint_compat_category_ids($conn, $selected_node_id);
                    $code = 'USR-'.date('ymdHis');

                    $created = $conn->query("
                        INSERT INTO complaint_list
                            (complaint_type, node_id, cc_id, cs_id, details, priority, subdivision, code)
                        VALUES
                            ('".$complaint_type."', '".$selected_node_id."', '".$cc_id."', '".$cs_id."', '".$customEscaped."', '".$priority."', '".$subdivision."', '".$code."')
                    ");
                    if($created) {
                        $c_list = (int)$conn->insert_id;
                    } else {
                        $err = "Custom complaint could not be saved. Please try again.";
                    }
                }
            }
        }

        if($err === '') {
            $complaintQ = $conn->query("SELECT * FROM complaint_list WHERE cid='$c_list'");
            $complaint = $complaintQ ? $complaintQ->fetch_assoc() : null;

            if(!$complaint) {
                $err = "Invalid complaint selected.";
            } else {
            $details = mysqli_real_escape_string($conn, $complaint['details']);
            $priority = mysqli_real_escape_string($conn, $complaint['priority']);
            $subdivision = mysqli_real_escape_string($conn, $complaint['subdivision']);

            $todaycompcount = $conn->query("SELECT ucid FROM users_complaint WHERE date='$date'")->num_rows;
            $thiscount = $todaycompcount + 1;
            $docketNumber = $d.sprintf("%02d", $thiscount);

            if($curtime >= '21:30' && $priority != '1') {
                $newQ = "INSERT INTO users_complaint
                (date, b_list, uid, details, c_list, time, priority, subdivision, docketNumber, c_status)
                VALUES
                ('$date', '$b_list', '$uid', '$details', '$c_list', '$time', '$priority', '$subdivision', '$docketNumber', '4')";
            } else {
                $newQ = "INSERT INTO users_complaint
                (date, b_list, uid, details, c_list, time, priority, subdivision, docketNumber)
                VALUES
                ('$date', '$b_list', '$uid', '$details', '$c_list', '$time', '$priority', '$subdivision', '$docketNumber')";
            }

            $result = $conn->query($newQ);

            if($result) {
                $msg = "Complaint added successfully.<br>Your complaint number is ".$docketNumber;
            } else {
                $err = "Complaint not saved. Please try again.";
            }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>ECIMS USER | NEW COMPLAINT</title>
    <?php include('includes/head.php'); ?>

    <style>
        .alert-success {
            color: #000;
        }

        .step-title {
            font-size: 18px;
            font-weight: 700;
            margin: 20px 0 12px;
            color: #222;
        }

        .selection-area {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
            gap: 12px;
            margin-bottom: 18px;
        }

        .select-card {
            position: relative;
            cursor: pointer;
            margin: 0;
        }

        .select-card input {
            display: none;
        }

        .select-card span {
            display: flex;
            min-height: 58px;
            align-items: center;
            justify-content: center;
            padding: 14px;
            border: 2px solid #e5e5e5;
            border-radius: 12px;
            background: #fff;
            color: #333;
            font-weight: 600;
            text-align: center;
            transition: all 0.25s ease;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        }

        .select-card.has-image span {
            min-height: 230px;
            padding: 0;
            overflow: hidden;
            background: #f7fbff;
            border-color: #d3dce8;
        }

        .select-card.has-image img {
            width: 100%;
            aspect-ratio: 3 / 2;
            object-fit: contain;
            display: block;
        }

        .select-card.has-image strong {
            width: 100%;
            padding: 12px;
            font-size: 15px;
            line-height: 1.35;
        }

        .select-card:hover span {
            border-color: #007bff;
            transform: translateY(-2px);
        }

        .select-card input:checked + span {
            background: #007bff;
            border-color: #007bff;
            color: #fff;
            box-shadow: 0 6px 18px rgba(0,123,255,0.35);
        }

        .complaint-card span {
            min-height: 70px;
            font-size: 15px;
        }

        .empty-box {
            grid-column: 1 / -1;
            padding: 15px;
            background: #fff4f4;
            color: red;
            border-radius: 8px;
            border: 1px solid #ffd1d1;
        }

        .loading-box {
            grid-column: 1 / -1;
            padding: 15px;
            background: #f7f7f7;
            border-radius: 8px;
        }

        .custom-complaint-box {
            display: none;
            margin-top: 18px;
            padding: 16px;
            background: #f7f9fc;
            border: 1px solid #dce3ec;
            border-radius: 8px;
        }

        .custom-complaint-note {
            margin-bottom: 10px;
            color: #444;
            font-weight: 600;
        }

        .submit-btn {
            padding: 12px 35px;
            font-size: 16px;
            display: none;
            border-radius: 8px;
            margin-top: 10px;
        }
    </style>
</head>

<body>
<div class="container-scroller">

    <div class="horizontal-menu">
        <?php $activePage = basename($_SERVER['PHP_SELF'], ".php"); ?>

        <nav class="navbar top-navbar col-lg-12 col-12 p-0">
            <div class="container-fluid">

                <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-start">
                    <a class="navbar-brand brand-logo" href="index.php">
                        <img style="width:115px;height:auto;" src="assets/images/logo.png" alt="logo" />
                    </a>
                    <a class="navbar-brand brand-logo-mini" href="index.php">
                        <img style="width:115px;height:auto;" src="assets/images/logo.png" alt="logo" />
                    </a>
                </div>

                <div class="text-center navbar-menu-wrapper d-none d-lg-block d-flex align-items-center justify-content-center">
                    <span style="text-transform:uppercase;font-size:30px;font-weight:bold;color:#000;">
                        military engineer services <br> HISAR/ALWAR
                    </span>
                </div>

                <div class="navbar-brand-wrapper d-flex align-items-center justify-content-end">
                    <a class="navbar-brand brand-logo d-none d-lg-block" href="index.php">
                        <img style="width:115px;height:auto;" src="assets/images/logo-right.png" alt="logo" />
                    </a>
                    <button class="navbar-toggler navbar-toggler-right d-lg-none align-self-center" type="button" data-toggle="horizontal-menu-toggle">
                        <i class="fa fa-bars text-white"></i>
                    </button>
                </div>

            </div>
        </nav>

        <p class="text-center p-0 m-1 fw-bolder">Login Date : <?php echo date('d/m/Y'); ?></p>

        <nav class="bottom-navbar">
            <div class="container-fluid">
                <?php include('includes/nav.php'); ?>
            </div>
        </nav>
    </div>

    <div class="container-fluid page-body-wrapper">
        <div class="main-panel">
            <div class="content-wrapper">

                <div class="page-header">
                    <h3 class="page-title">New Complaint</h3>
                </div>

                <div class="row">
                    <div class="col-12 grid-margin stretch-card">
                        <div class="card">
                            <div class="card-body">

                                <?php
                                if(!empty($err)) {
                                    echo "
                                    <div class='alert alert-danger'>
                                        <h4><i class='fa fa-warning'></i> Error!</h4>
                                        ".$err."
                                    </div>";
                                }

                                if(!empty($msg)) {
                                    echo "
                                    <div class='alert alert-success'>
                                        <h4><i class='fa fa-check'></i> Success!</h4>
                                        ".$msg."
                                    </div>";
                                }
                                ?>

                                <form method="POST">

                                    <div class="step-title">1. Select Complaint Type</div>

                                    <div class="selection-area">
                                        <?php
                                        $cat = complaint_root_nodes($conn);
                                        while($fetchcat = $cat->fetch_assoc()) {
                                        ?>
                                            <label class="select-card">
                                                <input type="radio" name="root_node_id" class="node_radio" value="<?php echo $fetchcat['id']; ?>" data-level="1" required>
                                                <span><?php echo complaint_html($fetchcat['name']); ?></span>
                                            </label>
                                        <?php } ?>
                                    </div>

                                    <div id="nodeLevels"></div>

                                    <div class="step-title">Select Complaint</div>

                                    <div id="complaintBox" class="selection-area">
                                        <div class="empty-box">Please select complaint type first.</div>
                                    </div>

                                    <input type="hidden" name="selected_node_id" id="selectedNodeId">

                                    <div id="customComplaintBox" class="custom-complaint-box">
                                        <div class="custom-complaint-note">
                                            If you have doubts or your complaint is not in the list, type your complaint below.
                                        </div>
                                        <textarea name="custom_complaint" id="customComplaint" class="form-control" rows="3" maxlength="500" placeholder="Type your complaint"></textarea>
                                    </div>

                                    <button type="submit" name="submit" class="btn btn-primary submit-btn">
                                        Submit Complaint
                                    </button>

                                </form>

                            </div>
                        </div>
                    </div>
                </div>

            </div>

            <?php include('includes/footer.php'); ?>
        </div>
    </div>
</div>

<?php include('includes/foot.php'); ?>

<script>
$(document).ready(function(){
    var selectedRootType = '';

    function levelTitle(level) {
        if(level === 2) {
            if(selectedRootType.indexOf('B/R') !== -1 || selectedRootType.indexOf('BR') !== -1) {
                return '2. Select Category';
            }

            if(selectedRootType.indexOf('E/M') !== -1 || selectedRootType.indexOf('EM') !== -1) {
                return '2. Select Priority';
            }
        }

        var titles = {
            3: '3. Select Location',
            4: '4. Select Item'
        };
        return titles[level] || (level + '. Select Option');
    }

    function loadNode(nodeId, level) {
        $('.node-level').filter(function(){
            return parseInt($(this).data('level'), 10) >= level;
        }).remove();
        $('#selectedNodeId').val('');
        $('#customComplaintBox').hide();
        $('#customComplaint').val('');
        $('.submit-btn').hide();

        $.ajax({
            url: '',
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'get_node_data',
                node_id: nodeId,
                level: level
            },
            beforeSend: function(){
                $('#complaintBox').html('<div class="loading-box">Loading...</div>');
            },
            success: function(response){
                if(response.has_children) {
                    $('#nodeLevels').append(
                        '<div class="node-level" data-level="'+level+'">' +
                            '<div class="step-title">'+levelTitle(level)+'</div>' +
                            '<div class="selection-area">'+response.nodes+'</div>' +
                        '</div>'
                    );
                }
                $('#complaintBox').html(response.complaints);
                if(!response.has_children) {
                    $('#selectedNodeId').val(nodeId);
                    $('#customComplaintBox').show();
                }
            }
        });
    }

    $(document).on('change', '.node_radio', function(){
        var nodeId = $(this).val();
        var level = parseInt($(this).data('level'), 10) + 1;
        if(parseInt($(this).data('level'), 10) === 1) {
            selectedRootType = $(this).closest('.select-card').text().trim().toUpperCase();
        }
        loadNode(nodeId, level);
    });

    $(document).on('change', '.complaint_radio', function(){
        $('#customComplaint').val('');
        $('.submit-btn').show();
    });

    $('#customComplaint').on('input', function(){
        var hasText = $.trim($(this).val()).length > 0;
        if(hasText) {
            $('.complaint_radio').prop('checked', false);
        }
        $('.submit-btn').toggle(hasText || $('.complaint_radio:checked').length > 0);
    });

});
</script>

</body>
</html>

<?php } ?>
