<?php

namespace App\Models\Invoice;

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

class Section extends BaseModel
{
    use HasUuid;

    protected $primaryKey = 'invoice_section_id';
    protected $table = 'invoice_sections';

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


    public function saveRecord($data = []){
        $validator = $this->validate($data,[
            'title' => ['required'],
            'invoice_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 getSectionsByInvoice($invoice_id){
        $selectedColumns = ["$this->table.invoice_section_id as id","$this->table.*"];
        $this->setSelect();
        $this->addFieldToFilter($this->table,'invoice_id','=',$invoice_id);
        $this->addOrderby($this->table,'created_at','asc');
        $sections = $this->get($selectedColumns);
        $estimateItemObj = new Item;
        foreach($sections as $section){
            $section->items = $estimateItemObj->getRecordsByInvoice($section->invoice_id,$section->invoice_section_id);
        }
        return $sections;
    }

}
