<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class GridPersistance extends Model
{
    protected $table = 'grid_persistance';
    protected $primaryKey = 'persistance_id';
    protected $fillable = ['grid_id','user_id','records_per_page'];

    public static function findGridPersistanceByGridIdAndUserd($grid_id, $user_id) {
        return GridPersistance::where('grid_id', $grid_id)
            ->where('user_id', $user_id)
            ->first();
    }

    public static function getRecordsPerPage($persistance_grid_id, $user_id = null) {
        if( !$persistance_grid_id ) {
            return null;
        }

        $grid_id = $persistance_grid_id;
        $user_id = $user_id ?? Auth::user()->id;
        $grid_persistance = GridPersistance::findGridPersistanceByGridIdAndUserd($grid_id, $user_id);
        return $grid_persistance->records_per_page ?? null;
    }



    public static function saveRecordsPerPage($persistance_grid_id, $recordsPerPage, $user_id = null) {
        if( !$persistance_grid_id ) {
            return null;
        }

        $grid_id = $persistance_grid_id;
        $user_id = $user_id ?? Auth::user()->id;
        $grid_persistance = GridPersistance::findGridPersistanceByGridIdAndUserd($grid_id, $user_id);
        if( !$grid_persistance ) {
            $grid_persistance = new GridPersistance();
            $grid_persistance->grid_id = $grid_id;
            $grid_persistance->user_id = $user_id;
        }
        $grid_persistance->records_per_page = $recordsPerPage;
        $grid_persistance->save();
    }

}
