<?php 
session_start(); 
include('includes/conn.php'); 

if(isset($_GET['ajax']) && $_GET['ajax'] == 'building_search') {

    $q = mysqli_real_escape_string($conn, trim($_GET['q'] ?? ''));
    $q = str_replace('P-', '', $q);

    $data = [];

    if($q != '') {
        $sql = $conn->query("
            SELECT bid, bNo, bName 
            FROM building_list 
            WHERE isDeleted='0' 
            AND bNo LIKE '".$q."%' 
            ORDER BY CAST(bNo AS UNSIGNED) ASC 
            LIMIT 20
        ");

        while($row = $sql->fetch_assoc()) {
            $data[] = $row;
        }
    }

    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

$err = '';

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

    $bid  = (int)($_POST['bid'] ?? 0);
    $mpin = mysqli_real_escape_string($conn, trim($_POST['mpin'] ?? ''));

    if($bid <= 0) {
        $err = '<div class="alert alert-danger">Please select building from dropdown.</div>';
    } else {

        $selectBuilding = $conn->query("
            SELECT * FROM building_list 
            WHERE bid = '".$bid."' 
            AND mpin = '".$mpin."' 
            AND isDeleted = '0'
            LIMIT 1
        ");

        if($selectBuilding && $selectBuilding->num_rows > 0) {
            
            

            $building = $selectBuilding->fetch_assoc();

            $buildingId   = $building['bid'];
            $buildingName = 'P-'.$building['bNo'];
            $_SESSION['reset_building_id'] = $buildingId;
            $_SESSION['reset_building_name'] = $buildingName;

            if($building['pin_reset_status'] == 0 || empty($building['mobile'])) {
                echo '<script>window.location.href="resetPin.php?bid='.$buildingId.'"</script>';
                exit;
            }

   $buildingUserKey = $building['mobile'];

            $checkUser = $conn->query("
                SELECT * FROM users 
                WHERE phone = '".$buildingUserKey."' 
                LIMIT 1
            ");

            if($checkUser && $checkUser->num_rows > 0) {

                $user = $checkUser->fetch_assoc();
                $userId = $user['uid'];

                $conn->query("
                    UPDATE users 
                    SET last_date = '".date('h:i a , d/m/Y')."' 
                    WHERE uid = '".$userId."'
                ");

            } else {

                $conn->query("
                    INSERT INTO users 
                    (phone, creation_date, last_date) 
                    VALUES 
                    ('".$buildingUserKey."', '".date('h:i a , d/m/Y')."', '".date('h:i a , d/m/Y')."')
                ");

                $userId = $conn->insert_id;
            }

            $_SESSION['ecimsuser'] = $userId;

            $_SESSION['building_login'] = true;
            $_SESSION['building_id'] = $buildingId;
            $_SESSION['building_name'] = $buildingName;

            $conn->query("
                INSERT INTO userlogs 
                (user, date) 
                VALUES 
                ('".$userId."', '".date('Y-m-d H:i:s')."')
            ");

            if(isset($_GET['st'])) {

                if($_GET['st'] == 'new') {
                    echo '<script>window.location.href="user-dashboard.php"</script>';
                } else if($_GET['st'] == 'list') {
                    echo '<script>window.location.href="user-dashboard.php"</script>';
                } else if($_GET['st'] == 'close') {
                    echo '<script>window.location.href="user-dashboard.php"</script>';
                } else if($_GET['st'] == 'feedback') {
                    echo '<script>window.location.href="user-dashboard.php"</script>';
                } else {
                    echo '<script>window.location.href="user-dashboard.php"</script>';
                }

            } else {
                echo '<script>window.location.href="user-dashboard.php"</script>';
            }

            exit;

        } else {
            $err = '<div class="alert alert-danger">Invalid Building or MPIN.</div>';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>ECIMS</title>
    <?php include('includes/head1.php'); ?>

    <style>
        .login-wrapper{
            min-height:650px;
            background:linear-gradient(135deg,#0b3d66,#1769aa,#44a3e8);
            display:flex;
            align-items:center;
            justify-content:center;
            padding:40px 15px;
        }

        .login-card{
            background:#fff;
            border-radius:22px;
            padding:35px;
            width:100%;
            max-width:460px;
            box-shadow:0 20px 45px rgba(0,0,0,.25);
            position:relative;
        }

        .login-card h2{
            font-weight:800;
            color:#2B6F96;
            text-align:center;
            text-transform:uppercase;
        }

        .login-card h4{
            text-align:center;
            margin-bottom:25px;
            font-weight:700;
        }

        .form-control{
            border-radius:12px;
            height:50px;
        }

        .btn-login{
            background:linear-gradient(45deg,#0d6efd,#00c6ff);
            border:none;
            border-radius:50px;
            height:52px;
            font-weight:800;
            font-size:17px;
            color:#fff;
            width:100%;
        }

        .btn-login:hover{
            color:#fff;
            transform:scale(1.03);
        }

        .suggestion-box{
            position:absolute;
            background:#fff;
            width:100%;
            border:1px solid #ddd;
            border-radius:12px;
            box-shadow:0 10px 25px rgba(0,0,0,.15);
            max-height:220px;
            overflow-y:auto;
            z-index:9999;
            display:none;
        }

        .suggestion-item{
            padding:12px 15px;
            cursor:pointer;
            border-bottom:1px solid #eee;
        }

        .suggestion-item:hover{
            background:#f1f7ff;
        }

        .suggestion-item strong{
            color:#0d6efd;
        }

        .search-area{
            position:relative;
        }

        .date-box{
            background:#fff;
            display:inline-block;
            padding:7px 20px;
            border-radius:50px;
            font-weight:800;
            margin-bottom:15px;
        }
    </style>
</head>

<body class="sidebar-toggle-display sidebar-hidden">

<div class="container-scroller">

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

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

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

        <div class="main-panel">

            <div class="content-wrapper" style="padding:0">

                <div class="login-wrapper">

                    <div class="login-card">

                        <div class="text-center">
                            <div class="date-box">
                                Today Date : <?php echo date('d/m/Y'); ?>
                            </div>
                        </div>

                        <h2>Welcome to ECIMS</h2>
                        <h4>Building Login</h4>

                        <?php echo $err; ?>

                        <form method="POST" autocomplete="off">

                            <input type="hidden" name="bid" id="bid">

                            <div class="form-group search-area">
                                <label>Building No</label>
                                <input type="text"
                                       class="form-control"
                                       id="building_no"
                                       placeholder="Type Building No. Example: 143"
                                       required>

                                <div id="buildingSuggestions" class="suggestion-box"></div>
                            </div>

                            <input type="hidden"
                                   id="building_name"
                                   name="building_name">

                            <div class="form-group">
                                <label>MPIN</label>
                                <input type="password"
                                       autocomplete="off"
                                       class="form-control"
                                       name="mpin"
                                       placeholder="Enter MPIN"
                                       required>
                            </div>

                            <div class="mt-3">
                                <input type="submit"
                                       name="login"
                                       class="btn btn-login"
                                       value="LOGIN">
                            </div>

                        </form>

                    </div>

                </div>

            </div>

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

        </div>

    </div>

</div>

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

<script>
document.getElementById('building_no').addEventListener('keyup', function () {

    let q = this.value.trim();
    let box = document.getElementById('buildingSuggestions');

    q = q.replace('P-', '').replace('p-', '');

    document.getElementById('bid').value = '';
    document.getElementById('building_name').value = '';

    if(q.length < 1) {
        box.style.display = 'none';
        box.innerHTML = '';
        return;
    }

    fetch('userLogin.php?ajax=building_search&q=' + encodeURIComponent(q))
        .then(response => response.json())
        .then(data => {

            box.innerHTML = '';

            if(data.length > 0) {

                data.forEach(item => {

                    let div = document.createElement('div');
                    div.className = 'suggestion-item';
                    div.innerHTML = '<strong>P-' + item.bNo + '</strong>';

                    div.onclick = function () {
                        document.getElementById('bid').value = item.bid;
                        document.getElementById('building_no').value = '' + item.bNo;
                        document.getElementById('building_name').value = '' + item.bNo;

                        box.style.display = 'none';
                        box.innerHTML = '';
                    };

                    box.appendChild(div);
                });

                box.style.display = 'block';

            } else {
                box.innerHTML = '<div class="suggestion-item">No building found</div>';
                box.style.display = 'block';
            }

        });
});

document.addEventListener('click', function(e) {
    if(!e.target.closest('.search-area')) {
        document.getElementById('buildingSuggestions').style.display = 'none';
    }
});
</script>

</body>
</html>