<?php

namespace App\Repositories;

use App\Models\Department;
use App\Models\DepartmentHardwareMapping;
use App\Models\MakeAndModel;
use DB;

class HardwarekitRepository
{
    /**
     * get all the departments
     */
    public function getDepartments()
    {
        return Department::get();
    }
    /**
     * It returns all the hardware standards from the database
     */
    public function getHardwareStandards()
    {
        return MakeAndModel::get();
    }
    /**
     * It returns a collection of DepartmentHardwareMapping models, each of which has a department
     * relationship, and each of which has a make_and_model_ids, technical_spec_ids, and costs attribute
     *
     * @return The DepartmentHardwareMapping model is being returned with the department relationship.
     */
    public function DepartmentHardwareKitData()
    {
        return DepartmentHardwareMapping::with('department:id,name')
            ->select()
            ->addSelect(
                DB::raw("count(department_hardware_mappings.make_and_model_id) as totalHardwares"),
                DB::raw("sum(department_hardware_mappings.cost) as totalCost"),
                DB::raw("group_concat(department_hardware_mappings.make_and_model_id) as make_and_model_ids"),
                DB::raw("group_concat(department_hardware_mappings.technical_spec_id) as technical_spec_ids"),
                DB::raw("group_concat(department_hardware_mappings.cost) as costs"),
            )
            ->groupBy('department_hardware_mappings.department_id')
            ->get();
    }

    /**
     *  When the value is not null, filter the data by the field and value
     *
     * @param data The data you want to filter
     * @param field The field you want to filter by
     * @param value The value of the input field.
     */
    public function filterDataWithInputFields($data, $field, $value)
    {
        $data = $data->when(
            $value ?? false,
            fn ($data, $value) => is_array($value) ? $data->whereIn($field, $value) : $data->where($field, $value)
        );

        return $data;
    }
    /**
     * delete Department Hardwares
     * @param int $departmentId
     */
    public function deleteDepartmentHardwares($departmentId)
    {
        DepartmentHardwareMapping::where('department_id', $departmentId)->delete();
    }

    /**
     * update Hardwares of the Department
     * @param array $conditions
     * @param array $data
     */
    public function updateDepartmentHardwares($data)
    {
        return DepartmentHardwareMapping::Insert($data);
    }
}
