<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Jobs\ImportPreClaimBatchRowsJob;
use App\Models\ImportBatch;
use App\Models\ImportBatchRow;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PreClaimController extends Controller
{
    public function index(){
        return view('admin.preclaim.index');
    }

    public function data(Request $request, ImportBatch $batch)
    {
        $rowsQuery = ImportBatchRow::query()
            ->where('import_batch_id', $batch->id)
            ->latest('id');

        if (trim((string) $request->get('search', '')) !== '') {
            $s = '%' . trim((string) $request->get('search')) . '%';
            $rowsQuery->where(function ($q) use ($s) {
                $q->where('row_data', 'like', $s)
                    ->orWhere('response_data', 'like', $s)
                    ->orWhere('request_data', 'like', $s);
            });
        }

        $rows = $rowsQuery->paginate(25)->withQueryString();

        return view('admin.preclaim.data', compact('batch', 'rows'));
    }

    public function import(Request $request){
        $request->validate(['file' => 'required|mimes:csv,xls,xlsx|max:2048' ]);

        $uploadedFile = $request->file('file');
        $filePath = $uploadedFile->store('imports/preclaim');

        $batch = DB::transaction(function () use ($uploadedFile, $filePath) {
            $prefix = 'pre_service_';

            // Count-based sequence (not based on latest id)
            $count = ImportBatch::query()
                ->where('file_name', 'pre_service')
                ->lockForUpdate()
                ->count();

            $nextNumber = $count + 1;
            //$batchNumber = $prefix . str_pad((string) $nextNumber, 3, '0', STR_PAD_LEFT);
            $batchNumber = $prefix . $nextNumber;
            return ImportBatch::create([
                'batch_number' => $batchNumber,
                'file_name' => 'pre_service',
                'file_type' => strtolower($uploadedFile->getClientOriginalExtension() ?: $uploadedFile->extension() ?: 'unknown'),
                'file_path' => $filePath,
                'completed' => 0,
            ]);
        });

        ImportPreClaimBatchRowsJob::dispatch($batch->id);

        return back()->with('success', 'Import started! Processing in background.');
    }
}
