<?php

namespace App\Services\PTW;

use App\Http\Resources\PTW\PtwResource;
use App\Models\Ptw;

class PtwServices extends PtwResource
{
    public $vvsPtwModel;
    public $page;
    public $pageSize;
    public function __construct(){
        $this->vvsPtwModel = new Ptw();
    }
    /**
     * Column name in DB Table and Front end request variables are mapped
     * key is the column name of DB table and value is the front end request variable
     */
    protected function columnMappingsFrontEndVsBackEnd(){
        return [
            'TYPE_ID' => 'TYPE_ID',
            'SITE_ID' => 'SITE_ID',
            'AUTO_GEN_REF_NO' => 'AUTO_GEN_NO',
        ];
    }
    
    public function getPtwList($requestData){
        $columnMapping = $this->columnMappingsFrontEndVsBackEnd();

        $query = Ptw::query();
        // Define the relationships to eager load
        $relationshipsToLoad = ['type','site','location','sopPolicy','contractor','stage'];

        // Iterate over the requested variables
        foreach ($requestData as $key => $value) {
            // Check if the value is not empty and the mapping exists
            if (!empty($value) && isset($columnMapping[$key])) {
                // Add a where clause for the mapped column name
                $query->where($columnMapping[$key], $value);
            }
        }
        
        // Eager load the specified relationships
        $query->with($relationshipsToLoad);
        
     
        /////////////////////////////PAGINATION LOGIC incorporation/////////////////////////////////////
       
        $this->page = $requestData -> PAGE_NUM ?? 1; // Default to page 1 if not provided
        $this->pageSize = $requestData -> PAGE_SIZE ?? config("constants.PAGINATION_PER_PAGE");

        /////////////////////////////END OF PAGINATION LOGIC incorporation/////////////////////////////////////

        return $query->paginate($this->pageSize, ['*'], 'page', $this->page);
    }

    public function getPtwDetails($requestData){
        return Ptw::where("ID", $requestData->PTW_ID)->first();
    }
}
