<?php
require_once 'config.php';
require __DIR__ . '/jwt/autoload.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

header('Content-Type: application/json');

$jwtSecret = "Shuvo_2025_SECURE49797567697979696967676967696979797969796f796f796f";

function getEmailFromToken($token, $secretKey) {
    try {
        $decoded = JWT::decode($token, new Key($secretKey, 'HS256'));
        return $decoded->email ?? null;
    } catch (Exception $e) {
        return null;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $type = isset($_POST['type']) ? trim($_POST['type']) : '';

    // ✅ Type 1: Token দিয়ে profile দেখা
    if ($type === '1') {

        if (!isset($_POST['token']) || empty(trim($_POST['token']))) {
            echo json_encode(["error" => "Token required"]);
            exit;
        }

        $token = trim($_POST['token']);
        $email = getEmailFromToken($token, $jwtSecret);

        if (!$email) {
            echo json_encode(["error" => "Invalid token (decode failed)"]);
            exit;
        }

        $stmt = $conn->prepare("SELECT * FROM users WHERE email = ? AND token = ?");
        $stmt->bind_param("ss", $email, $token);
        $stmt->execute();
        $check = $stmt->get_result();

        if ($check->num_rows === 0) {
            echo json_encode(["error" => "Token does not match user record"]);
            exit;
        }

        echo json_encode($check->fetch_assoc());
        $stmt->close();
        $conn->close();
        exit;
    }

    // ✅ Type pass: শুধু token দিয়ে password change
    if ($type === 'pass') {

        if (!isset($_POST['token']) || empty(trim($_POST['token']))) {
            echo json_encode(["error" => "Token required"]);
            exit;
        }

        $token    = trim($_POST['token']);
        $oldpass  = trim($_POST['oldpass'] ?? '');
        $newpass  = trim($_POST['newpass'] ?? '');

        if (empty($oldpass) || empty($newpass)) {
            echo json_encode(["error" => "Old/New passwords required"]);
            exit;
        }

        $email = getEmailFromToken($token, $jwtSecret);
        if (!$email) {
            echo json_encode(["error" => "Invalid token (decode failed)"]);
            exit;
        }

        $stmt = $conn->prepare("SELECT * FROM users WHERE email = ? AND token = ?");
        $stmt->bind_param("ss", $email, $token);
        $stmt->execute();
        $check = $stmt->get_result();

        if ($check->num_rows === 0) {
            echo json_encode(["error" => "Token does not match user record"]);
            exit;
        }

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

        if ($oldpass !== $user['password']) {
            echo json_encode(["error" => "Old password incorrect"]);
            exit;
        }

        $stmt = $conn->prepare("UPDATE users SET password = ? WHERE email = ?");
        $stmt->bind_param("ss", $newpass, $email);
        if ($stmt->execute()) {
            echo json_encode(["status" => "success", "message" => "Password Changed"]);
        } else {
            echo json_encode(["error" => "Password Update Failed"]);
        }
        $stmt->close();
        $conn->close();
        exit;
    }

    // ✅ Type resetpass: শুধু token দিয়ে password reset
    if ($type === 'resetpass') {

        if (!isset($_POST['token']) || empty(trim($_POST['token']))) {
            echo json_encode(["error" => "Token required"]);
            exit;
        }

        $token   = trim($_POST['token']);
        $newpass = trim($_POST['newpass'] ?? '');

        if (empty($newpass)) {
            echo json_encode(["error" => "New password required"]);
            exit;
        }

        $email = getEmailFromToken($token, $jwtSecret);
        if (!$email) {
            echo json_encode(["error" => "Invalid token (decode failed)"]);
            exit;
        }

        $stmt = $conn->prepare("SELECT * FROM users WHERE email = ? AND token = ?");
        $stmt->bind_param("ss", $email, $token);
        $stmt->execute();
        $check = $stmt->get_result();

        if ($check->num_rows === 0) {
            echo json_encode(["error" => "Token does not match user record"]);
            exit;
        }

        $stmt->close();

        $stmt = $conn->prepare("UPDATE users SET password = ? WHERE email = ?");
        $stmt->bind_param("ss", $newpass, $email);
        if ($stmt->execute()) {
            echo json_encode(["status" => "success", "message" => "Password Reset Successfully"]);
        } else {
            echo json_encode(["error" => "Error Resetting Password"]);
        }
        $stmt->close();
        $conn->close();
        exit;
    }

    // ✅ Type edit: Token দিয়ে username, email, number update
    if ($type === 'edit') {

        if (!isset($_POST['token']) || empty(trim($_POST['token']))) {
            echo json_encode(["error" => "Token required"]);
            exit;
        }

        $token = trim($_POST['token']);
        $email = getEmailFromToken($token, $jwtSecret);

        if (!$email) {
            echo json_encode(["error" => "Invalid token (decode failed)"]);
            exit;
        }

        $stmt = $conn->prepare("SELECT * FROM users WHERE email = ? AND token = ?");
        $stmt->bind_param("ss", $email, $token);
        $stmt->execute();
        $check = $stmt->get_result();

        if ($check->num_rows === 0) {
            echo json_encode(["error" => "Token does not match user record"]);
            exit;
        }
        $stmt->close();

        $new_username = trim($_POST['username'] ?? '');
        $new_email    = trim($_POST['email'] ?? '');
        $new_number   = trim($_POST['number'] ?? '');

        if (empty($new_username) || empty($new_email) || empty($new_number)) {
            echo json_encode(["error" => "username, email and number are required"]);
            exit;
        }

        $stmt = $conn->prepare("UPDATE users SET username = ?, email = ?, number = ? WHERE email = ?");
        $stmt->bind_param("ssss", $new_username, $new_email, $new_number, $email);
        if ($stmt->execute()) {
            echo json_encode(["status" => "success", "message" => "Profile Updated"]);
        } else {
            echo json_encode(["error" => "Error Updating Profile"]);
        }
        $stmt->close();
        $conn->close();
        exit;
    }

    // ✅ বাকি সব type এর জন্য username লাগবে
    if (!isset($_POST['username']) || empty(trim($_POST['username']))) {
        echo json_encode(["error" => "Username is required"]);
        exit;
    }

    $username = trim($_POST['username']);

    $stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        echo json_encode(["error" => "User not found"]);
        exit;
    }

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

    echo json_encode(["error" => "Invalid Type"]);

    $conn->close();

} else {
    echo json_encode(["error" => "Invalid Request"]);
}
?>