<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Inside\Content\Models\Contents\PAndP;

class AddPAndPContactsTable extends Migration
{
    use \Inside\Host\Migrations\CreateContentTypes;

    public function up(): void
    {
        if (!Schema::hasTable('desk_p_and_p_contacts')) {
            Schema::create('desk_p_and_p_contacts', function (Blueprint $table) {
                $table->uuid('content_uuid');
                $table->uuid('user_uuid');
                $table->foreign('content_uuid')->references('uuid')->on('inside_content_p_and_p')->onDelete('cascade');
                $table->foreign('user_uuid')->references('uuid')->on('inside_users')->onDelete('cascade');
            });
        }

        $contents = PAndP::query()->get();

        foreach ($contents as $content) {
            $contacts = $content->contact;

            foreach ($contacts as $contact) {
                DB::table('desk_p_and_p_contacts')->insert([
                    'content_uuid' => $content->uuid,
                    'user_uuid' => $contact->uuid
                ]);
            }
        }
    }

    public function down(): void
    {
    }
}
