<?php

use App\Producto;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class EliminarProveedor extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('productos', function (Blueprint $table) {
            $table->dropColumn('proveedor_id');
        });
        Schema::dropIfExists('proveedores');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::create('proveedores', function (Blueprint $table) {
            $table->id();
            $table->string('nombre');
            $table->string('direccion')->nullable();
            $table->string('telefono')->nullable();
            $table->string('correo')->nullable();
            $table->boolean('economia_solidaria')->nullable();
            $table->boolean('nacional')->nullable();
            $table->text('detalles_de_pago')->nullable();
            $table->text('comentario')->nullable();
            $table->timestamps();
        });

        Schema::table('productos', function (Blueprint $table) {
            $table->foreignId('proveedor_id')->nullable();
        });

        $proveedor_id = DB::table('proveedores')->insertGetId([
            ['nombre' => 'Proveedor de economía solidaria',
                'economia_solidaria' => 1,
                'nacional' => 1]
        ]);

        foreach (Producto::all() as $producto) {
            $producto->proveedor_id = $producto->es_solidario ? $proveedor_id : null;
            $producto->save();
        }
    }
}