<?php

namespace App\Http\Controllers;

use App\Models\ExcelRecord;
use Illuminate\Http\Request;

class RecordController extends Controller
{
    /**
     * Show the records table page
     */
    public function index()
    {
        return view('records.index');
    }

    /**
     * Get paginated records with search, filter, and sort
     */
    public function listRecords(Request $request)
    {
        $query = ExcelRecord::query();

        // Apply search
        if ($request->has('search') && !empty($request->search)) {
            $query->search($request->search);
        }

        // Apply filters
        if ($request->has('filters') && is_array($request->filters)) {
            $query->filter($request->filters);
        }

        // Apply sorting
        $sortColumn = $request->get('sort_column', 'id');
        $sortDirection = $request->get('sort_direction', 'desc');
        $query->sort($sortColumn, $sortDirection);

        // Get paginated results
        $perPage = $request->get('per_page', 50);
        $records = $query->paginate($perPage);

        return response()->json([
            'data' => $records->items(),
            'current_page' => $records->currentPage(),
            'last_page' => $records->lastPage(),
            'per_page' => $records->perPage(),
            'total' => $records->total(),
            'from' => $records->firstItem(),
            'to' => $records->lastItem(),
        ]);
    }
}

