<?php
ob_start();
session_start();
error_reporting(0);

include("../config/theconfig.php");
require_once("../config/customer_session_guard.php");

if (!isset($_SESSION['customerid'])) {
    header("Location: login.php");
    exit(0);
}

customer_session_abort_if_blocked($con, 'redirect');

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

// Max attempts constant
$max_attempts = 3;

// Initialize or get the attempts counter
if (!isset($_SESSION['otp_attempts'])) {
    $_SESSION['otp_attempts'] = 0;
}

$customerid = $_SESSION['customerid'];

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

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

$stmt->close();

// Handle the POST request for OTP verification
if (isset($_POST['verify_otp'])) {
    $otp = trim($_POST['otp']);

    $otp_stmt = $con->prepare("SELECT otp FROM customers WHERE customerid = ?");
    $otp_stmt->bind_param("s", $customerid);
    $otp_stmt->execute();
    $otp_result = $otp_stmt->get_result();

    if ($otp_result && $otp_result->num_rows === 1) {
        $row = $otp_result->fetch_assoc();
        if ($row['otp'] === $otp) {
            // Correct OTP
            $_SESSION['otp_attempts'] = 0; 
            $_SESSION['otp_verified'] = true;
        } else {
            // Incorrect OTP
            $_SESSION['otp_attempts']++; // Increment the counter
            $remaining_attempts = $max_attempts - $_SESSION['otp_attempts'];

            if ($remaining_attempts <= 0) {
                // Block the account on the final attempt
                $block_stmt = $con->prepare("UPDATE customers SET accstatus='blocked' WHERE customerid = ?");
                $block_stmt->bind_param("s", $customerid);
                $block_stmt->execute();
                $block_stmt->close();
                $_SESSION['account_blocked'] = true;
                $error = "Invalid PIN. You have reached the maximum number of attempts.";
            } else {
                // Show error message with remaining attempts
                $error = "Invalid PIN. You have $remaining_attempts attempt(s) left.";
            }
        }
    } else {
        $error = "PIN verification failed. Please try again later.";
    }
    $otp_stmt->close();
}

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

if (isset($_GET['logout'])) {
    session_unset();
    session_destroy();
    header("Location: login.php");
    exit(0);
}


$sbank   = "Default Bank";
$semail  = "support@defaultbank.com";
$favicon = "assets/images/brand/favicon_1758475458.ico";

$stmt = $con->prepare("SELECT bank_name, email, favicon FROM system_settings LIMIT 1");
if ($stmt) {
    $stmt->execute();
    $stmt->bind_result($dbBank, $dbEmail, $dbFavicon);
    if ($stmt->fetch()) {
        // Override defaults if values exist
        $sbank   = $dbBank ?: $sbank;
        $semail  = $dbEmail ?: $semail;
        $favicon = $dbFavicon ?: $favicon;
    }
    $stmt->close();
}

?>

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8" />
      <title>Verify Account Pin | <?php echo $sbank ?></title>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta content="Verify PIN" name="description" />
      <?php if (!empty($favicon)): ?>
      <link rel="icon" href="../<?= htmlspecialchars($favicon); ?>" type="image/<?= pathinfo($favicon, PATHINFO_EXTENSION); ?>">
      <?php endif; ?>
      <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
      <link href="assets/css/bootstrap.min.css" id="bootstrap-style" rel="stylesheet" type="text/css" />
      <link href="assets/css/icons.min.css" rel="stylesheet" type="text/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>
<style>
    /* --- PREMIUM BLUE THEME --- */
    :root {
        --primary-purple: #003399; /* Primary Blue */
        --dark-purple: #005D9D;    /* Secondary Blue */
        --soft-purple-bg: #e6efff; /* Light Blue background for profile ring */
        --bg-body: #f8fafc;
        --text-main: #0f172a;
        --text-secondary: #64748b;
    }

    body {
        background: var(--bg-body);
        font-family: 'Plus Jakarta Sans', sans-serif;
        min-height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .card {
        border: none;
        border-radius: 24px;
        box-shadow: 0 20px 40px -10px rgba(0,0,0,0.1);
        background: #fff;
        overflow: hidden;
    }

    .card-body { padding: 40px; }

    .otp-header {
        text-align: center;
        margin-bottom: 30px;
    }

    .profile-img-container {
        position: relative;
        width: 100px;
        height: 100px;
        margin: 0 auto 20px;
    }

    .profile-img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        object-fit: cover;
        border: 4px solid var(--soft-purple-bg);
        padding: 3px;
    }
    
    .status-badge {
        position: absolute;
        bottom: 5px;
        right: 5px;
        width: 20px;
        height: 20px;
        background: #10b981;
        border: 3px solid white;
        border-radius: 50%;
    }

    .form-label {
        font-weight: 600;
        color: var(--text-main);
        margin-bottom: 8px;
    }

    .form-control {
        border-radius: 12px;
        padding: 12px 16px;
        border: 1px solid #e2e8f0;
        height: 50px;
        text-align: center;
        font-size: 1.2rem;
        letter-spacing: 5px;
        font-weight: 700;
    }

    .form-control:focus {
        border-color: var(--primary-purple);
        box-shadow: 0 0 0 4px var(--soft-purple-bg);
    }

    .btn-primary {
        background-color: var(--primary-purple);
        border: none;
        border-radius: 12px;
        padding: 14px;
        font-weight: 700;
        width: 100%;
        transition: all 0.3s ease;
        font-size: 1rem;
        /* Updated Shadow to Blue */
        box-shadow: 0 4px 12px rgba(0, 51, 153, 0.3);
    }

    .btn-primary:hover {
        background-color: var(--dark-purple);
        transform: translateY(-2px);
        box-shadow: 0 6px 15px rgba(0, 51, 153, 0.4);
    }
    
    .footer-text {
        color: #94a3b8;
        font-size: 0.8rem;
        text-align: center;
        margin-top: 30px;
    }
</style>
   </head>
   <body>
      <div class="container">
         <div class="row justify-content-center">
            <div class="col-md-8 col-lg-6 col-xl-5">
               <div class="card">
                  <div class="card-body">
                     
                     <div class="otp-header">
                        <div class="profile-img-container">
                            <img src="assets/images/users/<?php echo $profileImage; ?>" alt="Profile" class="profile-img">
                            <div class="status-badge"></div>
                        </div>
                        <h4 class="fw-bold mb-1 text-dark"><?php echo $customerName; ?></h4>
                        <p class="text-secondary small mb-0">Verify your identity to proceed.</p>
                     </div>

                     <?php if (isset($error)): ?>
                     <div class="alert alert-danger d-flex align-items-center mb-4" role="alert" style="border-radius: 12px;">
                        <i class="bx bx-error-circle fs-4 me-2"></i>
                        <div><?php echo $error; ?></div>
                     </div>
                     <?php endif; ?>

                     <form method="POST">
                        <div class="mb-4">
                           <label for="otp" class="form-label">Account PIN (6-Digits)</label>
                           <input type="password" class="form-control" id="otp" name="otp" placeholder="••••••" maxlength="6" inputmode="numeric" autocomplete="off" required>
                        </div>
                        
                        <div class="d-grid">
                           <button name="verify_otp" class="btn btn-primary" type="submit">Verify Identity <i class="bx bx-shield-quarter ms-1"></i></button>
                        </div>
                     </form>

                     <div class="text-center mt-4 pt-2 border-top border-light">
                        <a href="otp.php?logout=true" class="text-decoration-none text-danger fw-bold small">
                            <i class="bx bx-log-out me-1"></i> Sign Out
                        </a>
                     </div>
                  </div>
               </div>
               
               <p class="footer-text">
                  &copy; <?php echo date("Y") . " " . $sbank; ?>. All rights reserved.
               </p>

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

      <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>
         // SweetAlert for Account Blocked
         <?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: 'Go to Login',
             confirmButtonColor: '#ef4444',
             allowOutsideClick: false
         }).then((result) => {
             if (result.isConfirmed) {
                 window.location.href = 'otp.php?destroy_session=true';
             }
         });
         <?php unset($_SESSION['account_blocked']); ?>
         
         <?php elseif (isset($error)): ?>
         // SweetAlert for Invalid OTP
         Swal.fire({
             icon: 'warning',
             title: 'Invalid PIN!',
             text: '<?php echo $error; ?>',
             confirmButtonText: 'Try Again',
             confirmButtonColor: '#f59e0b'
         });
         <?php endif; ?>

         // SweetAlert for Success
         <?php if (isset($_SESSION['otp_verified'])): ?>
         Swal.fire({
             icon: 'success',
             title: 'Verified!',
             text: 'Identity verified successfully. Redirecting...',
             showConfirmButton: false,
             timer: 1500
         }).then(() => {
             window.location.href = 'dashboard.php';
         });
         <?php unset($_SESSION['otp_verified']); ?>
         <?php endif; ?>
      </script>
   </body>
</html>