<?php
require_once 'config/config.php';

class User {
    public static function find($username, $password, $clientId) {
        try {
            $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
           
            $stmt = $pdo->prepare("SELECT * FROM opf_accounts WHERE user_api = :username AND account = :clientId LIMIT 1");
            $stmt->execute([
                ':username' => $username,
                ':clientId' => $clientId
            ]);

            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($user && password_verify($password, $user['password'])) {
                return $user;
            }

            return null;
        } catch (PDOException $e) {
            error_log("Error en login: " . $e->getMessage());
            return null;
        }
    }
    
    public static function guardarToken($username, $clientId, $token) {
    try {
        $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $pdo->prepare("UPDATE opf_accounts SET token = :token WHERE user_api = :username AND account = :clientId");
        $stmt->execute([
            ':token' => $token,
            ':username' => $username,
            ':clientId' => $clientId
        ]);

        return true;
    } catch (PDOException $e) {
        error_log("Error al guardar token: " . $e->getMessage());
        return false;
    }
}


    public static function validarTokenEnBD($username, $clientId, $token) {
    try {
        $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $pdo->prepare("SELECT token FROM opf_accounts WHERE user_api = :username AND account = :clientId LIMIT 1");
        $stmt->execute([
            ':username' => $username,
            ':clientId' => $clientId
        ]);

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return ($row && $row['token'] === $token);
    } catch (PDOException $e) {
        error_log("Error en validación de token en BD: " . $e->getMessage());
        return false;
    }
}


}
