<?php
include "config.php";
require_once "sms/SmsHelper.php";

error_reporting(0);
session_start();

if (isset($_SESSION['log']) && $_SESSION['log'] !== '') {
    header('Location:home.php');
    exit();
}

if (empty($_SESSION['pending_login'])) {
    header('Location:index.php');
    exit();
}

$otpError = '';
$otpMessage = '';
$pendingLogin = $_SESSION['pending_login'];
$smsConfig = include "sms/sms_config.php";

if (isset($_POST['verify_otp'])) {
    $otpInput = isset($_POST['otp_code']) ? trim($_POST['otp_code']) : '';
    $expiresAt = isset($_SESSION['login_otp_expires_at']) ? $_SESSION['login_otp_expires_at'] : 0;
    $attempts = isset($_SESSION['login_otp_attempts']) ? $_SESSION['login_otp_attempts'] : 0;
    $sessionEmployeeCode = isset($_SESSION['login_otp_employee_code']) ? $_SESSION['login_otp_employee_code'] : '';

    if ($attempts >= 5) {
        $otpError = 'Too many invalid OTP attempts. Please login again.';
    } elseif ($sessionEmployeeCode === '' || strcasecmp($sessionEmployeeCode, $pendingLogin['employee_code']) !== 0) {
        $otpError = 'OTP session mismatch. Please login again.';
    } elseif ($otpInput === '') {
        $otpError = 'Please enter OTP.';
    } elseif (time() > $expiresAt) {
        $otpError = 'OTP expired. Please resend OTP.';
    } elseif (!isset($_SESSION['login_otp_value']) || $otpInput !== $_SESSION['login_otp_value']) {
        $_SESSION['login_otp_attempts'] = $attempts + 1;
        $otpError = 'Invalid OTP.';
    } else {
        $_SESSION['log'] = $pendingLogin['username'];
        unset($_SESSION['pending_login'], $_SESSION['login_otp_employee_code'], $_SESSION['login_otp_value'], $_SESSION['login_otp_expires_at'], $_SESSION['login_otp_resend_after'], $_SESSION['login_otp_attempts']);
        header('Location:home.php');
        exit();
    }
}

if (isset($_POST['resend_otp'])) {
    $resendAfter = isset($_SESSION['login_otp_resend_after']) ? $_SESSION['login_otp_resend_after'] : 0;

    if (time() < $resendAfter) {
        $otpError = 'Please wait before requesting a new OTP.';
    } else {
        $otpCode = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
        $smsHelper = new SmsHelper($smsConfig);
        $smsResponse = $smsHelper->sendOtp($pendingLogin['otp_mobile'], $otpCode, $pendingLogin['employee_name'], $pendingLogin['employee_code']);

        if ($smsResponse['success']) {
            $_SESSION['login_otp_value'] = $otpCode;
            $_SESSION['login_otp_expires_at'] = time() + 300;
            $_SESSION['login_otp_resend_after'] = time() + 30;
            $_SESSION['login_otp_attempts'] = 0;
            $otpMessage = 'A new OTP has been sent.';
        } else {
            $otpError = 'OTP could not be resent. Please check SMS API settings.';
        }
    }
}
?>
<html>
<head>
    <link rel="stylesheet" href="fontawesome-free-5.15.1-web/css/all.css">
    <link rel="stylesheet" href="bootstrap/min.css">
    <script src="bootstrap/jquery.min.js"></script>
    <script src="bootstrap/popper.min.js"></script>
    <script src="bootstrap/bootstrap.js"></script>
    <style>
        body {
            background-image:url("image/mountain2.jpg");
            background-position:center;
        }
        .otp-card {
            background-color:rgba(228, 237, 230, 0.82);
            width:500px;
            min-height:360px;
            margin:auto;
            margin-top:100px;
            border-radius:20px;
            font-family:timesnewroman;
            padding:30px 40px;
        }
        h1 {
            text-align:center;
            margin-bottom:20px;
        }
        .otp-card .form-control {
            margin-bottom:20px;
        }
    </style>
</head>
<body>
    <div class="otp-card">
        <h1>OTP VERIFY</h1>
        <p>OTP sent to <strong><?php echo htmlspecialchars($pendingLogin['otp_mobile']); ?></strong></p>
        <p>Employee Code: <strong><?php echo htmlspecialchars($pendingLogin['employee_code']); ?></strong></p>

        <?php if ($otpError != '') { ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($otpError); ?></div>
        <?php } ?>

        <?php if ($otpMessage != '') { ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($otpMessage); ?></div>
        <?php } ?>

        <form method="post" action="login_otp.php">
            <input type="text" name="otp_code" class="form-control" maxlength="6" autocomplete="off" placeholder="Enter 6 digit OTP">
            <input type="submit" name="verify_otp" class="btn btn-warning" value="Verify OTP">
            <input type="submit" name="resend_otp" class="btn btn-info" value="Resend OTP">
            <a href="logout.php" class="btn btn-danger">Cancel</a>
        </form>
    </div>
</body>
</html>
