<?php
declare(strict_types=1);

require_once "session_config.php";
require_once "config.php";

// Check if already logged in
if (isset($_SESSION['username'])) {
    header("Location: dashboard");
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title>UPI PG BUSINESS</title>
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, shrink-to-fit=no" name="viewport" />

    <link rel="icon" href="assets/img/hdfc.png" type="image/*" />

    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito:200,300,400,600,700,800,900">
    <link rel="stylesheet" href="assets/css/ready.css">
    <link rel="stylesheet" href="assets/css/demo.css">
    <link rel="stylesheet" href="https://rsms.me/inter/inter.css">

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <style>
        body{
            font-family: 'Inter', sans-serif;
            background: #f2f3f8 !important;
        }
        a{ text-decoration:none!important; }
        .card{ border-radius:5px!important; }
    </style>
</head>

<body>

<!-- DISCLAIMER MODAL -->
<div class="modal fade" id="disclaimer" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">❗ Disclaimer Notice</h5>
            </div>
            <div class="modal-body">
                <p>This PAY ICON does not provide any Payment Gateway services.</p>
                <p>We only provide API to generate QR code for your UPI ID.</p>
                <p>We are not involved in any transaction.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-dark" onclick="document.body.innerHTML=''">Leave</button>
                <button type="button" class="btn btn-primary" data-dismiss="modal">I Agree</button>
            </div>
        </div>
    </div>
</div>

<div class="container">
<section class="h-100">
<div class="container py-5 h-100">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col-xl-6">
<div class="card">
<div class="card-body p-md-5">

<div class="text-center">
    <img src="assets/img/hdfc.png" style="width:185px;" alt="Logo">
    <h6 class="mt-4 mb-4">Please login to your account</h6>
</div>

<?php
/* ================= LOGIN LOGIC ================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {

    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    if ($username === '' || $password === '') {
        echo "<script>
            Swal.fire('Error','Invalid Input','error')
            .then(()=>{location.href='index';});
        </script>";
        exit;
    }

    // Validate mobile number format
    if (!preg_match('/^[0-9]{10}$/', $username)) {
        echo "<script>
            Swal.fire('Invalid Mobile','Enter 10-digit number','error')
            .then(()=>{location.href='index';});
        </script>";
        exit;
    }

    $stmt = $conn->prepare(
        "SELECT id, password, acc_lock, acc_ban FROM users WHERE mobile = ?"
    );
    
    if (!$stmt) {
        error_log("Prepare failed: " . $conn->error);
        echo "<script>
            Swal.fire('System Error','Please try again','error')
            .then(()=>{location.href='index';});
        </script>";
        exit;
    }
    
    $stmt->bind_param("s", $username);
    
    if (!$stmt->execute()) {
        error_log("Execute failed: " . $stmt->error);
        echo "<script>
            Swal.fire('System Error','Please try again','error')
            .then(()=>{location.href='index';});
        </script>";
        exit;
    }
    
    $res = $stmt->get_result();
    $stmt->close();

    if ($res->num_rows === 0) {
        echo "<script>
            Swal.fire('User Not Found','Try again','error')
            .then(()=>{location.href='index';});
        </script>";
        exit;
    }

    $row = $res->fetch_assoc();

    $userId  = (int)($row['id'] ?? 0);
    $hash    = $row['password'] ?? '';
    $lock    = (int)($row['acc_lock'] ?? 0);
    $ban     = $row['acc_ban'] ?? 'off';

    if ($ban === 'on') {
        echo "<script>
            Swal.fire('Account Locked','Contact admin','error')
            .then(()=>{location.href='index';});
        </script>";
        exit;
    }

    if (password_verify($password, $hash)) {

        $_SESSION['username'] = $username;
        $_SESSION['user_id']  = $userId;
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

        $reset = $conn->prepare(
            "UPDATE users SET acc_lock = 0 WHERE mobile = ?"
        );
        
        if ($reset) {
            $reset->bind_param("s", $username);
            $reset->execute();
            $reset->close();
        }

        echo "<script>
            Swal.fire('Login Successful','Redirecting...','success')
            .then(()=>{location.href='dashboard';});
        </script>";
        exit;

    } else {

        $lock++;
        $up = $conn->prepare(
            "UPDATE users SET acc_lock = ? WHERE mobile = ?"
        );
        
        if ($up) {
            $up->bind_param("is", $lock, $username);
            $up->execute();
            $up->close();
        }

        if ($lock >= 3) {
            echo "<script>
                Swal.fire('Account Locked','Too many attempts','error')
                .then(()=>{location.href='index';});
            </script>";
        } else {
            echo "<script>
                Swal.fire('Wrong Password','Try again','error')
                .then(()=>{location.href='index';});
            </script>";
        }
        exit;
    }
}
?>

<form method="POST" action="">
    <div class="form-group mb-3">
        <label>Mobile Number</label>
        <input type="text" name="username" class="form-control"
               minlength="10" maxlength="10"
               oninput="this.value=this.value.replace(/[^0-9]/g,'');"
               pattern="[0-9]{10}"
               title="Please enter a 10-digit mobile number"
               required>
    </div>

    <div class="form-group mb-3">
        <label>Password</label>
        <input type="password" name="password" class="form-control" 
               minlength="6"
               required>
    </div>

    <div class="text-center">
        <button class="btn btn-primary w-100 mb-2" name="submit" type="submit">Login</button>
        <a href="forgotpassword">Forgot password?</a>
    </div>

    <div class="text-center mt-3">
        <span>Don't have an account?</span>
        <button type="button" class="btn btn-outline-danger btn-sm"
                onclick="location.href='register'">Register</button>
    </div>
</form>

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

<script src="assets/js/core/jquery.3.2.1.min.js"></script>
<script src="assets/js/core/bootstrap.min.js"></script>

<script>
$(document).ready(function(){
    $('#disclaimer').modal({
        backdrop:'static',
        keyboard:false
    }).modal('show');
});

// Prevent form resubmission on page refresh
if (window.history.replaceState) {
    window.history.replaceState(null, null, window.location.href);
}
</script>

</body>
</html>