<?php
require_once 'includes/config.php';
require_once 'includes/mailer.php';
require_once 'includes/device_security.php';

// Create OTP table
$db = getDB();
try {
    $db->exec("CREATE TABLE IF NOT EXISTS device_reset_otp (
        id INT AUTO_INCREMENT PRIMARY KEY,
        email VARCHAR(200) NOT NULL,
        user_id INT NOT NULL,
        otp VARCHAR(10) NOT NULL,
        expires_at TIMESTAMP NOT NULL,
        used TINYINT(1) DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
} catch(Exception $e) {}

$step   = $_GET['step'] ?? 'email'; // email, otp, done
$error  = '';
$success = '';
$email  = '';

// Step 1: Send OTP
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_otp'])) {
    $email = sanitize($_POST['email'] ?? '');
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'সঠিক Gmail/Email দিন।';
    } else {
        // Find user by email
        $u = $db->prepare("SELECT * FROM users WHERE email=? AND status='active'");
        $u->execute([$email]); $user = $u->fetch();
        if (!$user) {
            $error = 'এই email দিয়ে কোনো account নেই।';
        } else {
            // Delete old OTPs
            $db->prepare("DELETE FROM device_reset_otp WHERE email=?")->execute([$email]);
            // Generate OTP
            $otp = str_pad(random_int(0,999999), 6, '0', STR_PAD_LEFT);
            $db->prepare("INSERT INTO device_reset_otp (email,user_id,otp,expires_at) VALUES (?,?,?,DATE_ADD(NOW(),INTERVAL 10 MINUTE))")
               ->execute([$email,$user['id'],$otp]);
            // Send email
            $result = sendOTPEmail($email, $otp, $user['name']);
            if ($result['ok']) {
                header('Location: device-reset.php?step=otp&e='.urlencode($email)); exit;
            } else {
                $error = 'Email পাঠাতে সমস্যা: '.$result['message'];
                // Clean up
                $db->prepare("DELETE FROM device_reset_otp WHERE email=?")->execute([$email]);
            }
        }
    }
}

// Step 2: Verify OTP
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_otp'])) {
    $email  = sanitize($_POST['email'] ?? '');
    $otp    = sanitize($_POST['otp']   ?? '');
    $step   = 'otp';

    $row = $db->prepare("SELECT * FROM device_reset_otp WHERE email=? AND otp=? AND used=0 AND expires_at > NOW()");
    $row->execute([$email,$otp]); $row=$row->fetch();

    if (!$row) {
        $error = 'OTP ভুল বা মেয়াদ শেষ হয়ে গেছে।';
    } else {
        // Reset all devices for this user
        $db->prepare("DELETE FROM user_devices WHERE user_id=?")->execute([$row['user_id']]);
        $db->prepare("UPDATE device_reset_otp SET used=1 WHERE id=?")->execute([$row['id']]);
        // Log user out (clear sessions)
        header('Location: device-reset.php?step=done'); exit;
    }
}

$emailParam = sanitize($_GET['e'] ?? '');
if($step==='otp' && $emailParam) $email = $emailParam;
$whatsapp = getSetting('whatsapp_number') ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
<title>Device Reset — <?= SITE_NAME ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
*{margin:0;padding:0;box-sizing:border-box;-webkit-tap-highlight-color:transparent}
body{font-family:'Segoe UI',sans-serif;background:linear-gradient(135deg,#0d1f4e,#1a3c8f,#2856c8);min-height:100vh;display:flex;align-items:center;justify-content:center;padding:20px}
.card{background:white;border-radius:24px;padding:36px 30px;width:100%;max-width:380px;box-shadow:0 25px 60px rgba(0,0,0,0.3)}
.logo{text-align:center;margin-bottom:28px}
.logo-icon{width:70px;height:70px;background:linear-gradient(135deg,#0d1f4e,#1a3c8f);border-radius:20px;display:flex;align-items:center;justify-content:center;margin:0 auto 14px;font-size:28px}
.logo h1{font-size:22px;font-weight:800;color:#0d1f4e}
.logo p{font-size:13px;color:#888;margin-top:4px}
.step-title{font-size:17px;font-weight:800;color:#1a1a2e;margin-bottom:6px;text-align:center}
.step-sub{font-size:13px;color:#888;text-align:center;margin-bottom:24px;line-height:1.6}
.alert-err{background:#fff5f5;color:#c53030;border:1px solid #fed7d7;padding:11px 14px;border-radius:10px;font-size:13px;font-weight:600;margin-bottom:16px;display:flex;align-items:center;gap:8px}
.fg{margin-bottom:14px}
.fg label{font-size:12px;font-weight:700;color:#555;text-transform:uppercase;letter-spacing:0.4px;display:block;margin-bottom:6px}
.inp{width:100%;padding:13px 14px;border:2px solid #e8ecf4;border-radius:12px;font-size:15px;outline:none;transition:0.2s}
.inp:focus{border-color:#1a3c8f;box-shadow:0 0 0 3px rgba(26,60,143,0.1)}
.inp-otp{text-align:center;font-size:28px;font-weight:800;letter-spacing:10px;font-family:monospace}
.btn{width:100%;padding:14px;background:linear-gradient(135deg,#1a3c8f,#2856c8);color:white;border:none;border-radius:12px;font-size:15px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px}
.step-bar{display:flex;gap:8px;margin-bottom:24px}
.step-dot{flex:1;height:4px;border-radius:2px;background:#f0f0f0}
.step-dot.done{background:#1a3c8f}
.back-link{text-align:center;margin-top:16px;font-size:13px}
.back-link a{color:#1a3c8f;font-weight:600;text-decoration:none}
.success-icon{width:80px;height:80px;background:#f0fff4;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 16px;font-size:36px}
</style>
</head>
<body>
<div class="card">
    <div class="logo">
        <div class="logo-icon">🔓</div>
        <h1><?= SITE_NAME ?></h1>
        <p>Device Reset</p>
    </div>

    <!-- Step bar -->
    <?php if($step !== 'done'): ?>
    <div class="step-bar">
        <div class="step-dot done"></div>
        <div class="step-dot <?= $step==='otp'||$step==='done'?'done':'' ?>"></div>
        <div class="step-dot <?= $step==='done'?'done':'' ?>"></div>
    </div>
    <?php endif; ?>

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

    <?php if($step === 'email'): ?>
    <!-- Step 1: Email input -->
    <div class="step-title">📧 Email দিন</div>
    <div class="step-sub">আপনার account এ registered email টি দিন। সেখানে OTP পাঠানো হবে।</div>
    <form method="POST">
        <div class="fg">
            <label>Email Address</label>
            <input type="email" name="email" class="inp" placeholder="yourname@gmail.com" required autofocus>
        </div>
        <button type="submit" name="send_otp" class="btn">
            <i class="fas fa-paper-plane"></i> OTP পাঠান
        </button>
    </form>

    <?php elseif($step === 'otp'): ?>
    <!-- Step 2: OTP verify -->
    <div class="step-title">🔐 OTP দিন</div>
    <div class="step-sub"><b><?= htmlspecialchars($email) ?></b> এ একটি ৬ সংখ্যার OTP পাঠানো হয়েছে।<br>১০ মিনিটের মধ্যে দিন।</div>
    <form method="POST">
        <input type="hidden" name="email" value="<?= htmlspecialchars($email) ?>">
        <div class="fg">
            <label>OTP Code</label>
            <input type="text" name="otp" class="inp inp-otp" placeholder="000000" maxlength="6" pattern="[0-9]{6}" required autofocus inputmode="numeric">
        </div>
        <button type="submit" name="verify_otp" class="btn">
            <i class="fas fa-check-circle"></i> Verify করুন
        </button>
    </form>
    <div class="back-link">
        <a href="device-reset.php">← অন্য email দিয়ে চেষ্টা করুন</a>
    </div>

    <?php elseif($step === 'done'): ?>
    <!-- Step 3: Done -->
    <div style="text-align:center">
        <div class="success-icon">✅</div>
        <div class="step-title" style="color:#276749">সফলভাবে Reset হয়েছে!</div>
        <div class="step-sub">আপনার সব ডিভাইস remove করা হয়েছে।<br>এখন নতুনভাবে login করুন।</div>
        <a href="login.php" class="btn" style="text-decoration:none;margin-top:8px">
            <i class="fas fa-sign-in-alt"></i> Login করুন
        </a>
    </div>
    <?php endif; ?>

    <?php if($whatsapp && $step==='email'): ?>
    <div style="margin-top:20px;text-align:center">
        <div style="font-size:12px;color:#aaa;margin-bottom:8px">অথবা সরাসরি যোগাযোগ করুন</div>
        <a href="https://wa.me/<?= preg_replace('/[^0-9]/','',$whatsapp) ?>" target="_blank"
           style="display:inline-flex;align-items:center;gap:8px;background:#25D366;color:white;padding:10px 20px;border-radius:50px;font-size:13px;font-weight:700;text-decoration:none">
            <i class="fab fa-whatsapp" style="font-size:16px"></i> WhatsApp
        </a>
    </div>
    <?php endif; ?>
</div>
</body>
</html>
