<?php
header('Content-Type: application/json; charset=utf-8');

$conn = new mysqli("localhost", "db_user", "db_pass", "db_name");
if ($conn->connect_error) {
    echo json_encode(["status" => "error", "message" => "db_error"]);
    exit;
}
$conn->set_charset("utf8mb4");

$action = $_POST['action'] ?? '';
$email = $_POST['email'] ?? '';
$otp = $_POST['otp'] ?? '';

if ($action === 'send') {
    if ($email === '') {
        echo json_encode(["status" => "error", "message" => "email_required"]);
        exit;
    }

    $code = (string)random_int(100000, 999999);
    $expiresAt = date('Y-m-d H:i:s', time() + 300);

    $stmt = $conn->prepare("DELETE FROM zabbar_otp WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->close();

    $stmt = $conn->prepare("INSERT INTO zabbar_otp (email, otp, expires_at) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $email, $code, $expiresAt);
    if (!$stmt->execute()) {
        echo json_encode(["status" => "error", "message" => "insert_failed"]);
        exit;
    }
    $stmt->close();

    $googleUrl = "https://script.google.com/macros/s/AKfycbygswhFT-3wlHCQ65j9DJsnadpNIBSswL05k7WZV7dx7emJOza-v8nl_GbiGlQDwGEuNw/exec?email=" . urlencode($email) . "&title=" . urlencode("Forget Password OTP") . "&body=" . urlencode("আপনার OTP কোড: " . $code . "। এটি ৫ মিনিটের মধ্যে ব্যবহার করুন।") . "&appname=" . urlencode("মাইঅ্যাপ");

    @file_get_contents($googleUrl);

    echo json_encode(["status" => "success"]);
    exit;
}

if ($action === 'verify') {
    if ($email === '' || $otp === '') {
        echo "none";
        exit;
    }

    $stmt = $conn->prepare("SELECT id FROM zabbar_otp WHERE email = ? AND otp = ? AND expires_at > NOW() ORDER BY id DESC LIMIT 1");
    $stmt->bind_param("ss", $email, $otp);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        echo "none";
        exit;
    }
    $stmt->close();

    $stmt = $conn->prepare("SELECT username FROM users WHERE email = ? LIMIT 1");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $userResult = $stmt->get_result();

    if ($userResult->num_rows === 0) {
        echo "none";
        exit;
    }

    $user = $userResult->fetch_assoc();
    $stmt->close();

    $stmt = $conn->prepare("DELETE FROM zabbar_otp WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->close();

    echo json_encode([
        "status" => "success",
        "username" => $user['username']
    ]);
    exit;
}

echo json_encode(["status" => "error", "message" => "invalid_action"]);