<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class ReworkCharges extends Migration
{
	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::table('ab_charge', function (Blueprint $table) {
			$table->dropForeign('fk_chg_acc');
			$table->dropForeign('fk_chg_pdt');
			$table->dropForeign('fk_chg_svc');
			$table->dropIndex('fk_chg_acc_idx');
			$table->dropIndex('fk_chg_svc_idx');
			$table->dropIndex('fk_chg_pdt_idx');
			$table->dropPrimary(['id','account_id','site_id']);
		});

		DB::statement('ALTER TABLE ab_charge RENAME TO charges');
		DB::statement('ALTER TABLE charges RENAME COLUMN date_charge TO charge_date');

		Schema::table('charges', function (Blueprint $table) {
			$table->unique(['id','account_id','site_id']);
			$table->foreign(['account_id','site_id'])->references(['id','site_id'])->on('accounts');
			$table->foreign(['service_id','site_id'])->references(['id','site_id'])->on('ab_service');
			$table->foreign(['product_id','site_id'])->references(['id','site_id'])->on('ab_product');
			$table->integer('user_id')->unsigned()->nullable();
			$table->foreign(['user_id','site_id'])->references(['id','site_id'])->on('users');
		});

		DB::statement('ALTER TABLE charges MODIFY COLUMN id INT auto_increment');
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		abort(500,'cant go back');
	}
}