<?php

namespace App\Models\Invoice;

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

class Item extends BaseModel
{
    use HasUuid;

    protected $primaryKey = 'invoice_item_id';
    protected $table = 'invoice_items';

    protected $fillable  = [
        'invoice_id',
        'invoice_section_id',
        'item_name',
        'description',
        'unit_type',
        'length_value',
        'length_unit',
        'width_value',
        'width_unit',
        'height_value',
        'height_unit',
        'quantity',
        'unit_price',
        'total',
        'sort_order'
    ];

    public function getUnitPriceAttribute($value)
    {
        return number_format((float) $value, 2, '.', '');
    }

    public function getQuantityAttribute($value)
    {
        return number_format((float) $value, 2, '.', '');
    }

    public function getTotalAttribute($value)
    {
        return number_format((float) $value, 2, '.', '');
    }

    public function saveRecord($data)
    {
        $response = ['success' => false, 'message' => 'Failed to save Item'];

        $itemID = !empty($data['id']) ? $data['id'] : 0;
        if (empty($itemID)) {
            $item = self::create($data);
        } else {
            $item = self::find($itemID);
            $item->update($data);
        }

        $response['success'] = true;
        $response['message'] = "Item saved successfully.";
        return $response;
    }

    public function getRecordsByInvoice($invoice_id, $invoice_section_id = 0)
    {
        $selectedColumns = ["$this->table.invoice_item_id as id", "$this->table.*"];
        $this->setSelect();
        $this->addFieldToFilter($this->table, 'invoice_id', '=', $invoice_id);
        if (!empty($invoice_section_id)) {
            $this->addFieldToFilter($this->table, 'invoice_section_id', '=', $invoice_section_id);
        }
        $this->addOrderby($this->table, 'sort_order', 'asc');
        return $this->get($selectedColumns);
    }

    public function remove($item_id)
    {
        $response = ['success' => false, 'message' => 'Failed to delete Item.'];
        $item = $this->load($item_id);
        if ($item) {
            $item->delete();
            $response['success'] = true;
            $response['message'] = 'Item Deleted successfully.';
        }
        return $response;
    }

    public function reorder($data = [])
    {
        $response = ['success' => false, 'message' => 'Failed to save order.'];
        if (!empty($data['items'])) {
            foreach ($data['items'] as $item) {
                $item = $this->load($item['id']);
                if ($item) {
                    $item->update(['sort_order' => $item['sort_order']]);
                }
            }
            $response['success'] = true;
            $response['message'] = "Order saved successfully.";
        }
        return $response;
    }
}
