<?php

namespace App\Http\Resources;

use App\Http\Controllers\Helpers\HelperController;
use App\Models\Material;
use App\Models\Material_comment;
use Illuminate\Http\Resources\Json\JsonResource;

class MaterialResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        return [
            'mat_id' => $this->id,
            'material_name' => $this->material_name($this->material_no),
            'material_code' => $this->material_no,
            'current_stock' => HelperController::number_format($this->current_stock),
            'unit_price' => HelperController::number_format($this->unit_price),
            'unit_of_measure' => $this->unit_of_measure,
            'sap_stock' => HelperController::number_format($this->sap_stock),
            'stock_variance' => HelperController::number_format($this->calculate_variance($this->current_stock, $this->sap_stock)),
            'variance_value' => HelperController::number_format($this->calculate_cost_variance($this->current_stock, $this->sap_stock, $this->unit_price)),
            'supervisor_comment' => $this->comment ? $this->comment : "N/A",
            'accountant_comment' => count($this->material_comments) > 0 ? $this->accountant_comment($this->id) : "N/A",
            'controller_comment' => count($this->material_comments) > 0 ? $this->controller_comment($this->id) : "N/A",
        ];
    }

    private function calculate_variance($current, $sap)
    {
        return round(($sap - $current), 2);
    }

    private function calculate_cost_variance($current, $sap, $cost)
    {
        return round(($sap * $cost) - ($current * $cost), 2);
    }

    private function material_name($no)
    {
        $mat = Material::where('material_no', $no)->first();
        return $mat->material_name;
    }
    private function show_status($status)
    {
        if ($status == 'active') {
            return 'Counting in progress';
        } elseif ($status == 'repeat') {
            return 'Counting on repeat mode';
        } elseif ($status == 'inactive') {
            return 'Counting yet to start';
        } elseif ($status == 'closed') {
            return 'Counting closed';
        }
    }
    private function accountant_comment($id)
    {
        $comment = Material_comment::where([['stock_take_material_id', $id], ['role', 'plant_accountant']])->first();
        if ($comment) {
            return $comment->comment;
        }
        return "No comment yet";
    }
    private function controller_comment($id)
    {
        $comment = Material_comment::where([['stock_take_material_id', $id], ['role', 'plant_controller']])->first();
        if ($comment) {
            return $comment->comment;
        }
        return "No comment yet";
    }
}