<?php
if (!function_exists('getSetting')) require_once __DIR__ . '/../includes/settings-helper.php';
$siteName = getSetting('site_name', 'Deutsche Bank Holdings Delaware');
$logo = getSetting('logo_path', 'logo.png');
$favicon = getSetting('favicon_path', 'logo.png');
$csrf = csrf_token();
?><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sign In — <?= htmlspecialchars($siteName) ?></title>
  <link rel="icon" type="image/png" href="../<?= htmlspecialchars($favicon) ?>">
  <meta name="theme-color" content="#033d75">
  <link rel="stylesheet" href="../plugin/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="../plugin/fontawesome/css/all.min.css">
  <link rel="stylesheet" href="../assets/css/landing.css">
  <style>
    .db-login-layout { display: grid; grid-template-columns: 1fr 480px; min-height: 100vh; }
    .db-login-visual { display: flex; flex-direction: column; justify-content: center; padding: 40px; position: relative; overflow: hidden; background-image: url('../assets/images/home/hero-banking-professional.jpg'); background-size: cover; background-position: center; }
    .db-login-visual::before { content: ''; position: absolute; inset: 0; background: linear-gradient(135deg, rgba(15,26,46,0.92) 0%, rgba(3,61,117,0.78) 100%); z-index: 1; }
    .db-login-visual-content { position: relative; z-index: 2; max-width: 480px; }
    .db-login-visual-content h2 { font-size: 2.5rem; font-weight: 700; color: #fff; margin-bottom: 16px; line-height: 1.15; }
    .db-login-visual-content p { font-size: 1.1rem; color: #ccc; line-height: 1.7; margin-bottom: 32px; }
    .db-login-benefit { display: flex; align-items: flex-start; gap: 12px; margin-bottom: 16px; }
    .db-login-benefit i { color: #28a745; font-size: 1.1rem; margin-top: 3px; }
    .db-login-benefit strong { display: block; color: #fff; font-size: 0.9rem; }
    .db-login-benefit span { color: #aaa; font-size: 0.85rem; }
    .db-login-form-side { display: flex; align-items: center; justify-content: center; padding: 32px; background: #fff; }
    .db-login-form-wrap { width: 100%; max-width: 420px; }
    .db-login-form-wrap img { height: 44px; display: block; margin: 0 auto 24px; }
    .db-login-form-wrap h2 { text-align: center; font-size: 1.5rem; margin-bottom: 8px; }
    .db-login-subtitle { text-align: center; font-size: 0.9rem; color: #888; margin-bottom: 32px; }
    .db-form-group { margin-bottom: 16px; }
    .db-form-label { display: block; font-size: 0.75rem; font-weight: 600; color: #555; margin-bottom: 4px; text-transform: uppercase; }
    .db-form-input { width: 100%; padding: 12px 14px; font-size: 0.9rem; border: 1.5px solid #ddd; border-radius: 6px; outline: none; box-sizing: border-box; }
    .db-form-input:focus { border-color: #033d75; box-shadow: 0 0 0 3px rgba(3,61,117,0.1); }
    .db-password-field { position: relative; }
    .db-password-field .toggle-password { position: absolute; right: 12px; top: 50%; transform: translateY(-50%); cursor: pointer; color: #aaa; background: none; border: none; }
    .db-login-back { text-align: center; font-size: 0.9rem; color: #888; margin-top: 20px; }
    .db-login-back a { color: #033d75; font-weight: 600; text-decoration: none; }
    @media (max-width: 900px) { .db-login-layout { grid-template-columns: 1fr; } .db-login-visual { display: none; } }
  </style>
</head>
<body>
<div class="db-login-layout">
  <div class="db-login-visual">
    <div class="db-login-visual-content">
      <h2>Welcome<br>back.</h2>
      <p>Sign in to access your accounts, manage transfers, pay bills, and stay in control of your finances.</p>
      <div class="db-login-benefit"><i class="fas fa-check-circle"></i><div><strong>Secure authentication</strong><span>Multi-factor protection keeps your account safe.</span></div></div>
      <div class="db-login-benefit"><i class="fas fa-check-circle"></i><div><strong>PIN-protected transactions</strong><span>Every transfer and payment is verified with your PIN.</span></div></div>
      <div class="db-login-benefit"><i class="fas fa-check-circle"></i><div><strong>Real-time alerts</strong><span>Stay informed about account activity as it happens.</span></div></div>
      <div class="db-login-benefit"><i class="fas fa-check-circle"></i><div><strong>24/7 support</strong><span>Help is available whenever you need it.</span></div></div>
    </div>
  </div>
  <div class="db-login-form-side">
    <div class="db-login-form-wrap">
      <a href="../index"><img src="../<?= htmlspecialchars($logo) ?>" alt="<?= htmlspecialchars($siteName) ?>"></a>
      <h2>Sign In</h2>
      <p class="db-login-subtitle">Access your secure banking dashboard.</p>
      <form method="POST" id="login-form" onsubmit="return false;">
        <input type="hidden" name="timezone" id="timezone" value="">
        <div class="db-form-group">
          <label class="db-form-label">Email Address or Account Number</label>
          <input type="text" class="db-form-input" name="id" id="id" placeholder="your@email.com or account number" required>
        </div>
        <div class="db-form-group">
          <label class="db-form-label">Password</label>
          <div class="db-password-field">
            <input type="password" class="db-form-input" name="pass" id="pass" placeholder="Enter your password" required>
            <button type="button" class="toggle-password" data-target="pass"><i class="fas fa-eye"></i></button>
          </div>
        </div>
        <button type="submit" id="login-btn" style="width:100%;padding:14px;font-size:1rem;background:#033d75;color:#fff;border:none;border-radius:6px;cursor:pointer;font-weight:600;">Sign In</button>
      </form>
      <p class="db-login-back">Don't have an account? <a href="register">Open an account</a></p>
    </div>
  </div>
</div>

<script src="../plugin/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
// Auto-detect user's timezone
(function(){
  var tz = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
  document.getElementById('timezone').value = tz;
})();
document.querySelectorAll('.toggle-password').forEach(function(btn){
  btn.addEventListener('click',function(){
    var i=document.getElementById(this.getAttribute('data-target'));
    i.type=i.type==='password'?'text':'password';
    this.querySelector('i').classList.toggle('fa-eye');
    this.querySelector('i').classList.toggle('fa-eye-slash');
  });
});

document.getElementById('login-btn').addEventListener('click',function(e){
  e.preventDefault();
  var btn=this, orig=btn.innerHTML;
  btn.innerHTML='<i class="fas fa-spinner fa-pulse"></i> Signing in…';
  btn.disabled=true;
  var id=document.getElementById('id').value.trim();
  var pass=document.getElementById('pass').value.trim();
  var timezone=document.getElementById('timezone').value;
  if(!id||!pass){Swal.fire({icon:'warning',title:'Missing Information',text:'Please enter your email/account number and password.'});btn.innerHTML=orig;btn.disabled=false;return;}
  $.ajax({type:'POST',url:'../apps/login/login.php',data:{id:id,pass:pass,timezone:timezone},
    success:function(d){
      btn.innerHTML=orig;btn.disabled=false;
      var r=d.trim();
      if(r==='pin_required'){showPinChallenge();}
      else if(r==='admin_otp'){showAdminOtpChallenge();}
      else if(r==='success'){Swal.fire({icon:'success',title:'Welcome Back',text:'Redirecting to your dashboard…',showConfirmButton:false,timer:1500}).then(function(){location.href='../dashboard/dashboard.php';});}
      else if(r==='incorrect'){Swal.fire({icon:'error',title:'Invalid Details',text:'Incorrect email or password.'});}
      else if(r==='notexist'){Swal.fire({icon:'error',title:'Account Not Found',text:'No account with that email or account number.'});}
      else if(r==='suspended'){Swal.fire({icon:'error',title:'Account Suspended',text:'Contact customer support.'});}
      else if(r==='inactive'){Swal.fire({icon:'warning',title:'Account Inactive',text:'Contact customer support.'});}
      else if(r==='terminated'){Swal.fire({icon:'error',title:'Account Terminated',text:'Contact customer care.'});}
      else if(r==='kyc'){Swal.fire({icon:'warning',title:'Verification Required',text:'Complete KYC to access your account.'}).then(function(){location.href='../dashboard/kyc.php';});}
      else if(r==='review'){Swal.fire({icon:'info',title:'Account Under Review',text:'Your account is being reviewed. You will be notified when approved.'});}
      else if(r==='step2'||r==='step3'){Swal.fire({icon:'info',title:'Registration Incomplete',text:'Please complete your registration to continue.'});}
      else if(r==='rate_limited'){Swal.fire({icon:'warning',title:'Too Many Attempts',text:'Please wait 15 minutes and try again.'});}
      else{Swal.fire({icon:'error',title:'Error',text:'Unexpected response: '+r});}
    },
    error:function(){btn.innerHTML=orig;btn.disabled=false;Swal.fire({icon:'error',title:'Connection Error',text:'Could not reach the server.'});}
  });
});

function showPinChallenge(){
  Swal.fire({
    title:"Enter PIN CODE",
    html:'<p style="font-size:0.9rem;color:#666;margin-bottom:1rem;">Enter your 4-digit  PIN to continue.</p>'+
      '<div style="display:flex;justify-content:center;gap:12px;flex-wrap:wrap;">'+
      '<input id="p1" maxlength="1" type="text" inputmode="numeric" pattern="[0-9]" class="swal2-input" style="width:52px;height:52px;text-align:center;font-size:1.3rem;border-radius:8px;" autofocus>'+
      '<input id="p2" maxlength="1" type="text" inputmode="numeric" pattern="[0-9]" class="swal2-input" style="width:52px;height:52px;text-align:center;font-size:1.3rem;border-radius:8px;">'+
      '<input id="p3" maxlength="1" type="text" inputmode="numeric" pattern="[0-9]" class="swal2-input" style="width:52px;height:52px;text-align:center;font-size:1.3rem;border-radius:8px;">'+
      '<input id="p4" maxlength="1" type="text" inputmode="numeric" pattern="[0-9]" class="swal2-input" style="width:52px;height:52px;text-align:center;font-size:1.3rem;border-radius:8px;">'+
      '</div>',
    showCancelButton:true,confirmButtonText:'Verify PIN',cancelButtonText:'Cancel',
    allowOutsideClick:false,
    didOpen:function(){
      var ins=document.querySelectorAll('#p1,#p2,#p3,#p4');
      ins.forEach(function(inp,i,all){
        inp.addEventListener('input',function(e){
          this.value=this.value.replace(/[^0-9]/g,'');
          if(this.value.length===1&&i<all.length-1)all[i+1].focus();
        });
        inp.addEventListener('keydown',function(e){if(e.key==='Backspace'&&this.value.length===0&&i>0)all[i-1].focus();});
      });
    },
    preConfirm:function(){
      var pin=document.getElementById('p1').value+document.getElementById('p2').value+document.getElementById('p3').value+document.getElementById('p4').value;
      if(pin.length!==4){Swal.showValidationMessage('Please enter all 4 digits');return false;}
      return pin;
    }
  }).then(function(result){
    if(result.isConfirmed){
      Swal.fire({title:'Verifying…',allowOutsideClick:false,showConfirmButton:false,willOpen:function(){Swal.showLoading();}});
      $.ajax({type:'POST',url:'../apps/user/checkpin.php',data:{pin:result.value,csrf_token:'<?= $csrf ?>'},
        success:function(d){
          var r=d.trim();
          if(r==='success'){
            Swal.fire({icon:'success',title:'Welcome Back',text:'Redirecting to your dashboard…',showConfirmButton:false,timer:1500}).then(function(){location.href='../dashboard/dashboard.php';});
          }else if(r==='otp_required'){
            Swal.close();
            showOtpChallenge();
          }else if(r==='admin_otp'){
            Swal.close();
            showAdminOtpChallenge();
          }else if(r==='suspended'){
            Swal.fire({icon:'error',title:'Account Suspended',text:'Contact customer support.'});
          }else if(r==='rate_limited'){
            Swal.fire({icon:'warning',title:'Too Many Attempts',text:'Too many failed PIN attempts. Please wait <?= RATE_LIMIT_SECONDS >= 60 ? "15 minutes" : RATE_LIMIT_SECONDS . " seconds" ?> and try again.'});
          }else{
            Swal.fire({icon:'error',title:'Incorrect PIN',text:'The transaction PIN you entered is incorrect. Please try again.'});
          }
        },
        error:function(){Swal.fire({icon:'error',title:'Connection Error',text:'Could not verify PIN.'});}
      });
    }
  });
}

function showOtpChallenge(){
  var otpExpiry = 600; // 10 minutes in seconds
  var otpTimer = null;
  var timerHtml = '<div id="otpTimer" style="text-align:center;color:#e74c3c;font-size:0.85rem;margin-bottom:0.5rem;"></div>';

  Swal.fire({
    title:"Additional Verification Required",
    html: timerHtml +
      '<p style="font-size:0.9rem;color:#666;margin-bottom:1rem;">A verification code has been sent to your email. Please enter the 6-digit code below to continue.</p>'+
      '<div style="display:flex;justify-content:center;gap:6px;flex-wrap:wrap;">'+
      '<input id="c1" maxlength="1" type="text" inputmode="numeric" pattern="[0-9]" class="swal2-input" style="width:42px;height:42px;text-align:center;font-size:1.1rem;border-radius:8px;" autofocus>'+
      '<input id="c2" maxlength="1" type="text" inputmode="numeric" pattern="[0-9]" class="swal2-input" style="width:42px;height:42px;text-align:center;font-size:1.1rem;border-radius:8px;">'+
      '<input id="c3" maxlength="1" type="text" inputmode="numeric" pattern="[0-9]" class="swal2-input" style="width:42px;height:42px;text-align:center;font-size:1.1rem;border-radius:8px;">'+
      '<input id="c4" maxlength="1" type="text" inputmode="numeric" pattern="[0-9]" class="swal2-input" style="width:42px;height:42px;text-align:center;font-size:1.1rem;border-radius:8px;">'+
      '<input id="c5" maxlength="1" type="text" inputmode="numeric" pattern="[0-9]" class="swal2-input" style="width:42px;height:42px;text-align:center;font-size:1.1rem;border-radius:8px;">'+
      '<input id="c6" maxlength="1" type="text" inputmode="numeric" pattern="[0-9]" class="swal2-input" style="width:42px;height:42px;text-align:center;font-size:1.1rem;border-radius:8px;">'+
      '</div>',
    showCancelButton:true,confirmButtonText:'Verify OTP',cancelButtonText:'Cancel',
    showDenyButton:true,denyButtonText:'Resend Code',
    allowOutsideClick:false,
    didOpen:function(){
      // Start countdown timer
      var remaining = otpExpiry;
      var el = document.getElementById('otpTimer');
      function updateTimer(){
        var m = Math.floor(remaining/60), s = remaining%60;
        el.textContent = 'Code expires in: '+m+':'+(s<10?'0':'')+s;
        if(remaining<=0){el.textContent='Code expired. Please request a new one.';Swal.close();}
        else remaining--;
      }
      updateTimer();
      otpTimer = setInterval(updateTimer, 1000);

      var ins=document.querySelectorAll('#c1,#c2,#c3,#c4,#c5,#c6');
      ins.forEach(function(inp,i,all){
        inp.addEventListener('input',function(e){
          this.value=this.value.replace(/[^0-9]/g,'');
          if(this.value.length===1&&i<all.length-1)all[i+1].focus();
        });
        inp.addEventListener('keydown',function(e){if(e.key==='Backspace'&&this.value.length===0&&i>0)all[i-1].focus();});
      });
      document.getElementById('c6').addEventListener('input',function(){if(this.value.length===1)setTimeout(function(){Swal.clickConfirm();},150);});
    },
    willClose:function(){if(otpTimer)clearInterval(otpTimer);},
    preConfirm:function(){return document.getElementById('c1').value+document.getElementById('c2').value+document.getElementById('c3').value+document.getElementById('c4').value+document.getElementById('c5').value+document.getElementById('c6').value;}
  }).then(function(result){
    if(result.isConfirmed){
      Swal.fire({title:'Verifying OTP…',allowOutsideClick:false,showConfirmButton:false,willOpen:function(){Swal.showLoading();}});
      $.ajax({type:'POST',url:'../apps/login/checkotp.php',data:{code:result.value,csrf_token:'<?= $csrf ?>'},
        success:function(d){
          var r = d.trim();
          if(r==='success'){Swal.fire({icon:'success',title:'Welcome Back',text:'Redirecting…',showConfirmButton:false,timer:1500}).then(function(){location.href='../dashboard/dashboard.php';});}
          else if(r==='admin_otp'){Swal.close();showAdminOtpChallenge();}
          else{Swal.fire({icon:'error',title:'Incorrect Code',text:'The code you entered is incorrect. Please try again.',showConfirmButton:true}).then(function(){showOtpChallenge();});}
        },
        error:function(){Swal.fire({icon:'error',title:'Connection Error',text:'Could not verify OTP.',showConfirmButton:true}).then(function(){showOtpChallenge();});}
      });
    }else if(result.isDenied){
      // Resend code — call checkpin.php to regenerate OTP
      Swal.fire({title:'Requesting new code…',allowOutsideClick:false,showConfirmButton:false,willOpen:function(){Swal.showLoading();}});
      $.ajax({type:'POST',url:'../apps/user/checkpin.php',data:{pin:'resend',csrf_token:'<?= $csrf ?>'},
        success:function(d){
          Swal.close();
          if(d.trim()==='otp_required'){showOtpChallenge();}
          else{Swal.fire({icon:'error',title:'Error',text:'Could not resend code. Please try again.',showConfirmButton:true});}
        },
        error:function(){Swal.close();Swal.fire({icon:'error',title:'Error',text:'Could not resend code.',showConfirmButton:true});}
      });
    }
  });
}

function showAdminOtpChallenge(){
  var otpExpiry = 600; // 10 minutes
  var otpTimer = null;
  var timerHtml = '<div id="adminOtpTimer" style="text-align:center;color:#e74c3c;font-size:0.85rem;margin-bottom:0.5rem;"></div>';

  Swal.fire({
    title:"Additional Verification Required",
    html: timerHtml +
      '<p style="font-size:0.9rem;color:#666;margin-bottom:1rem;">A verification code has been sent to your email. Please enter the 6-digit code below to continue.</p>'+
      '<div style="display:flex;justify-content:center;gap:6px;flex-wrap:wrap;">'+
      '<input id="a1" maxlength="1" type="text" inputmode="numeric" pattern="[0-9]" class="swal2-input" style="width:42px;height:42px;text-align:center;font-size:1.1rem;border-radius:8px;" autofocus>'+
      '<input id="a2" maxlength="1" type="text" inputmode="numeric" pattern="[0-9]" class="swal2-input" style="width:42px;height:42px;text-align:center;font-size:1.1rem;border-radius:8px;">'+
      '<input id="a3" maxlength="1" type="text" inputmode="numeric" pattern="[0-9]" class="swal2-input" style="width:42px;height:42px;text-align:center;font-size:1.1rem;border-radius:8px;">'+
      '<input id="a4" maxlength="1" type="text" inputmode="numeric" pattern="[0-9]" class="swal2-input" style="width:42px;height:42px;text-align:center;font-size:1.1rem;border-radius:8px;">'+
      '<input id="a5" maxlength="1" type="text" inputmode="numeric" pattern="[0-9]" class="swal2-input" style="width:42px;height:42px;text-align:center;font-size:1.1rem;border-radius:8px;">'+
      '<input id="a6" maxlength="1" type="text" inputmode="numeric" pattern="[0-9]" class="swal2-input" style="width:42px;height:42px;text-align:center;font-size:1.1rem;border-radius:8px;">'+
      '</div>',
    showCancelButton:true,confirmButtonText:'Verify',cancelButtonText:'Cancel',
    showDenyButton:true,denyButtonText:'Resend Code',
    allowOutsideClick:false,
    didOpen:function(){
      var remaining = otpExpiry;
      var el = document.getElementById('adminOtpTimer');
      function updateTimer(){
        var m = Math.floor(remaining/60), s = remaining%60;
        el.textContent = 'Code expires in: '+m+':'+(s<10?'0':'')+s;
        if(remaining<=0){el.textContent='Code expired. Please request a new one.';Swal.close();}
        else remaining--;
      }
      updateTimer();
      otpTimer = setInterval(updateTimer, 1000);

      var ins=document.querySelectorAll('#a1,#a2,#a3,#a4,#a5,#a6');
      ins.forEach(function(inp,i,all){
        inp.addEventListener('input',function(e){
          this.value=this.value.replace(/[^0-9]/g,'');
          if(this.value.length===1&&i<all.length-1)all[i+1].focus();
        });
        inp.addEventListener('keydown',function(e){if(e.key==='Backspace'&&this.value.length===0&&i>0)all[i-1].focus();});
      });
      document.getElementById('a6').addEventListener('input',function(){if(this.value.length===1)setTimeout(function(){Swal.clickConfirm();},150);});
    },
    willClose:function(){if(otpTimer)clearInterval(otpTimer);},
    preConfirm:function(){return document.getElementById('a1').value+document.getElementById('a2').value+document.getElementById('a3').value+document.getElementById('a4').value+document.getElementById('a5').value+document.getElementById('a6').value;}
  }).then(function(result){
    if(result.isConfirmed){
      Swal.fire({title:'Verifying…',allowOutsideClick:false,showConfirmButton:false,willOpen:function(){Swal.showLoading();}});
      $.ajax({type:'POST',url:'../apps/login/verify-admin-otp.php',data:{code:result.value,csrf_token:'<?= $csrf ?>'},
        success:function(d){
          if(d.trim()==='success'){Swal.fire({icon:'success',title:'Welcome Back',text:'Redirecting…',showConfirmButton:false,timer:1500}).then(function(){location.href='../dashboard/dashboard.php';});}
          else if(d.trim()==='expired'){Swal.fire({icon:'error',title:'Code Expired',text:'The verification code has expired. Please try again.',showConfirmButton:true});}
          else{Swal.fire({icon:'error',title:'Incorrect Code',text:'The code you entered is incorrect.',showConfirmButton:true}).then(function(){showAdminOtpChallenge();});}
        },
        error:function(){Swal.fire({icon:'error',title:'Connection Error',text:'Could not verify code.',showConfirmButton:true}).then(function(){showAdminOtpChallenge();});}
      });
    }else if(result.isDenied){
      // Resend admin OTP — regenerate via checkotp.php
      Swal.fire({title:'Requesting new admin code…',allowOutsideClick:false,showConfirmButton:false,willOpen:function(){Swal.showLoading();}});
      $.ajax({type:'POST',url:'../apps/login/checkotp.php',data:{code:'resend',csrf_token:'<?= $csrf ?>'},
        success:function(d){
          Swal.close();
          if(d.trim()==='admin_otp'){showAdminOtpChallenge();}
          else{Swal.fire({icon:'error',title:'Error',text:'Could not resend code.',showConfirmButton:true});}
        },
        error:function(){Swal.close();Swal.fire({icon:'error',title:'Error',text:'Could not resend code.',showConfirmButton:true});}
      });
    }
  });
}
</script>
</body>
</html>
