<?php
ob_start();
session_start();

// Set error reporting for development (adjust for production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Include configuration
require_once __DIR__ . '/../config/theconfig.php';

// Set response header
header('Content-Type: text/html; charset=UTF-8');

// Check if user is logged in
if (!isset($_SESSION['customerid'])) {
    header("Location: login.php");
    exit;
}

// Redirect if OTP is already verified
if (isset($_SESSION['otp_verified'])) {
    header("Location: dashboard.php");
    exit;
}

// Initialize variables
$max_attempts = 3;
$customerid = $_SESSION['customerid'];
$customerName = "Customer";
$profileImage = "avatar-1.jpg";
$error = "";

// Initialize OTP attempts if not set
if (!isset($_SESSION['otp_attempts'])) {
    $_SESSION['otp_attempts'] = 0;
}

// Fetch customer details
$stmt = $conn->prepare("SELECT firstname, lastname, image FROM customers WHERE customerid = ?");
$stmt->bind_param("s", $customerid);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 1) {
    $customer = $result->fetch_assoc();
    $customerName = $customer['firstname'] . " " . $customer['lastname'];
    $profileImage = !empty($customer['image']) ? $customer['image'] : 'avatar-1.jpg';
}
$stmt->close();

// Function to generate OTP
function generateOTP() {
    return str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT); // 6-digit OTP
}

// OTP Verification
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_otp'])) {
    if ($_SESSION['otp_attempts'] >= $max_attempts) {
        // Block account
        $stmt = $conn->prepare("UPDATE customers SET accstatus = 'blocked' WHERE customerid = ?");
        $stmt->bind_param("s", $customerid);
        $stmt->execute();
        $stmt->close();
        $_SESSION['otp_attempts']++;
        $_SESSION['account_blocked'] = true;
        $error = "Account blocked due to too many failed attempts. Please contact support.";
    } else {
        $otp = filter_input(INPUT_POST, 'otp', FILTER_SANITIZE_STRING);
        
        // Fetch stored OTP
        $stmt = $conn->prepare("SELECT transpassword, otp_generated_at FROM customers WHERE customerid = ?");
        $stmt->bind_param("s", $customerid);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 1) {
            $row = $result->fetch_assoc();
            $stored_otp = $row['transpassword'];
            $otp_generated_at = $row['otp_generated_at'];

            // Optional: Check OTP expiration (e.g., 5 minutes)
            $otp_expiry = 10000000000000000 * 60; // 5 minutes in seconds
            if (!empty($otp_generated_at) && (time() - strtotime($otp_generated_at)) > $otp_expiry) {
                $error = "OTP has expired. Please request a new one.";
            } elseif ($stored_otp === $otp) {
                // OTP is correct
                $_SESSION['otp_attempts'] = 0; // Reset attempts
                $_SESSION['otp_verified'] = true; // Mark as verified
                
                // Generate and store new OTP for next login
                $new_otp = generateOTP();
                $current_time = date('Y-m-d H:i:s');
                $stmt_update = $conn->prepare("UPDATE customers SET otp = ?, otp_generated_at = ?, otp_attempts = 0 WHERE customerid = ?");
                $stmt_update->bind_param("sss", $new_otp, $current_time, $customerid);
                $stmt_update->execute();
                $stmt_update->close();

                // Redirect to dashboard
                header("Location: dashboard.php");
                exit;
            } else {
                // Invalid OTP
                $_SESSION['otp_attempts']++;
                $remaining_attempts = $max_attempts - $_SESSION['otp_attempts'];
                
                // Update otp_attempts in database
                $stmt_update = $conn->prepare("UPDATE customers SET otp_attempts = ? WHERE customerid = ?");
                $attempts = $_SESSION['otp_attempts'];
                $stmt_update->bind_param("is", $attempts, $customerid);
                $stmt_update->execute();
                $stmt_update->close();

                if ($remaining_attempts > 0) {
                    $error = "Invalid OTP. You have $remaining_attempts attempt(s) left.";
                } else {
                    $error = "Invalid OTP. You have reached the maximum number of attempts.";
                    $_SESSION['last_attempt'] = true;
                }
            }
        } else {
            $error = "OTP verification failed. Please try again later.";
        }
        $stmt->close();
    }
}

// Handle session destruction
if (isset($_GET['destroy_session']) || isset($_GET['logout'])) {
    session_unset();
    session_destroy();
    header("Location: login.php");
    exit;
}

// Close database connection
$conn->close();
?>


<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8" />
      <title>Verify Account Pin.</title>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta content="Verify PIN" name="description" />
      <!-- App favicon -->
      <link rel="shortcut icon" href="assets/images/favicon.ico">
      <!-- Bootstrap Css -->
      <link href="assets/css/bootstrap.min.css" id="bootstrap-style" rel="stylesheet" type="text/css" />
      <!-- Icons Css -->
      <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
      <!-- App Css-->
      <link href="assets/css/app.min.css" id="app-style" rel="stylesheet" type="text/css" />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
   </head>
   <body>
      <div class="account-pages my-5 pt-sm-5">
         <div class="container">
            <div class="row justify-content-center">
               <div class="col-md-8 col-lg-6 col-xl-5">
                  <div class="card overflow-hidden no-box">
                     <div class="card-body pt-0">
                        <h4 class="p-2 mt-3" style="margin-bottom:-14px; text-align:center;">Account Pin Verification</h4>

                        <!-- Customer Details -->
                        <div class="text-center mt-4">
                           <img src="assets/images/users/<?php echo $profileImage; ?>" alt="Profile" class="rounded-circle" width="90" height="90" style="border: 3px solid #b6922e; padding: 2px; border-radius: 50%;">
                           <h4 class="mt-3"><?php echo $customerName; ?></h4>
                        </div>

                        <!-- OTP Form -->
                        <div class="p-2 mt-4">
                           <?php if (isset($error)): ?>
                           <div class="alert alert-danger">
                              <?php echo $error; ?>
                           </div>
                           <?php endif; ?>
                           <form method="POST">
                              <div class="mb-3">
                                 <label for="otp" class="form-label">Enter your 6 digit account pin / Transaction Password.</label>
                                 <input type="text" class="form-control" id="otp" name="otp" placeholder="Enter Account Pin" required>
                              </div>
                              <div class="mt-4 text-end">
                                 <button name="verify_otp" class="btn btn-primary w-xs waves-effect waves-light" type="submit">Verify Pin</button>
                              </div>
                           </form>
                        </div>
                     </div>
                  </div>

                  <!-- Logout button -->
                  <div class="text-center mt-4">
                     <a href="otp.php?logout=true" class="btn btn-danger">Logout</a>
                  </div>

                  <div class="mt-5">
                     <div>
                        <p class="text-center text-md-left"> ©  <script>document.write(new Date().getFullYear())</script> Internet Banking, All Rights Reserved.</p>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
      <!-- JAVASCRIPT -->
      <script src="assets/libs/jquery/jquery.min.js"></script>
      <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
      <script src="assets/libs/metismenu/metisMenu.min.js"></script>
      <script src="assets/libs/simplebar/simplebar.min.js"></script>
      <script src="assets/libs/node-waves/waves.min.js"></script>

      <script>
        
         <?php if (isset($_SESSION['account_blocked'])): ?>
            Swal.fire({
                icon: 'error',
                title: 'Account Disabled',
                text: 'Your account has been temporarily disabled due to too many failed PIN attempts.',
                confirmButtonText: 'OK'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = 'login.php'; 
                }
            });
            <?php unset($_SESSION['account_blocked']); // Clear the session flag ?>
         <?php endif; ?>

         // Check if last attempt
         <?php if (isset($_SESSION['last_attempt'])): ?>
            Swal.fire({
                icon: 'error',
                title: 'Last Attempt!',
                text: 'This was your last attempt. You will be redirected to the login page.',
                confirmButtonText: 'OK'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = 'otp.php?destroy_session=true'; 
                }
            });
            <?php unset($_SESSION['last_attempt']); // Clear the session flag ?>
         <?php endif; ?>

         // Check if OTP is verified successfully
         <?php if (isset($_SESSION['otp_verified'])): ?>
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: 'Pin successfully verified.',
                confirmButtonText: 'Login'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = 'dashboard.php'; 
                }
            });
            <?php unset($_SESSION['otp_verified']); // Clear the session flag ?>
         <?php endif; ?>
      </script>
   </body>
</html>
