<?php

namespace App\Http\Resources;

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

class ReportsResource 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 [
            'month' => $this->pretty_date($this->created_at),
            'material_name' => $this->get_mat_name($this->material_no),
            'material_no' => $this->material_no,
            'current_stock' => $this->current_stock ? HelperController::number_format($this->current_stock) : 'Not counted yet',
            'sap_stock' => HelperController::number_format($this->sap_stock),
            'stock_variance' => $this->current_stock ? HelperController::number_format($this->calculate_variance($this->current_stock, $this->sap_stock)) : 'N/A',
            'cost_variance' => $this->current_stock ? HelperController::number_format($this->calculate_cost_variance($this->current_stock, $this->sap_stock, $this->unit_price)) : "N/A",

        ];
    }

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

    private function calculate_cost_variance($current, $sap, $price)
    {
        return round(($sap * $price) - ($current * $price), 2);
    }
    private function pretty_date($date)
    {
        return date('M d, Y', strtotime($date));
    }

    private function get_mat_name($no)
    {
        $mat = Material::where('material_no', $no)->first();
        return $mat->material_name;
    }
}