<?php

if (!defined('ABSPATH')) {
    exit;
}

class BSPP_Magic_Link_Repository {
    private $table;

    public function __construct() {
        global $wpdb;
        $this->table = $wpdb->prefix . 'bobasoftware_pp_magic_links';
    }

    public function create($user_id, $token_hash, $expires_at_gmt) {
        global $wpdb;

        $user_id = (int) $user_id;
        $token_hash = sanitize_text_field($token_hash);
        $expires_at_gmt = sanitize_text_field($expires_at_gmt);

        if ($user_id <= 0 || empty($token_hash) || empty($expires_at_gmt)) {
            return false;
        }

        $inserted = $wpdb->insert(
            $this->table,
            [
                'user_id' => $user_id,
                'token_hash' => $token_hash,
                'expires_at' => $expires_at_gmt,
                'used_at' => null,
            ]
        );

        if (!$inserted) {
            return false;
        }

        return (int) $wpdb->insert_id;
    }

    public function get_valid_by_hash($token_hash) {
        global $wpdb;

        $token_hash = sanitize_text_field($token_hash);
        if (empty($token_hash)) {
            return null;
        }

        return $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM {$this->table}
                 WHERE token_hash = %s
                 AND used_at IS NULL
                 AND expires_at > %s
                 ORDER BY id DESC
                 LIMIT 1",
                $token_hash,
                gmdate('Y-m-d H:i:s')
            )
        );
    }

    public function mark_used($id) {
        global $wpdb;

        $id = (int) $id;
        if ($id <= 0) {
            return false;
        }

        return (bool) $wpdb->update(
            $this->table,
            ['used_at' => gmdate('Y-m-d H:i:s')],
            ['id' => $id]
        );
    }
}

