<?php

namespace App\Http\Controllers;

use App\Models\Contacttype;
use App\Models\Credit;
use App\Models\Priceproduct;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;

class MigrationController extends Controller
{
    public function runMigrations()
    {
        Artisan::call('config:clear');
        Artisan::call('cache:clear');
        Artisan::call('config:cache');

        $migratedTables = [];
        $failedMigrations = [];
        $executedSeeders = [];
        $failedSeeders = [];

        // Menjalankan migrations
        $migrationFiles = glob(database_path('migrations') . '/*.php');

        foreach ($migrationFiles as $file) {
            $migrationName = basename($file, '.php');

            if (DB::table('migrations')->where('migration', $migrationName)->exists()) {
                continue;
            }

            try {
                Artisan::call('migrate', ['--path' => 'database/migrations/' . $migrationName . '.php']);
                $migratedTables[] = $migrationName;
            } catch (\Exception $e) {
                $failedMigrations[] = [
                    'migration' => $migrationName,
                    'error' => $e->getMessage(),
                ];
            }
        }

        // Menjalankan seeders
        $seederFiles = glob(database_path('seeders') . '/*.php');

        foreach ($seederFiles as $file) {
            $seederName = basename($file, '.php');

            try {
                Artisan::call('db:seed', ['--class' => $seederName]);
                $executedSeeders[] = $seederName;
            } catch (\Exception $e) {
                $failedSeeders[] = [
                    'seeder' => $seederName,
                    'error' => $e->getMessage(),
                ];
            }
        }

        // Menjalankan Pengecekan di PriceProduct ketika contact_type NULL
        $priceproducts = Priceproduct::whereNull('contact_type')->get();

        foreach ($priceproducts as $priceproduct) {
            $contact = Contacttype::where('name', $priceproduct->name)->first();
            if ($contact) {
                $priceproduct->contact_type = $contact->id;
                $priceproduct->save();
            }
        }

        // Update date yang ada di Credits yang date null diisi dengan created_at
        $credits = Credit::whereNull('date')->get();

        foreach ($credits as $credit) {
            $credit->date = date("Y-d-m", strtotime($credit->created_at));
            $credit->save();
        }

        return response()->json([
            'message' => 'Migrations and Seeders run successfully',
            'migrated_tables' => $migratedTables,
            'failed_migrations' => $failedMigrations,
            'executed_seeders' => $executedSeeders,
            'failed_seeders' => $failedSeeders,
        ]);
    }
}
