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

$err = '';
$bid = 0;

if(isset($_GET['bid']) && $_GET['bid'] != '') {
    $bid = (int)$_GET['bid'];
    $_SESSION['reset_building_id'] = $bid;
}

if(isset($_SESSION['reset_building_id']) && $_SESSION['reset_building_id'] != '') {
    $bid = (int)$_SESSION['reset_building_id'];
}

if($bid <= 0) {
    echo '<script>window.location.href="userLogin.php"</script>';
    exit;
}

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

if(!$checkBuilding || $checkBuilding->num_rows == 0) {
    echo '<script>window.location.href="userLogin.php"</script>';
    exit;
}

$building = $checkBuilding->fetch_assoc();
$_SESSION['reset_building_name'] = 'P-'.$building['bNo'];

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

    $mobile      = mysqli_real_escape_string($conn, trim($_POST['mobile'] ?? ''));
    $new_pin     = mysqli_real_escape_string($conn, trim($_POST['new_pin'] ?? ''));
    $confirm_pin = mysqli_real_escape_string($conn, trim($_POST['confirm_pin'] ?? ''));

    if($mobile == '') {
        $err = '<div class="alert alert-danger">Please enter mobile number.</div>';
    } 
    else if(!preg_match('/^[0-9]{10}$/', $mobile)) {
        $err = '<div class="alert alert-danger">Please enter valid 10 digit mobile number.</div>';
    } 
    else if(!preg_match('/^[0-9]{4}$/', $new_pin)) {
        $err = '<div class="alert alert-danger">PIN must be 4 digits only.</div>';
    } 
    else if($new_pin != $confirm_pin) {
        $err = '<div class="alert alert-danger">Confirm PIN does not match.</div>';
    } 
    else {

        $updateBuilding = $conn->query("
            UPDATE building_list 
            SET mobile = '".$mobile."', 
                mpin = '".$new_pin."', 
                pin_reset_status = '1'
            WHERE bid = '".$bid."'
        ");

        if($updateBuilding) {

            $checkUser = $conn->query("
                SELECT * FROM users 
                WHERE phone = '".$mobile."' 
                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 
                    ('".$mobile."', '".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'] = $bid;
            $_SESSION['building_name'] = $_SESSION['reset_building_name'];

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

            unset($_SESSION['reset_building_id']);
            unset($_SESSION['reset_building_name']);

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

        } else {
            $err = '<div class="alert alert-danger">Something went wrong. Please try again.</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);
        }

        .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">

        <div class="main-panel" style="width:100%;">

            <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>First Time PIN Reset</h4>

                        <?php echo $err; ?>

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

                            <div class="form-group">
                                <label>Building No</label>
                                <input type="text"
                                       class="form-control"
                                       value="<?php echo $_SESSION['reset_building_name']; ?>"
                                       readonly>
                            </div>

                            <div class="form-group">
                                <label>Mobile Number</label>
                                <input type="text"
                                       name="mobile"
                                       maxlength="10"
                                       class="form-control"
                                       placeholder="Enter Mobile Number"
                                       value="<?php echo isset($_POST['mobile']) ? $_POST['mobile'] : ''; ?>"
                                       required>
                            </div>

                            <div class="form-group">
                                <label>New MPIN</label>
                                <input type="password"
                                       name="new_pin"
                                       maxlength="4"
                                       class="form-control"
                                       placeholder="Enter New 4 Digit MPIN"
                                       required>
                            </div>

                            <div class="form-group">
                                <label>Confirm MPIN</label>
                                <input type="password"
                                       name="confirm_pin"
                                       maxlength="4"
                                       class="form-control"
                                       placeholder="Confirm MPIN"
                                       required>
                            </div>

                            <div class="mt-3">
                                <input type="submit"
                                       name="update_pin"
                                       class="btn btn-login"
                                       value="UPDATE & CONTINUE">
                            </div>

                        </form>

                    </div>

                </div>

            </div>

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

        </div>

    </div>

</div>

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

</body>
</html>