<?php
require_once "../config/database.php";
require_once "../includes/csrf.php";
require_once "../includes/lang.php";

header("Content-Type: application/json; charset=utf-8");

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $data = json_decode(file_get_contents("php://input"), true) ?: [];
    $action = trim((string)($data["action"] ?? ""));
    $email = trim((string)($data["email"] ?? ""));
    $token = trim((string)($data["token"] ?? ""));
    $password = (string)($data["password"] ?? "");

    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(["success" => false, "error" => "invalid_email"]);
        exit;
    }

    if ($action === "reset") {
        if (strlen($password) < 6) {
            echo json_encode(["success" => false, "error" => "password_too_short"]);
            exit;
        }

        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$email]);
        if (!$stmt->fetch()) {
            echo json_encode(["success" => false, "error" => "email_not_found"]);
            exit;
        }

        $pdo->beginTransaction();
        try {
            $up = $pdo->prepare("UPDATE users SET password = SHA2(?, 256), updated_at = NOW() WHERE email = ?");
            $up->execute([$password, $email]);

            $pdo->prepare("DELETE FROM reset_tokens WHERE email = ?")->execute([$email]);

            $pdo->commit();
            echo json_encode(["success" => true, "message" => t("password_reset_success")]);
        } catch (Throwable $e) {
            $pdo->rollBack();
            echo json_encode(["success" => false, "error" => "reset_failed"]);
        }
        exit;
    }

    // fallback token flow
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$email]);
    if (!$stmt->fetch()) {
        echo json_encode(["success" => false, "error" => "email_not_found"]);
        exit;
    }

    $token = bin2hex(random_bytes(32));
    $expires = date('Y-m-d H:i:s', time() + 3600);

    $pdo->prepare("DELETE FROM reset_tokens WHERE email = ?")->execute([$email]);
    $ins = $pdo->prepare("INSERT INTO reset_tokens (email, token, expires_at) VALUES (?, ?, ?)");
    $ins->execute([$email, $token, $expires]);

    $resetUrl = "http://localhost/konzona/final/public/lost-password.php?token=" . $token . "&email=" . urlencode($email);
    $subject = t("password_reset_request");
    $message = t("password_reset_email") . "\n\n" . $resetUrl . "\n\n" . t("token_expires_1h");
    $headers = "From: noreply@konzona.com";

    if (mail($email, $subject, $message, $headers)) {
        echo json_encode(["success" => true, "message" => t("reset_email_sent")]);
    } else {
        echo json_encode(["success" => false, "error" => "email_failed"]);
    }
} elseif ($_SERVER["REQUEST_METHOD"] === "GET") {
    $token = $_GET["token"] ?? "";
    $email = $_GET["email"] ?? "";

    if (empty($token) || empty($email)) {
        http_response_code(400);
        echo json_encode(["success" => false, "error" => "missing_params"]);
        exit;
    }

    $stmt = $pdo->prepare("SELECT * FROM reset_tokens WHERE email = ? AND token = ? AND expires_at > NOW() AND used = 0");
    $stmt->execute([$email, $token]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        echo json_encode(["success" => true, "valid" => true]);
    } else {
        echo json_encode(["success" => false, "error" => "invalid_or_expired_token"]);
    }
} else {
    http_response_code(405);
    echo json_encode(["success" => false, "error" => "method_not_allowed"]);
}
?>

