<?php

namespace App\Models\Estimate;

use App\Models\BaseModel;
use App\Traits\HasUuid;

class Section extends BaseModel
{
    use HasUuid;

    protected $primaryKey = 'estimate_section_id';
    protected $table = 'estimate_sections';

    protected $fillable  = [
        'estimate_id',
        'title'
    ];


    public function saveRecord($data = []){
        $validator = $this->validate($data,[
            'title' => ['required'],
            'estimate_id' => ['required'],
        ]);
        if(!$validator['success']){
            return $validator;
        }

        $response = ['success' => false,'message' => 'Failed to create section.'];

        $sectionID = !empty($data['id']) ? $data['id'] : 0;
        if(empty($sectionID)){
            self::create($data);
        }else{
            $section = $this->load($sectionID);
            $section->update($data);
        }
        $response['success'] = true;
        $response['message'] = "Section created successfully.";
        return $response;
    }

    public function getSectionsByEstimate($estimate_id){
        $selectedColumns = ["$this->table.estimate_section_id as id","$this->table.*"];
        $this->setSelect();
        $this->addFieldToFilter($this->table,'estimate_id','=',$estimate_id);
        $this->addOrderby($this->table,'created_at','asc');
        $sections = $this->get($selectedColumns);
        $estimateItemObj = new Item;
        foreach($sections as $section){
            $section->items = $estimateItemObj->getRecordsByEstimate($section->estimate_id,$section->estimate_section_id);
        }
        return $sections;
    }

}
