<?php

namespace App\Console\Commands;

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

class CleanSalesAndCustomers extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'pos:clean-data {--force : Skip confirmation prompt}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Clean all sales and customer data from the database';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('🗑️  POS Data Cleanup Tool');
        $this->info('=======================');
        
        // Show current data counts
        $this->showCurrentCounts();
        
        if (!$this->option('force') && !$this->confirm('⚠️  This will permanently delete ALL sales and customer data. Are you sure?')) {
            $this->info('Operation cancelled.');
            return 0;
        }
        
        $this->warn('Starting data cleanup...');
        
        // Disable foreign key checks
        DB::statement('PRAGMA foreign_keys=0;'); // For SQLite
        
        try {
            $totalDeleted = 0;
            
            // Delete in proper order to avoid foreign key constraints
            $tables = [
                'exchanges' => 'Exchange records',
                'customer_payments' => 'Customer payments', 
                'payments' => 'Payment records',
                'sell_transactions' => 'Sell transactions',
                'direct_sales' => 'Direct sales',
                'sales' => 'Sales records',
                'customers' => 'Customer records'
            ];
            
            foreach ($tables as $table => $description) {
                $count = DB::table($table)->count();
                if ($count > 0) {
                    DB::table($table)->delete();
                    $this->info("✅ Deleted {$count} {$description}");
                    $totalDeleted += $count;
                } else {
                    $this->line("   No {$description} to delete");
                }
            }
            
            // Reset auto-increment counters for SQLite
            $this->info('Resetting ID counters...');
            foreach (array_keys($tables) as $table) {
                DB::statement("DELETE FROM sqlite_sequence WHERE name='{$table}';");
            }
            
            $this->info('✅ Successfully cleaned all data!');
            $this->info("📊 Total records deleted: {$totalDeleted}");
            
        } catch (\Exception $e) {
            $this->error('❌ Error cleaning data: ' . $e->getMessage());
            return 1;
        } finally {
            // Re-enable foreign key checks
            DB::statement('PRAGMA foreign_keys=1;'); // For SQLite
        }
        
        $this->info('🎉 Database cleanup completed successfully!');
        return 0;
    }
    
    private function showCurrentCounts()
    {
        $this->info('Current data in database:');
        
        $tables = [
            'sales' => 'Sales',
            'sell_transactions' => 'Sell Transactions', 
            'direct_sales' => 'Direct Sales',
            'customers' => 'Customers',
            'payments' => 'Payments',
            'customer_payments' => 'Customer Payments',
            'exchanges' => 'Exchanges'
        ];
        
        foreach ($tables as $table => $label) {
            $count = DB::table($table)->count();
            $this->line("  📋 {$label}: {$count}");
        }
        
        $this->newLine();
    }
}
