<?php

namespace auctionforge\ajax;

use auctionforge\ajax\abs\AjaxHandler;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\model\ViewHistory as ViewHistoryModel;

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

        if (SettingsHelper::getOption('enable_recently_viewed', '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;

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

        $result = ViewHistoryModel::recordView($userEmail, $postId, $termId);

        if ($result !== false) {
            wp_send_json_success(array('message' => 'View recorded'));
        } else {
            wp_send_json_error(array('message' => 'Failed to record view'));
        }
    }
}

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

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

        $userEmail = isset($_POST['user_email']) ? sanitize_email($_POST['user_email']) : '';

        if (empty($userEmail)) {
            wp_send_json_error(array('message' => 'Missing user email'));
            return;
        }

        $history = ViewHistoryModel::getHistory($userEmail);

        $items = array();
        foreach ($history as $row) {
            $permalink = get_permalink($row->post_id);
            $thumbnail = '';

            if (!empty($row->imagesBase) && !empty($row->imagesListStr)) {
                $imagesList = explode(',', $row->imagesListStr);
                if (!empty($imagesList[0])) {
                    $image = $imagesList[0];
                    if ($row->imagesCloned) {
                        // Build CDN URL for cloned images
                        $prefix = '';
                        $server = SettingsHelper::getOption('server', '');
                        if (preg_match('/:\/\/([\w\-]+)\./', $server, $m)) {
                            $prefix = $m[1];
                        }
                        $imgIndex = preg_replace('/\D+/', '', $image);
                        $thumbnail = 'https://bidspirit-images.global.ssl.fastly.net/' . $prefix . '/cloned-images/' . $row->imagesBase . '/' . $imgIndex . '/' . $image;
                    } else {
                        // Build CDN URL for non-cloned (Cloudinary) images
                        $prefix = '';
                        $server = SettingsHelper::getOption('server', '');
                        if (preg_match('/:\/\/([\w\-]+)\./', $server, $m)) {
                            $prefix = $m[1];
                        }
                        $thumbnail = 'https://res.cloudinary.com/bidspirit/image/upload/w_200/' . $prefix . '_' . $row->imagesBase . '_' . $image;
                    }
                }
            }

            if (empty($thumbnail)) {
                $thumbId = get_post_thumbnail_id($row->post_id);
                if ($thumbId) {
                    $thumbnail = get_the_post_thumbnail_url($row->post_id, 'thumbnail');
                }
            }

            $auctionState = '';
            if (!empty($row->term_id)) {
                $auctionState = SettingsHelper::getTermOption($row->term_id, 'auction_state');
            }

            $items[] = array(
                'post_id' => $row->post_id,
                'term_id' => $row->term_id,
                'lot_index' => $row->itemIndex,
                'lot_name' => !empty($row->lot_name) ? $row->lot_name : $row->post_title,
                'auction_name' => $row->auction_name,
                'auction_state' => $auctionState,
                'start_price' => intval($row->startPrice),
                'sold_bid' => intval($row->soldBid),
                'leading_bid' => intval($row->leadingBid),
                'estimated_price' => $row->estimatedPrice,
                'thumbnail' => $thumbnail,
                'permalink' => $permalink,
                'viewed_at' => $row->viewed_at,
                'viewed_at_formatted' => date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($row->viewed_at)),
                'bidspirit_lot_id' => isset($row->bidspirit_lot_id) ? $row->bidspirit_lot_id : '',
                'bidspirit_auction_id' => isset($row->auctionId) ? $row->auctionId : '',
            );
        }

        wp_send_json_success(array(
            'count' => count($items),
            'items' => $items,
        ));
    }
}

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

        $userEmail = isset($_POST['user_email']) ? sanitize_email($_POST['user_email']) : '';

        if (empty($userEmail)) {
            wp_send_json_error(array('message' => 'Missing user email'));
            return;
        }

        ViewHistoryModel::clearHistory($userEmail);
        wp_send_json_success(array('message' => 'History cleared'));
    }
}

$recordView = new ViewHistoryRecord();
$recordView->init('bp_record_view');

$getHistory = new ViewHistoryGet();
$getHistory->init('bp_get_view_history');

$clearHistory = new ViewHistoryClear();
$clearHistory->init('bp_clear_view_history');
