<?php
/**
 * VR票务插件 - 核销记录
 *
 * @package vr_ticket\admin\controller
 */

namespace app\plugins\vr_ticket\admin\controller;

class Verification extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 核销记录列表
     */
    public function list()
    {
        $where = [];

        $keywords = input('keywords', '', null, 'trim');
        if (!empty($keywords)) {
            $where[] = ['ticket_code|verifier_name', 'like', "%{$keywords}%"];
        }

        $verifier_id = input('verifier_id', 0, 'intval');
        if ($verifier_id > 0) {
            $where[] = ['verifier_id', '=', $verifier_id];
        }

        // 日期范围
        $start_date = input('start_date', '', null, 'trim');
        $end_date = input('end_date', '', null, 'trim');
        if (!empty($start_date)) {
            $where[] = ['created_at', '>=', strtotime($start_date)];
        }
        if (!empty($end_date)) {
            $where[] = ['created_at', '<=', strtotime($end_date . ' 23:59:59')];
        }

        $list = \Db::name('plugins_vr_verifications')
            ->where($where)
            ->order('id', 'desc')
            ->paginate(20)
            ->toArray();

        // 补充票信息和商品信息（修复：column() 不支持多字段映射，改用 select() + PHP 拼接）
        $ticket_ids = array_filter(array_column($list['data'], 'ticket_id'));
        if (!empty($ticket_ids)) {
            $tickets_raw = \Db::name('plugins_vr_tickets')
                ->where('id', 'in', $ticket_ids)
                ->select();
            $tickets = [];
            foreach ($tickets_raw as $t) {
                $tickets[$t['id']] = $t;
            }
            foreach ($list['data'] as &$item) {
                $ticket = $tickets[$item['ticket_id']] ?? [];
                $item['seat_info'] = $ticket['seat_info'] ?? '';
                $item['real_name'] = $ticket['real_name'] ?? '';
                $item['goods_id'] = $ticket['goods_id'] ?? 0;
            }
            unset($item);
        }

        // 商品名
        $goods_ids = array_filter(array_unique(array_column($list['data'], 'goods_id')));
        if (!empty($goods_ids)) {
            $goods_map = \Db::name('Goods')
                ->where('id', 'in', $goods_ids)
                ->column('title', 'id');
            foreach ($list['data'] as &$item) {
                $item['goods_title'] = $goods_map[$item['goods_id']] ?? '已删除';
            }
            unset($item);
        }

        // 核销员列表（用于筛选）
        $verifiers = \Db::name('plugins_vr_verifiers')
            ->where('status', 1)
            ->column('name', 'id');

        return view('', [
            'list'      => $list['data'],
            'page'      => $list['page'],
            'count'     => $list['total'],
            'verifiers' => $verifiers,
        ]);
    }
}
