<?php
namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class DidSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        try {
            $connection = 'master';

            // Check if table exists
            if (!Schema::connection($connection)->hasTable('did')) {
                Log::error('Table "did" does not exist on ' . $connection . ' connection.');
                return;
            }

            // Check if reserved column exists, if not create it
            if (!Schema::connection($connection)->hasColumn('did', 'reserved')) {
                Schema::connection($connection)->table('did', function (Blueprint $table) {
                    $table->boolean('reserved')->default(false);
                });
            }

            // Array of sample CLI numbers (5 samples, user can replace or add)
            $clis = [
                '12345678901',
                '23456789012',
                '34567890123',
                '45678901234',
                '56789012345',
            ];

            foreach ($clis as $cli) {
                $existing = DB::connection($connection)->table('did')->where('cli', $cli)->first();
                if (empty($existing)) {
                    echo "Adding {$cli} to {$connection}.did\n";
                    DB::connection($connection)->table('did')->insert([
                        "parent_id" => '0',
                        "cli" => $cli,
                        "user_id" => 0,
                        "area_code" => '0',
                        "country_code" => '0',
                        "provider" => '0',
                        "voip_provider" => 'didforsale',
                        "reserved" => true
                    ]);
                }
            }
        } catch (\Exception $e) {
            Log::error('Error in DidSeeder: ' . $e->getMessage());
        }
    }
}
