<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\UnifiedNumberSequence;
use App\Models\Sale;
use Illuminate\Support\Facades\Log;

class UnifiedNumberController extends Controller
{
    /**
     * Get next unified number
     */
    public function getNextNumber(Request $request)
    {
        try {
            // Generate unified number
            $unifiedNumber = UnifiedNumberSequence::getNextNumber();
            
            Log::info('Unified number generated', [
                'unified_number' => $unifiedNumber,
                'user_id' => auth()->id(),
                'ip' => $request->ip()
            ]);
            
            return response()->json([
                'success' => true,
                'unified_number' => $unifiedNumber,
                'invoice_no' => $unifiedNumber, // Same as unified number
                'receipt_no' => $unifiedNumber, // Same as unified number
                'date' => now()->format('Y-m-d'),
                'timestamp' => now()->toISOString(),
                'today_sales_count' => Sale::getTodaySalesCount()
            ]);
            
        } catch (\Exception $e) {
            Log::error('Failed to generate unified number: ' . $e->getMessage());
            
            // Fallback number generation
            $date = date('Ymd');
            $timestamp = time();
            $unifiedNumber = "INVRCP-{$date}-" . substr($timestamp, -4);
            
            return response()->json([
                'success' => true,
                'unified_number' => $unifiedNumber,
                'invoice_no' => $unifiedNumber,
                'receipt_no' => $unifiedNumber,
                'fallback' => true,
                'message' => 'Using fallback number generation',
                'date' => now()->format('Y-m-d'),
                'timestamp' => now()->toISOString()
            ]);
        }
    }
    
    /**
     * Get current number (without incrementing)
     */
    public function getCurrentNumber(Request $request)
    {
        try {
            $currentNumber = UnifiedNumberSequence::getCurrentNumber();
            $stats = UnifiedNumberSequence::getStats();
            
            return response()->json([
                'success' => true,
                'current_number' => $currentNumber,
                'stats' => $stats,
                'timestamp' => now()->toISOString()
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to get current number: ' . $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * Get number statistics
     */
    public function getStats(Request $request)
    {
        try {
            $stats = UnifiedNumberSequence::getStats();
            
            // Add sales statistics
            $today = now()->format('Y-m-d');
            $salesToday = Sale::whereDate('created_at', $today)->count();
            
            $stats['sales_today'] = $salesToday;
            $stats['server_time'] = now()->toDateTimeString();
            
            return response()->json([
                'success' => true,
                'stats' => $stats,
                'timestamp' => now()->toISOString()
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to get statistics: ' . $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * Test unified number generation
     */
    public function testNumbers(Request $request)
    {
        try {
            $count = min($request->get('count', 5), 10); // Max 10 numbers
            $numbers = [];
            
            for ($i = 0; $i < $count; $i++) {
                $numbers[] = UnifiedNumberSequence::getNextNumber();
            }
            
            return response()->json([
                'success' => true,
                'numbers' => $numbers,
                'count' => count($numbers),
                'timestamp' => now()->toISOString()
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage(),
                'timestamp' => now()->toISOString()
            ], 500);
        }
    }
}