<?php
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/Mailer.php';

if (isLoggedIn()) redirect(ADMIN_URL . '/index.php');

// ═══════════════════════════════════════════════
//  ⚙️  SMTP CONFIG — Set your Gmail App Password
// ═══════════════════════════════════════════════
const SMTP_USER     = 'cyconsultancybd@gmail.com';
const SMTP_PASS     = 'YOUR_APP_PASSWORD_HERE';   // <-- 16-char Gmail App Password
const SMTP_FROM     = 'cyconsultancybd@gmail.com';
const SMTP_NAME     = 'CY Consultancy Admin';
// ═══════════════════════════════════════════════

$step  = $_SESSION['reset_step']  ?? 'email';
$email = $_SESSION['reset_email'] ?? '';
$msg   = '';
$error = '';

// Ensure OTP table
db()->query("CREATE TABLE IF NOT EXISTS admin_password_resets (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(100) NOT NULL,
    otp VARCHAR(6) NOT NULL,
    expires_at DATETIME NOT NULL,
    used TINYINT(1) DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

function makeMailer(): CYMailer {
    $m = new CYMailer();
    $m->username  = SMTP_USER;
    $m->password  = SMTP_PASS;
    $m->fromEmail = SMTP_FROM;
    $m->fromName  = SMTP_NAME;
    return $m;
}

function sendOtp(string $toEmail, string $toName, string $otp): array {
    $subject = 'CY Admin — Password Reset OTP';
    $html = "
    <div style='font-family:Arial,sans-serif;max-width:480px;margin:0 auto;background:#f8fafc;padding:32px;border-radius:12px;'>
      <div style='background:linear-gradient(135deg,#1a56db,#1e3a8a);border-radius:10px;padding:24px;text-align:center;margin-bottom:24px;'>
        <h2 style='color:#fff;margin:0;font-size:20px;'>CY Consultancy Centre</h2>
        <p style='color:#bfdbfe;margin:6px 0 0;font-size:13px;'>Admin Panel — Password Reset</p>
      </div>
      <p style='color:#374151;font-size:14px;'>Dear <strong>{$toName}</strong>,</p>
      <p style='color:#374151;font-size:14px;'>Your one-time password (OTP) for admin password reset:</p>
      <div style='background:#fff;border:2px dashed #1a56db;border-radius:12px;padding:20px;text-align:center;margin:20px 0;'>
        <span style='font-size:40px;font-weight:800;letter-spacing:12px;color:#1a56db;'>{$otp}</span>
      </div>
      <p style='color:#6b7280;font-size:13px;'>⏱ Valid for <strong>10 minutes</strong>. Do not share this OTP with anyone.</p>
      <p style='color:#9ca3af;font-size:11px;margin-top:24px;border-top:1px solid #e5e7eb;padding-top:16px;'>
        If you did not request this, please ignore this email.<br>
        — CY Consultancy Centre Admin System
      </p>
    </div>";

    $text = "Dear {$toName},\n\nYour OTP for password reset: {$otp}\n\nValid for 10 minutes.\n\n— CY Consultancy Admin";

    $m = makeMailer();
    $ok = $m->send($toEmail, $toName, $subject, $html, $text);
    return ['ok' => $ok, 'error' => $m->lastError];
}

// ── STEP 1: Email submit ─────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['step_email'])) {
    $inputEmail = strtolower(trim($_POST['email'] ?? ''));
    $st = db()->prepare("SELECT * FROM admin_users WHERE email=? LIMIT 1");
    $st->bind_param('s', $inputEmail);
    $st->execute();
    $user = $st->get_result()->fetch_assoc();

    if (!$user) {
        $error = 'No admin account found with this email address.';
    } else {
        $otp     = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
        $expires = date('Y-m-d H:i:s', strtotime('+10 minutes'));
        $esc     = db()->real_escape_string($inputEmail);
        db()->query("UPDATE admin_password_resets SET used=1 WHERE email='{$esc}'");
        $ins = db()->prepare("INSERT INTO admin_password_resets (email, otp, expires_at) VALUES (?,?,?)");
        $ins->bind_param('sss', $inputEmail, $otp, $expires);
        $ins->execute();

        $result = sendOtp($inputEmail, $user['full_name'] ?? 'Admin', $otp);
        if ($result['ok']) {
            $_SESSION['reset_step']  = 'otp';
            $_SESSION['reset_email'] = $inputEmail;
            $step  = 'otp';
            $email = $inputEmail;
            $msg   = 'OTP sent successfully! Check your inbox (and spam folder).';
        } else {
            // Dev fallback: show OTP on screen if SMTP not configured
            $isDefault = (SMTP_PASS === 'YOUR_APP_PASSWORD_HERE');
            if ($isDefault) {
                $_SESSION['reset_step']  = 'otp';
                $_SESSION['reset_email'] = $inputEmail;
                $_SESSION['dev_otp']     = $otp;
                $step  = 'otp';
                $email = $inputEmail;
                $msg   = "⚙️ SMTP not configured. Dev mode OTP: <strong style='font-size:22px;letter-spacing:4px;color:#1a56db'>{$otp}</strong>";
            } else {
                $error = 'Email send failed: ' . $result['error'];
            }
        }
    }
}

// ── STEP 2: OTP verify ───────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['step_otp'])) {
    $inputOtp = trim($_POST['otp'] ?? '');
    $st = db()->prepare("SELECT * FROM admin_password_resets WHERE email=? AND otp=? AND used=0 AND expires_at > NOW() ORDER BY id DESC LIMIT 1");
    $st->bind_param('ss', $email, $inputOtp);
    $st->execute();
    $row = $st->get_result()->fetch_assoc();
    if (!$row) {
        $error = 'Invalid or expired OTP. Please try again.';
        $step  = 'otp';
    } else {
        $_SESSION['reset_step']   = 'newpass';
        $_SESSION['reset_otp_id'] = $row['id'];
        unset($_SESSION['dev_otp']);
        $step = 'newpass';
    }
}

// ── STEP 3: New password ─────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['step_newpass'])) {
    $pass1 = $_POST['password']  ?? '';
    $pass2 = $_POST['password2'] ?? '';
    $otpId = (int)($_SESSION['reset_otp_id'] ?? 0);
    if (strlen($pass1) < 6) {
        $error = 'Password must be at least 6 characters.';
        $step  = 'newpass';
    } elseif ($pass1 !== $pass2) {
        $error = 'Passwords do not match.';
        $step  = 'newpass';
    } else {
        $hash = password_hash($pass1, PASSWORD_DEFAULT);
        $upd  = db()->prepare("UPDATE admin_users SET password=? WHERE email=?");
        $upd->bind_param('ss', $hash, $email);
        $upd->execute();
        db()->query("UPDATE admin_password_resets SET used=1 WHERE id={$otpId}");
        unset($_SESSION['reset_step'], $_SESSION['reset_email'], $_SESSION['reset_otp_id']);
        $step = 'done';
    }
}

// ── Resend → back to email ───────────────────────────────────────
if (isset($_POST['resend_otp'])) {
    unset($_SESSION['reset_step'], $_SESSION['reset_email'], $_SESSION['reset_otp_id'], $_SESSION['dev_otp']);
    $step = 'email'; $email = '';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Reset Password — CY Consultancy Admin</title>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700;800&family=Playfair+Display:wght@700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
:root{
  --brand:#1a56db;--brand2:#1e3a8a;
  --text:#fff;--muted:rgba(255,255,255,0.6);
  --border:rgba(255,255,255,0.15);
  --input-bg:rgba(255,255,255,0.08);
  --danger:#f87171;--success:#34d399;
}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
body{
  font-family:'Outfit',sans-serif;min-height:100vh;
  display:flex;align-items:center;justify-content:center;
  background:#050d1a;position:relative;overflow:hidden;
}
/* ── BG ── */
.bg{position:absolute;inset:0;z-index:0;}
.bg-img{
  position:absolute;inset:0;
  background:
    radial-gradient(ellipse 100% 80% at 0% 0%,   rgba(26,86,219,0.35) 0%,transparent 55%),
    radial-gradient(ellipse 80% 100% at 100% 100%,rgba(30,58,138,0.4)  0%,transparent 55%),
    radial-gradient(ellipse 60% 60% at 50% 50%,  rgba(99,102,241,0.08) 0%,transparent 70%);
}
.bg-grid{
  position:absolute;inset:0;
  background-image:
    linear-gradient(rgba(255,255,255,0.03) 1px,transparent 1px),
    linear-gradient(90deg,rgba(255,255,255,0.03) 1px,transparent 1px);
  background-size:50px 50px;
}
.orb{position:absolute;border-radius:50%;filter:blur(90px);animation:pulse 6s ease-in-out infinite;}
.orb1{width:500px;height:500px;top:-150px;left:-150px;background:rgba(26,86,219,0.2);animation-delay:0s;}
.orb2{width:400px;height:400px;bottom:-100px;right:-100px;background:rgba(99,102,241,0.15);animation-delay:-3s;}
@keyframes pulse{0%,100%{transform:scale(1);}50%{transform:scale(1.1);}}

/* ── WRAP ── */
.wrap{position:relative;z-index:10;width:100%;max-width:440px;padding:24px;
  animation:up .55s cubic-bezier(.22,1,.36,1) both;}
@keyframes up{from{opacity:0;transform:translateY(30px);}to{opacity:1;transform:none;}}

.tag{text-align:center;margin-bottom:20px;}
.tag span{
  background:rgba(26,86,219,0.2);border:1px solid rgba(26,86,219,0.4);
  color:#93c5fd;font-size:10.5px;font-weight:700;letter-spacing:.14em;
  text-transform:uppercase;padding:5px 16px;border-radius:20px;
  backdrop-filter:blur(10px);
}

/* ── GLASS CARD ── */
.card{
  background:rgba(255,255,255,0.07);
  backdrop-filter:blur(24px) saturate(180%);
  -webkit-backdrop-filter:blur(24px) saturate(180%);
  border:1px solid rgba(255,255,255,0.12);
  border-radius:24px;
  padding:36px 34px 30px;
  box-shadow:
    0 8px 32px rgba(0,0,0,0.4),
    inset 0 1px 0 rgba(255,255,255,0.1);
}

/* ── BRAND ── */
.brand{display:flex;align-items:center;gap:12px;margin-bottom:24px;padding-bottom:20px;border-bottom:1px solid var(--border);}
.b-logo{width:44px;height:44px;object-fit:contain;flex-shrink:0;border-radius:10px;}
.b-fall{width:44px;height:44px;background:linear-gradient(135deg,var(--brand),var(--brand2));
  border-radius:12px;display:none;align-items:center;justify-content:center;
  font-family:'Playfair Display',serif;font-size:17px;font-weight:800;color:#fff;flex-shrink:0;}
.b-text h1{font-family:'Playfair Display',serif;font-size:16px;font-weight:700;color:#fff;}
.b-text p{font-size:11px;color:var(--muted);margin-top:2px;}

/* ── STEPS ── */
.steps{display:flex;align-items:center;margin-bottom:22px;}
.sd{width:26px;height:26px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;flex-shrink:0;transition:all .3s;}
.sd.done{background:var(--brand);color:#fff;}
.sd.active{background:var(--brand);color:#fff;box-shadow:0 0 0 4px rgba(26,86,219,0.25);}
.sd.idle{background:rgba(255,255,255,0.1);color:rgba(255,255,255,0.4);border:1.5px solid rgba(255,255,255,0.15);}
.sl{flex:1;height:1.5px;background:rgba(255,255,255,0.1);}
.sl.done{background:var(--brand);}

/* ── ALERTS ── */
.alert{border-radius:10px;padding:11px 14px;font-size:13px;font-weight:500;
  display:flex;align-items:flex-start;gap:8px;margin-bottom:16px;line-height:1.5;}
.alert i{flex-shrink:0;margin-top:1px;}
.alert-err{background:rgba(248,113,113,0.12);color:#fca5a5;border:1px solid rgba(248,113,113,0.3);}
.alert-ok {background:rgba(52,211,153,0.12);color:#6ee7b7;border:1px solid rgba(52,211,153,0.25);}

/* ── TITLE ── */
.title{margin-bottom:20px;}
.title .ico{font-size:28px;margin-bottom:8px;}
.title h2{font-size:20px;font-weight:700;color:#fff;}
.title p{font-size:13px;color:var(--muted);margin-top:4px;line-height:1.5;}
.title .em{color:#93c5fd;font-weight:600;}

/* ── FORM ── */
.fg{margin-bottom:14px;}
.fl{display:block;font-size:12px;font-weight:600;color:rgba(255,255,255,0.7);margin-bottom:6px;letter-spacing:.03em;}
.iw{position:relative;}
.iw .fi{position:absolute;left:13px;top:50%;transform:translateY(-50%);color:rgba(255,255,255,0.3);font-size:13px;pointer-events:none;z-index:1;}
.fi-input{
  width:100%;padding:11px 14px 11px 38px;
  background:var(--input-bg);
  border:1.5px solid rgba(255,255,255,0.1);
  border-radius:11px;
  font-size:14px;font-family:'Outfit',sans-serif;
  color:#fff;outline:none;
  transition:border-color .15s,box-shadow .15s,background .15s;
}
.fi-input::placeholder{color:rgba(255,255,255,0.25);}
.fi-input:focus{
  border-color:rgba(26,86,219,0.7);
  background:rgba(26,86,219,0.12);
  box-shadow:0 0 0 3px rgba(26,86,219,0.15);
}
/* OTP special */
.otp-inp{
  text-align:center;font-size:32px;font-weight:800;
  letter-spacing:.4em;padding:16px 14px;
  border-radius:14px;
}
.eye{position:absolute;right:11px;top:50%;transform:translateY(-50%);
  background:none;border:none;cursor:pointer;color:rgba(255,255,255,0.3);
  font-size:14px;padding:4px;z-index:2;transition:color .15s;}
.eye:hover{color:rgba(255,255,255,0.7);}

/* ── BUTTONS ── */
.btn{
  width:100%;padding:13px;border:none;border-radius:11px;
  font-size:15px;font-weight:700;font-family:'Outfit',sans-serif;
  cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;
  margin-top:6px;transition:opacity .15s,transform .15s;
}
.btn-p{
  background:linear-gradient(135deg,var(--brand),var(--brand2));
  color:#fff;box-shadow:0 6px 20px rgba(26,86,219,0.35);
}
.btn-p:hover{opacity:.9;transform:translateY(-1px);}
.btn-link{
  background:none;border:none;color:rgba(255,255,255,0.45);
  font-size:12.5px;font-weight:500;cursor:pointer;
  font-family:'Outfit',sans-serif;
  padding:10px;text-decoration:underline;
  display:block;margin:10px auto 0;
  transition:color .15s;
}
.btn-link:hover{color:rgba(255,255,255,0.8);}
.back{
  display:flex;align-items:center;justify-content:center;gap:6px;
  color:rgba(255,255,255,0.35);font-size:12.5px;text-decoration:none;
  margin-top:18px;transition:color .15s;
}
.back:hover{color:rgba(255,255,255,0.7);}

/* ── DONE ── */
.done-w{text-align:center;padding:8px 0;}
.done-ico{width:68px;height:68px;border-radius:50%;
  background:rgba(52,211,153,0.15);border:2px solid rgba(52,211,153,0.3);
  display:flex;align-items:center;justify-content:center;font-size:28px;
  margin:0 auto 16px;}
.done-w h2{font-size:22px;font-weight:700;color:#fff;margin-bottom:8px;}
.done-w p{font-size:13px;color:var(--muted);line-height:1.6;margin-bottom:22px;}

/* ── FOOTER ── */
.ft{text-align:center;margin-top:18px;font-size:11px;color:rgba(255,255,255,0.2);}
.ft a{color:rgba(147,197,253,0.5);text-decoration:none;}
.ft a:hover{color:#93c5fd;}

@media(max-width:480px){.card{padding:28px 20px 24px;}.wrap{padding:16px;}}
</style>
</head>
<body>
<div class="bg">
  <div class="bg-img"></div>
  <div class="bg-grid"></div>
  <div class="orb orb1"></div>
  <div class="orb orb2"></div>
</div>

<div class="wrap">
  <div class="tag"><span><i class="fas fa-key"></i> &nbsp;Password Reset</span></div>

  <div class="card">
    <!-- Brand -->
    <div class="brand">
      <img src="<?=e(SITE_URL)?>/assets/images/cyconsultancy.png" class="b-logo"
        onerror="this.style.display='none';document.getElementById('bf').style.display='flex';">
      <div class="b-fall" id="bf">CY</div>
      <div class="b-text">
        <h1>CY Consultancy Centre</h1>
        <p>Admin Password Reset</p>
      </div>
    </div>

    <?php if ($step !== 'done'): ?>
    <!-- Progress -->
    <div class="steps">
      <div class="sd <?=in_array($step,['otp','newpass'])?'done':'active'?>">
        <?=in_array($step,['otp','newpass'])?'<i class="fas fa-check" style="font-size:10px"></i>':'1'?>
      </div>
      <div class="sl <?=in_array($step,['otp','newpass'])?'done':''?>"></div>
      <div class="sd <?=$step==='otp'?'active':($step==='newpass'?'done':'idle')?>">
        <?=$step==='newpass'?'<i class="fas fa-check" style="font-size:10px"></i>':'2'?>
      </div>
      <div class="sl <?=$step==='newpass'?'done':''?>"></div>
      <div class="sd <?=$step==='newpass'?'active':'idle'?>">3</div>
    </div>
    <?php endif; ?>

    <?php if($error):?><div class="alert alert-err"><i class="fas fa-circle-exclamation"></i><span><?=e($error)?></span></div><?php endif;?>
    <?php if($msg):?><div class="alert alert-ok"><i class="fas fa-circle-check"></i><span><?=$msg?></span></div><?php endif;?>

    <?php if($step==='email'): ?>
    <!-- ── Step 1 ── -->
    <div class="title">
      <div class="ico">📧</div>
      <h2>Forgot Password?</h2>
      <p>Enter your admin email address. We'll send a 6-digit OTP.</p>
    </div>
    <form method="POST">
      <div class="fg">
        <label class="fl">Admin Email Address</label>
        <div class="iw">
          <i class="fas fa-envelope fi"></i>
          <input type="email" name="email" class="fi-input"
            placeholder="cyconsultancybd@gmail.com"
            value="<?=e($_POST['email']??'')?>" required autofocus>
        </div>
      </div>
      <button type="submit" name="step_email" class="btn btn-p">
        <i class="fas fa-paper-plane"></i> Send OTP
      </button>
    </form>

    <?php elseif($step==='otp'): ?>
    <!-- ── Step 2 ── -->
    <div class="title">
      <div class="ico">🔢</div>
      <h2>Enter OTP</h2>
      <p>6-digit code sent to <span class="em"><?=e($email)?></span><br>Valid for 10 minutes.</p>
    </div>
    <form method="POST">
      <div class="fg">
        <label class="fl">6-Digit OTP Code</label>
        <div class="iw">
          <input type="text" name="otp" class="fi-input otp-inp"
            placeholder="——————" maxlength="6" pattern="\d{6}"
            inputmode="numeric" required autofocus autocomplete="one-time-code">
        </div>
      </div>
      <button type="submit" name="step_otp" class="btn btn-p">
        <i class="fas fa-shield-halved"></i> Verify OTP
      </button>
    </form>
    <form method="POST">
      <button type="submit" name="resend_otp" class="btn-link">
        ↩ Didn't receive it? Send again
      </button>
    </form>

    <?php elseif($step==='newpass'): ?>
    <!-- ── Step 3 ── -->
    <div class="title">
      <div class="ico">🔐</div>
      <h2>Set New Password</h2>
      <p>OTP verified! Create a strong new password.</p>
    </div>
    <form method="POST">
      <div class="fg">
        <label class="fl">New Password</label>
        <div class="iw">
          <i class="fas fa-lock fi"></i>
          <input type="password" id="p1" name="password" class="fi-input"
            placeholder="Minimum 6 characters" required autofocus>
          <button type="button" class="eye" onclick="tp('p1','e1')">
            <i class="fas fa-eye" id="e1"></i>
          </button>
        </div>
      </div>
      <div class="fg">
        <label class="fl">Confirm New Password</label>
        <div class="iw">
          <i class="fas fa-lock fi"></i>
          <input type="password" id="p2" name="password2" class="fi-input"
            placeholder="Repeat password" required>
          <button type="button" class="eye" onclick="tp('p2','e2')">
            <i class="fas fa-eye" id="e2"></i>
          </button>
        </div>
      </div>
      <button type="submit" name="step_newpass" class="btn btn-p">
        <i class="fas fa-check"></i> Update Password
      </button>
    </form>

    <?php elseif($step==='done'): ?>
    <!-- ── Done ── -->
    <div class="done-w">
      <div class="done-ico">✅</div>
      <h2>Password Updated!</h2>
      <p>Your admin password has been reset.<br>You can now login with the new password.</p>
      <a href="<?=e(ADMIN_URL)?>/login.php" class="btn btn-p" style="text-decoration:none;max-width:260px;margin:0 auto;">
        <i class="fas fa-right-to-bracket"></i> Go to Login
      </a>
    </div>
    <?php endif; ?>

    <?php if($step!=='done'): ?>
    <a href="<?=e(ADMIN_URL)?>/login.php" class="back">
      <i class="fas fa-arrow-left"></i> Back to Login
    </a>
    <?php endif; ?>
  </div>

  <div class="ft">&copy; <?=date('Y')?> CY Consultancy Centre &nbsp;·&nbsp; <a href="<?=e(SITE_URL)?>">Website</a></div>
</div>

<script>
function tp(id,ic){
  const i=document.getElementById(id),e=document.getElementById(ic);
  i.type=i.type==='password'?'text':'password';
  e.className=i.type==='password'?'fas fa-eye':'fas fa-eye-slash';
}
const otp=document.querySelector('.otp-inp');
if(otp){
  otp.addEventListener('input',function(){
    this.value=this.value.replace(/\D/g,'');
    if(this.value.length===6)this.closest('form').submit();
  });
}
</script>
</body>
</html>
