OcrController.php 6.47 KB
<?php

namespace App\Http\Controllers;

use App\Models\DtTemplate;
use App\Models\MstTemplate;
use Illuminate\Http\Request;

class OcrController extends Controller
{
    public function index()
    {
        return view('ocr.index');
    }


    public function store(Request $request)
    {

        $request->validate([
            'customer_name_text' => 'required|string',
            'customer_name_xy' => 'required|string',
        ]);
        $dataDetail = $request->fields ?? [];
        $tableColumns = $request->table_columns ?? [];
        try {
            $masterTemplate = MstTemplate::updateOrCreate(
                ['tpl_name' => $request->template_name],
                [
                    'tpl_text' => $request->customer_name_text,
                    'tpl_xy'   => $request->customer_name_xy,
                ]
            );

            foreach ($dataDetail as $field => $value) {
                if (empty($value['coords'])) {
                    continue;
                }

                DtTemplate::updateOrInsert(
                    [
                        'tpl_id'     => $masterTemplate->id,
                        'field_name' => $field,
                    ],
                    [
                        'field_xy' => is_array($value['coords'])
                            ? implode(',', $value['coords'])
                            : $value['coords'],
                    ]
                );

            }

            // Lưu mapping cột bảng (lưu col index vào field_xy với field_name đặc biệt)
            if (!empty($tableColumns) && is_array($tableColumns)) {
                foreach ($tableColumns as $name => $colIdx) {
                    if ($colIdx === null || $colIdx === '' || $colIdx === false) {
                        continue;
                    }
                    DtTemplate::updateOrInsert(
                        [
                            'tpl_id'     => $masterTemplate->id,
                            'field_name' => '__table_col__' . $name,
                        ],
                        [
                            'field_xy' => (string) $colIdx,
                        ]
                    );
                }
            }
            return response()->json([
                'success' => true,
                'message' => 'Lưu template thành công',
                'template_id' => $masterTemplate->id
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Lỗi khi lưu template: ' . $e->getMessage()
            ], 500);
        }
    }


    public function getData(Request $request)
    {
        try {
            // Lấy template name từ request hoặc mặc định
            $templateName = $request->get('template_name', '');

            // Giả sử file OCR JSON & ảnh nằm trong storage/app/public/image/
            $jsonPath = public_path("image/nemo_new_3_1757403463_with_table.json");
            $imgPath = ("image/nemo_new_3_1757403463.jpg");

            if (!file_exists($jsonPath)) {
                return response()->json(['error' => 'File OCR JSON không tìm thấy'], 404);
            }

            $ocrData = json_decode(file_get_contents($jsonPath), true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                return response()->json(['error' => 'File OCR JSON không hợp lệ'], 400);
            }

            if (!empty($ocrData)) {
                foreach ($ocrData['tables'] as $item_data) {
                    $table_box = $item_data['table_box'];
                    $total_rows = $item_data['total_rows'] - 1;
                    $table_detail = $item_data['cells'];
                }
            }

            $dataMapping = [];
            $is_template = false;

            if ($templateName) {
                $mst = MstTemplate::where('tpl_name', $templateName)->first();

                if ($mst) {
                    // Lấy detail của template
                    $details = DtTemplate::where('tpl_id', $mst->id)->get();

                    $tableColumnMapping = [];
                    foreach ($details as $detail) {
                        if (strpos($detail->field_name, '__table_col__') === 0) {
                            $name = substr($detail->field_name, strlen('__table_col__'));
                            $tableColumnMapping[$name] = is_numeric($detail->field_xy) ? intval($detail->field_xy) : null;
                            continue;
                        }
                        $coords = array_map('intval', explode(',', $detail->field_xy));
                        // coords = [x1, y1, x2, y2]

                        $dataMapping[$detail->field_name] = [
                            'text' => '',
                            'coords' => $coords
                        ];
                    }
                    $dataMapping['template_name'] = [
                        'text' => $mst->tpl_name,
                        'coords' => ''
                    ];

                    $is_template = true;

                }
            }


            return response()->json([
                'success' => true,
                'ocrData' => $ocrData['ocr_data'] ?? [],
                'tableInfo' => $table_detail ?? [],
                'table_box' => $table_box ?? [],
                'total_rows' => $total_rows ?? 0,
                'rows_box' => $rows_box ?? [],
                'pdfImageUrl' => $imgPath,
                'dataMapping' => $dataMapping,
                'is_template' => $is_template,
                'tableColumnMapping' => $tableColumnMapping ?? [], //?? new \stdClass(),
                'fieldOptions' => [
                    [ 'value' => 'template_name',  'label' => 'Tên Mẫu PDF' ],
                    [ 'value' => 'customer_name',  'label' => 'Tên khách hàng' ],
                    [ 'value' => 'export_date',    'label' => 'Ngày xuất' ],
                    [ 'value' => 'order_code',     'label' => 'Mã đơn hàng' ],
                    [ 'value' => 'customer',       'label' => 'Khách hàng' ],
                    [ 'value' => 'address',        'label' => 'Địa chỉ' ],
                    [ 'value' => 'staff',          'label' => 'Nhân viên' ],
                ],
                'template_name' => $templateName
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'Lỗi khi load data: ' . $e->getMessage()
            ], 500);
        }
    }
}