<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once '../config.php';

$step = 'request'; // request, otp_sent, reset
$message = '';
$error = '';
$mobile = '';

// Generate OTP
function generateOTP() {
    return str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT);
}

// Send OTP via email (using PHP mail) or SMS
function sendOTP($patient, $otp) {
    // Try email first
    if (!empty($patient['email'])) {
        $subject = "Your OTP for password reset - " . ($GLOBALS['brand']['name'] ?? 'ওয়ান হোমিওপ্যাথি');
        $message = "Dear {$patient['name']},\n\nYour OTP for password reset is: $otp\n\nThis OTP is valid for 10 minutes.\n\nIf you did not request this, please ignore.\n\nThank you.";
        $headers = "From: noreply@drmdferdous.com\r\n";
        if (mail($patient['email'], $subject, $message, $headers)) {
            return 'email';
        }
    }
    // Fallback to SMS
    if (function_exists('sendSMSViaBulkSMSBD')) {
        $sms_msg = "Your OTP for password reset: $otp. Valid for 10 minutes.";
        sendSMSViaBulkSMSBD($patient['mobile'], $sms_msg);
        return 'sms';
    }
    return false;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $mobile = trim($_POST['mobile'] ?? '');
    if (empty($mobile)) {
        $error = 'মোবাইল নম্বর দিন';
    } else {
        $mobile_esc = $conn->real_escape_string($mobile);
        $patient = $conn->query("SELECT * FROM opd_patients WHERE mobile = '$mobile_esc'")->fetch_assoc();
        if (!$patient) {
            $error = 'এই মোবাইল নম্বরের কোনো অ্যাকাউন্ট নেই';
        } else {
            // Generate and save OTP
            $otp = generateOTP();
            $expiry = date('Y-m-d H:i:s', strtotime('+10 minutes'));
            $conn->query("UPDATE opd_patients SET otp = '$otp', otp_expiry = '$expiry' WHERE id = {$patient['id']}");
            
            // Send OTP
            $sent = sendOTP($patient, $otp);
            if ($sent) {
                $_SESSION['reset_patient_id'] = $patient['id'];
                $_SESSION['reset_mobile'] = $patient['mobile'];
                $step = 'otp_sent';
                $message = "আপনার মোবাইল/ইমেইলে একটি OTP পাঠানো হয়েছে। দয়া করে যাচাই করুন।";
            } else {
                $error = 'OTP পাঠাতে ব্যর্থ হয়েছে। আবার চেষ্টা করুন।';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>পাসওয়ার্ড রিসেট | <?= htmlspecialchars($brand['name'] ?? 'ওয়ান হোমিওপ্যাথি') ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body{background:linear-gradient(135deg,#1b4332,#2d6a4f,#40916c);min-height:100vh;display:flex;align-items:center;justify-content:center;font-family:sans-serif}
        .box{background:#fff;border-radius:20px;padding:40px;box-shadow:0 20px 60px rgba(0,0,0,.3);max-width:400px;width:100%;animation:fadeInUp 0.6s ease}
        .btn-primary{background:#2d6a4f;border:none}
        .btn-primary:hover{background:#1b4332}
    </style>
</head>
<body>
<div class="box text-center">
    <div style="font-size:4rem">🔑</div>
    <h3>পাসওয়ার্ড রিসেট</h3>
    
    <?php if($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    <?php if($message): ?>
        <div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>
    
    <?php if($step == 'request'): ?>
        <p class="text-muted">আপনার মোবাইল নম্বর দিন। আমরা একটি OTP পাঠাব।</p>
        <form method="POST">
            <input type="text" name="mobile" class="form-control mb-3" placeholder="মোবাইল নম্বর" value="<?= htmlspecialchars($mobile) ?>" required>
            <button type="submit" class="btn btn-primary w-100">OTP পাঠান</button>
        </form>
    <?php elseif($step == 'otp_sent'): ?>
        <p class="text-muted">আপনার মোবাইল/ইমেইলে ৬ ডিজিটের OTP পাঠানো হয়েছে।</p>
        <form method="POST" action="verify_otp.php">
            <input type="hidden" name="mobile" value="<?= htmlspecialchars($_SESSION['reset_mobile']) ?>">
            <div class="mb-3">
                <input type="text" name="otp" class="form-control" placeholder="ওটিপি লিখুন" maxlength="6" required>
            </div>
            <button type="submit" class="btn btn-primary w-100">যাচাই করুন</button>
        </form>
        <div class="mt-3">
            <a href="forgot_password.php" class="btn btn-link">পুনরায় OTP পাঠান</a>
        </div>
    <?php endif; ?>
    <div class="mt-3">
        <a href="index.php" class="btn btn-link">লগইন পৃষ্ঠায় ফিরুন</a>
    </div>
</div>
</body>
</html>