<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class UpdatePageHeaders extends Command
{
    protected $signature = 'ui:update-headers {--dry-run : Show what would be changed without making changes}';
    protected $description = 'Update all blade files to use the new page-header component';

    // Icon mapping based on page/folder names
    private array $iconMap = [
        // Dashboards
        'dashboard' => ['icon' => 'tachometer-alt', 'color' => 'primary'],
        'alldashboard' => ['icon' => 'chart-line', 'color' => 'primary'],
        'accountdashboard' => ['icon' => 'calculator', 'color' => 'info'],
        'employeedashboard' => ['icon' => 'users', 'color' => 'success'],
        'machinedashboard' => ['icon' => 'cogs', 'color' => 'warning'],
        'manufacturingdashboard' => ['icon' => 'industry', 'color' => 'info'],
        'stockdashboard' => ['icon' => 'boxes', 'color' => 'success'],

        // Customer/Vendor
        'addcustomer' => ['icon' => 'user-plus', 'color' => 'primary'],
        'customerlist' => ['icon' => 'users', 'color' => 'primary'],
        'customerview' => ['icon' => 'user', 'color' => 'info'],
        'customer' => ['icon' => 'users', 'color' => 'primary'],

        // RFQ
        'rfq' => ['icon' => 'file-alt', 'color' => 'info'],
        'rfqdetails' => ['icon' => 'file-alt', 'color' => 'info'],

        // Quotation
        'quotation' => ['icon' => 'file-invoice', 'color' => 'warning'],
        'quotationorder' => ['icon' => 'file-invoice', 'color' => 'warning'],
        'quotationdetails' => ['icon' => 'file-invoice', 'color' => 'info'],

        // Sales
        'sales' => ['icon' => 'shopping-cart', 'color' => 'success'],
        'salesorder' => ['icon' => 'shopping-cart', 'color' => 'success'],
        'salesdetails' => ['icon' => 'shopping-cart', 'color' => 'info'],
        'salesmanagement' => ['icon' => 'chart-bar', 'color' => 'success'],

        // Purchase
        'purchase' => ['icon' => 'shopping-bag', 'color' => 'primary'],
        'purchaseorder' => ['icon' => 'shopping-bag', 'color' => 'primary'],
        'purchasedetails' => ['icon' => 'shopping-bag', 'color' => 'info'],
        'purchasemanagement' => ['icon' => 'clipboard-list', 'color' => 'primary'],

        // Invoice
        'invoice' => ['icon' => 'file-invoice-dollar', 'color' => 'success'],
        'invoiceorder' => ['icon' => 'file-invoice-dollar', 'color' => 'success'],
        'invoicedetails' => ['icon' => 'file-invoice-dollar', 'color' => 'info'],

        // GRN
        'grn' => ['icon' => 'truck-loading', 'color' => 'info'],
        'grnorder' => ['icon' => 'truck-loading', 'color' => 'info'],
        'grndetails' => ['icon' => 'truck-loading', 'color' => 'info'],

        // Route Card
        'routecard' => ['icon' => 'route', 'color' => 'warning'],
        'routecardorder' => ['icon' => 'route', 'color' => 'warning'],
        'routecarddetails' => ['icon' => 'route', 'color' => 'info'],

        // Manufacturing
        'manufacturing' => ['icon' => 'industry', 'color' => 'info'],
        'manufacturingorder' => ['icon' => 'industry', 'color' => 'info'],
        'manufacturingplanning' => ['icon' => 'tasks', 'color' => 'warning'],
        'planning' => ['icon' => 'tasks', 'color' => 'warning'],
        'ready_to_production' => ['icon' => 'play-circle', 'color' => 'success'],
        'projectplanning' => ['icon' => 'project-diagram', 'color' => 'info'],

        // Employee
        'employee' => ['icon' => 'user-tie', 'color' => 'primary'],
        'employeedetails' => ['icon' => 'user-tie', 'color' => 'primary'],
        'employeeattendance' => ['icon' => 'user-clock', 'color' => 'success'],
        'employeecalendar' => ['icon' => 'calendar-alt', 'color' => 'info'],
        'employeedailyreport' => ['icon' => 'clipboard-list', 'color' => 'warning'],
        'employeeleave' => ['icon' => 'calendar-minus', 'color' => 'danger'],
        'employeepayroll' => ['icon' => 'money-check-alt', 'color' => 'success'],
        'attendance_matrix' => ['icon' => 'table', 'color' => 'info'],
        'holiday' => ['icon' => 'umbrella-beach', 'color' => 'warning'],
        'leave' => ['icon' => 'calendar-minus', 'color' => 'danger'],
        'leave_balance' => ['icon' => 'balance-scale', 'color' => 'info'],
        'payroll' => ['icon' => 'money-check-alt', 'color' => 'success'],
        'salary_structure' => ['icon' => 'coins', 'color' => 'warning'],

        // Machine
        'machine' => ['icon' => 'cogs', 'color' => 'warning'],
        'addmachine' => ['icon' => 'plus-circle', 'color' => 'success'],
        'editmachine' => ['icon' => 'edit', 'color' => 'warning'],
        'machinedetails' => ['icon' => 'cogs', 'color' => 'info'],

        // Master Data
        'master' => ['icon' => 'database', 'color' => 'secondary'],
        'accounttype' => ['icon' => 'landmark', 'color' => 'info'],
        'companytype' => ['icon' => 'building', 'color' => 'primary'],
        'conversion_processes' => ['icon' => 'sync-alt', 'color' => 'warning'],
        'process' => ['icon' => 'cog', 'color' => 'info'],
        'producttype' => ['icon' => 'cubes', 'color' => 'success'],
        'rawmaterials' => ['icon' => 'layer-group', 'color' => 'warning'],
        'rfqtype' => ['icon' => 'tags', 'color' => 'info'],
        'stockitems' => ['icon' => 'boxes', 'color' => 'success'],

        // SKU
        'sku' => ['icon' => 'barcode', 'color' => 'info'],
        'skumaster' => ['icon' => 'barcode', 'color' => 'info'],
        'skuapproval' => ['icon' => 'check-circle', 'color' => 'success'],
        'skumovement' => ['icon' => 'exchange-alt', 'color' => 'warning'],

        // Reports
        'reports' => ['icon' => 'chart-bar', 'color' => 'info'],
        'billreport' => ['icon' => 'file-invoice', 'color' => 'success'],
        'customerreport' => ['icon' => 'users', 'color' => 'primary'],
        'employeereport' => ['icon' => 'user-tie', 'color' => 'info'],
        'inventoryreport' => ['icon' => 'warehouse', 'color' => 'warning'],
        'machinereport' => ['icon' => 'cogs', 'color' => 'secondary'],

        // Accounts
        'accounts' => ['icon' => 'calculator', 'color' => 'info'],
        'receivable' => ['icon' => 'hand-holding-usd', 'color' => 'success'],
        'payable' => ['icon' => 'money-bill-wave', 'color' => 'danger'],
        'aging' => ['icon' => 'history', 'color' => 'warning'],
        'balance-sheet' => ['icon' => 'balance-scale', 'color' => 'primary'],
        'cash-flow' => ['icon' => 'money-bill-wave', 'color' => 'success'],
        'profit-loss' => ['icon' => 'chart-line', 'color' => 'info'],

        // Profile & Activity
        'profile' => ['icon' => 'user-circle', 'color' => 'primary'],
        'activity' => ['icon' => 'history', 'color' => 'info'],

        // Edit/View patterns
        'edit' => ['icon' => 'edit', 'color' => 'warning'],
        'view' => ['icon' => 'eye', 'color' => 'info'],
        'show' => ['icon' => 'eye', 'color' => 'info'],
        'index' => ['icon' => 'list', 'color' => 'primary'],
    ];

    public function handle()
    {
        $isDryRun = $this->option('dry-run');
        $basePath = resource_path('views');
        $roles = ['admin', 'manager', 'superadmin'];

        $updatedCount = 0;
        $skippedCount = 0;
        $errorCount = 0;

        foreach ($roles as $role) {
            $rolePath = $basePath . '/' . $role;
            if (!File::isDirectory($rolePath)) {
                $this->warn("Directory not found: {$rolePath}");
                continue;
            }

            $this->info("\n📁 Processing {$role} folder...");

            $files = File::allFiles($rolePath);
            foreach ($files as $file) {
                if ($file->getExtension() !== 'php') continue;

                $filePath = $file->getPathname();
                $content = File::get($filePath);

                // Skip if already using new component
                if (str_contains($content, '<x-layout.page-header')) {
                    $this->line("  ⏭️  Already updated: " . $file->getRelativePathname());
                    $skippedCount++;
                    continue;
                }

                // Check for old header pattern
                $oldPatterns = [
                    // Pattern 1: bg-white p-2 d-sm-flex
                    '/<div class="bg-white p-2 d-sm-flex align-items-center justify-content-between[^"]*">\s*<h1 class="h5 mb-0 text-gray-800">([^<]+)<\/h1>\s*<div class="display-date">.*?<\/div>\s*<div class="display-time"><\/div>\s*<\/div>/s',
                    // Pattern 2: With Page Heading comment
                    '/<!-- Page Heading -->\s*<div class="bg-white p-2 d-sm-flex align-items-center justify-content-between[^"]*">\s*<h1 class="h5 mb-0 text-gray-800">([^<]+)<\/h1>\s*<div class="display-date">.*?<\/div>\s*<div class="display-time"><\/div>\s*<\/div>/s',
                ];

                $matched = false;
                $title = '';

                foreach ($oldPatterns as $pattern) {
                    if (preg_match($pattern, $content, $matches)) {
                        $matched = true;
                        $title = trim($matches[1]);
                        break;
                    }
                }

                if (!$matched) {
                    continue;
                }

                // Determine icon and color based on filename/path
                $iconInfo = $this->getIconForFile($file->getRelativePathname());

                // Create new component tag
                $newHeader = '<x-layout.page-header title="' . $title . '" icon="' . $iconInfo['icon'] . '" iconColor="' . $iconInfo['color'] . '" />';

                // Replace old pattern with new component
                $newContent = $content;
                foreach ($oldPatterns as $pattern) {
                    $newContent = preg_replace($pattern, $newHeader, $newContent);
                }

                if ($newContent !== $content) {
                    if ($isDryRun) {
                        $this->info("  📝 Would update: " . $file->getRelativePathname());
                        $this->line("     Title: {$title}");
                        $this->line("     Icon: {$iconInfo['icon']} ({$iconInfo['color']})");
                    } else {
                        File::put($filePath, $newContent);
                        $this->info("  ✅ Updated: " . $file->getRelativePathname());
                    }
                    $updatedCount++;
                }
            }
        }

        $this->newLine();
        $this->info("═══════════════════════════════════════");
        $this->info("📊 Summary:");
        $this->info("   Updated: {$updatedCount} files");
        $this->info("   Skipped (already done): {$skippedCount} files");
        if ($isDryRun) {
            $this->warn("   ⚠️  DRY RUN - No files were actually modified");
        }
        $this->info("═══════════════════════════════════════");

        return 0;
    }

    private function getIconForFile(string $relativePath): array
    {
        $filename = pathinfo($relativePath, PATHINFO_FILENAME);
        $parts = explode('/', $relativePath);

        // Check filename first
        if (isset($this->iconMap[$filename])) {
            return $this->iconMap[$filename];
        }

        // Check parent folder
        if (count($parts) >= 2) {
            $folder = $parts[count($parts) - 2];
            if (isset($this->iconMap[$folder])) {
                return $this->iconMap[$folder];
            }
        }

        // Check for patterns in filename
        foreach ($this->iconMap as $key => $value) {
            if (str_contains(strtolower($filename), $key)) {
                return $value;
            }
        }

        // Default
        return ['icon' => 'file-alt', 'color' => 'primary'];
    }
}
