<?php

namespace App\Libs\Database\Eloquent\Relations;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class BelongsToManyWebsite extends BelongsToMany
{

    protected $websiteId;

    /**
     * Create a new belongs to many relationship instance dependent on website.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  \Illuminate\Database\Eloquent\Model  $parent
     * @param  int  $websiteId
     * @param  string  $table
     * @param  string  $foreignPivotKey
     * @param  string  $relatedPivotKey
     * @param  string  $parentKey
     * @param  string  $relatedKey
     * @param  string|null  $relationName
     * @return void
     */
    public function __construct(
        Builder $query,
        Model $parent,
        $websiteId,
        $table,
        $foreignPivotKey,
        $relatedPivotKey,
        $parentKey,
        $relatedKey,
        $relationName = null
    ) {
        $this->websiteId = $websiteId;

        parent::__construct($query, $parent, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey,
            $relationName);

        $this->withPivot("website_id")->wherePivot("website_id", "=", $this->websiteId);
    }

    /**
     * Format the sync / toggle record list so that it is keyed by ID.
     *
     * @param  array  $records
     * @return array
     */
    protected function formatRecordsList(array $records)
    {
        return collect($records)->mapWithKeys(function ($attributes, $id) {
            if (!is_array($attributes)) {
                [$id, $attributes] = [$attributes, []];
            }

            if (!array_key_exists("website_id", $attributes)) {
                $attributes["website_id"] = $this->websiteId;
            }

            return [$id => $attributes];
        })->all();
    }
}
