<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     * Migrate data from offices table to unified locations table
     */
    public function up(): void
    {
        // Only run if offices table exists
        if (!Schema::hasTable('offices')) {
            return;
        }

        // Get all offices
        $offices = DB::table('offices')->get();

        // Get default company (first one or ID 1)
        $defaultCompanyId = DB::table('companies')->value('id') ?? 1;

        foreach ($offices as $office) {
            // Use office's company_id or default
            $companyId = $office->company_id ?? $defaultCompanyId;

            // Check if location with same name and company already exists
            $exists = DB::table('locations')
                ->where('company_id', $companyId)
                ->where('name', $office->name)
                ->exists();

            if (!$exists) {
                // Determine type based on office name/characteristics
                $type = $this->determineType($office->name);

                DB::table('locations')->insert([
                    'company_id' => $companyId,
                    'name' => $office->name,
                    'code' => $office->code ?? $this->generateCode($office->name),
                    'address' => $office->address,
                    'city' => $office->city,
                    'province' => $office->province,
                    'latitude' => $office->latitude,
                    'longitude' => $office->longitude,
                    'radius' => $office->radius ?? 100,
                    'category' => 'internal', // Offices are internal locations
                    'type' => $type,
                    'allow_daily_checkin' => true, // Offices allow daily checkin
                    'allow_business_trip' => false, // By default offices are not business trip destinations
                    'is_active' => $office->is_active ?? true,
                    'is_primary' => false,
                    'sort_order' => 0,
                    'created_at' => $office->created_at ?? now(),
                    'updated_at' => now(),
                ]);
            } else {
                // Update existing location to allow daily checkin
                DB::table('locations')
                    ->where('company_id', $companyId)
                    ->where('name', $office->name)
                    ->update([
                        'allow_daily_checkin' => true,
                        'category' => 'internal',
                    ]);
            }
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Remove locations that were migrated from offices
        // Be careful: only delete internal locations that don't allow business trip
        DB::table('locations')
            ->where('category', 'internal')
            ->where('allow_daily_checkin', true)
            ->where('allow_business_trip', false)
            ->delete();
    }

    /**
     * Determine location type based on office name
     */
    private function determineType(string $name): string
    {
        $nameLower = strtolower($name);

        if (str_contains($nameLower, 'pusat') || str_contains($nameLower, 'headquarters') || str_contains($nameLower, 'hq')) {
            return 'headquarters';
        }

        if (str_contains($nameLower, 'cabang') || str_contains($nameLower, 'branch')) {
            return 'branch';
        }

        if (str_contains($nameLower, 'bpkp')) {
            return 'bpkp';
        }

        if (str_contains($nameLower, 'pemda') || str_contains($nameLower, 'pemerintah')) {
            return 'pemda';
        }

        return 'branch'; // Default to branch for offices
    }

    /**
     * Generate code from name
     */
    private function generateCode(string $name): string
    {
        // Take first 3 letters of each word, max 10 chars
        $words = explode(' ', $name);
        $code = '';

        foreach ($words as $word) {
            $code .= strtoupper(substr($word, 0, 3));
            if (strlen($code) >= 10) {
                break;
            }
        }

        return substr($code, 0, 10);
    }
};
