<?php

namespace auctionforge\ajax;

use auctionforge\ajax\abs\AjaxHandler;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\model\LotAnalytics as LotAnalyticsModel;

class LotAnalyticsRecordFavorite extends AjaxHandler
{
    function callback()
    {
        check_ajax_referer('bp-ajax-string', 'security');

        if (SettingsHelper::getOption('enable_lot_analytics', 'off') !== 'on') {
            wp_send_json_error(array('message' => 'Feature disabled'));
            return;
        }

        $userEmail = isset($_POST['user_email']) ? sanitize_email($_POST['user_email']) : '';
        $postId = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
        $termId = isset($_POST['term_id']) ? intval($_POST['term_id']) : 0;
        $isFavorite = isset($_POST['is_favorite']) ? ($_POST['is_favorite'] === 'true' || $_POST['is_favorite'] === '1') : true;

        if (empty($userEmail) || empty($postId)) {
            wp_send_json_error(array('message' => 'Missing required fields'));
            return;
        }

        $result = LotAnalyticsModel::recordFavorite($userEmail, $postId, $termId, $isFavorite);

        if ($result) {
            $count = LotAnalyticsModel::getFavoriteCount($postId);
            wp_send_json_success(array('message' => 'Favorite recorded', 'favorite_count' => $count));
        } else {
            wp_send_json_error(array('message' => 'Failed to record favorite'));
        }
    }
}

class LotAnalyticsGetStats extends AjaxHandler
{
    function callback()
    {
        check_ajax_referer('bp-ajax-string', 'security');

        if (SettingsHelper::getOption('enable_lot_analytics', 'off') !== 'on') {
            wp_send_json_error(array('message' => 'Feature disabled'));
            return;
        }

        $postId = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;

        if (empty($postId)) {
            wp_send_json_error(array('message' => 'Missing post ID'));
            return;
        }

        $analytics = LotAnalyticsModel::getLotAnalytics($postId);

        wp_send_json_success(array(
            'view_count' => $analytics ? intval($analytics->view_count) : 0,
            'unique_visitors' => $analytics ? intval($analytics->unique_visitors) : 0,
            'favorite_count' => $analytics ? intval($analytics->favorite_count) : 0,
        ));
    }
}

class LotAnalyticsBackfill extends AjaxHandler
{
    function callback()
    {
        check_ajax_referer('bp-ajax-string', 'security');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Unauthorized'));
            return;
        }

        $count = LotAnalyticsModel::backfillFromPageviews();
        wp_send_json_success(array('message' => "Backfilled {$count} lots from pageview data"));
    }
}
