<?php

namespace App\Http\Controllers\FrontUser;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Call;
use App\Models\WalletTransaction;
use Illuminate\Support\Carbon;

class CallsController extends Controller
{
    public function index()
    {
        $userId = Auth::id();
        
        // Get calls with pagination
        $calls = Call::where('user_id', $userId)
            ->latest()
            ->paginate(20);
        
        // Get call statistics
        $totalCalls = Call::where('user_id', $userId)->count();
        $thisMonthCalls = Call::where('user_id', $userId)
            ->whereMonth('date_time', Carbon::now()->month)
            ->count();
        $totalDuration = Call::where('user_id', $userId)
            ->where('status', 'completed')
            ->sum('duration');
        $totalCost = Call::where('user_id', $userId)
            ->where('status', 'completed')
            ->sum('cost');
        
        // Get recent calls
        $recentCalls = Call::where('user_id', $userId)
            ->latest()
            ->take(5)
            ->get();
        
        return view('FrontUser.calls.index', compact(
            'calls',
            'totalCalls',
            'thisMonthCalls',
            'totalDuration',
            'totalCost',
            'recentCalls'
        ));
    }

    public function create()
    {
        $userId = Auth::id();
        $user = Auth::user();
        
        // Check if user has sufficient balance
        $minBalance = 50; // Minimum balance required for calls
        $hasBalance = $user->wallet_balance >= $minBalance;
        
        // Get license status
        $licenseStatus = null;
        if ($user->license) {
            $license = $user->license;
            $licenseStatus = [
                'isActive' => $license->is_active,
                'startsAt' => $license->starts_at,
                'expiresAt' => $license->expires_at,
                'key' => $license->key
            ];
        }
        
        // Get call packages/plans
        $callPackages = [
            [
                'id' => 'basic',
                'name' => 'Basic Plan',
                'price' => 0.50,
                'duration' => 60,
                'features' => ['Standard quality', 'Basic recording', 'Email support']
            ],
            [
                'id' => 'premium',
                'name' => 'Premium Plan',
                'price' => 1.00,
                'duration' => 120,
                'features' => ['HD quality', 'Advanced recording', 'Priority support', 'Analytics']
            ],
            [
                'id' => 'enterprise',
                'name' => 'Enterprise Plan',
                'price' => 2.00,
                'duration' => 300,
                'features' => ['4K quality', 'Full recording', '24/7 support', 'Advanced analytics', 'API access']
            ]
        ];
        
        return view('FrontUser.calls.create', compact('hasBalance', 'callPackages', 'minBalance', 'licenseStatus'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'phone_number' => 'required|string|min:10|max:15',
            'package' => 'required|in:basic,premium,enterprise',
            'scheduled_time' => 'nullable|date|after:now'
        ]);

        $userId = Auth::id();
        $user = Auth::user();
        
        // Get package details
        $packages = [
            'basic' => ['price' => 0.50, 'duration' => 60],
            'premium' => ['price' => 1.00, 'duration' => 120],
            'enterprise' => ['price' => 2.00, 'duration' => 300]
        ];
        
        $package = $packages[$request->package];
        $cost = $package['price'];
        
        // Check balance
        if ($user->wallet_balance < $cost) {
            return response()->json([
                'success' => false,
                'message' => 'Insufficient wallet balance. Please add funds.'
            ], 400);
        }
        
        // Create call
        $call = Call::create([
            'user_id' => $userId,
            'phone_number' => $request->phone_number,
            'package' => $request->package,
            'cost' => $cost,
            'duration' => $package['duration'],
            'status' => 'scheduled',
            'date_time' => $request->scheduled_time ?? now()->addMinutes(5),
            'reference_id' => 'CALL_' . time() . '_' . $userId
        ]);
        
        // Deduct cost from wallet
        $user->decrement('wallet_balance', $cost);
        
        // Create transaction record
        WalletTransaction::create([
            'user_id' => $userId,
            'type' => 'debit',
            'amount' => $cost,
            'status' => 'completed',
            'payment_method' => 'wallet',
            'description' => 'Call booking - ' . ucfirst($request->package) . ' plan',
            'reference_id' => 'CALL_TXN_' . $call->id
        ]);
        
        return response()->json([
            'success' => true,
            'message' => 'Call scheduled successfully!',
            'call_id' => $call->id,
            'reference_id' => $call->reference_id
        ]);
    }

    public function show($id)
    {
        $userId = Auth::id();
        
        $call = Call::where('user_id', $userId)
            ->where('id', $id)
            ->firstOrFail();
        
        // Get call analytics
        $analytics = [
            'duration' => $call->duration,
            'cost' => $call->cost,
            'quality' => $call->quality ?? 'Standard',
            'recording_url' => $call->recording_url ?? null,
            'transcript' => $call->transcript ?? null,
            'sentiment' => $call->sentiment ?? 'Neutral',
            'keywords' => $call->keywords ?? []
        ];
        
        return view('FrontUser.calls.show', compact('call', 'analytics'));
    }

    public function edit($id)
    {
        $userId = Auth::id();
        
        $call = Call::where('user_id', $userId)
            ->where('id', $id)
            ->whereIn('status', ['scheduled', 'pending'])
            ->firstOrFail();
        
        return view('FrontUser.calls.edit', compact('call'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'phone_number' => 'required|string|min:10|max:15',
            'scheduled_time' => 'required|date|after:now'
        ]);

        $userId = Auth::id();
        
        $call = Call::where('user_id', $userId)
            ->where('id', $id)
            ->whereIn('status', ['scheduled', 'pending'])
            ->firstOrFail();
        
        $call->update([
            'phone_number' => $request->phone_number,
            'date_time' => $request->scheduled_time
        ]);
        
        return response()->json([
            'success' => true,
            'message' => 'Call updated successfully!'
        ]);
    }

    public function destroy($id)
    {
        $userId = Auth::id();
        
        $call = Call::where('user_id', $userId)
            ->where('id', $id)
            ->whereIn('status', ['scheduled', 'pending'])
            ->firstOrFail();
        
        // Refund the cost
        $user = Auth::user();
        $user->increment('wallet_balance', $call->cost);
        
        // Create refund transaction
        WalletTransaction::create([
            'user_id' => $userId,
            'type' => 'credit',
            'amount' => $call->cost,
            'status' => 'completed',
            'payment_method' => 'refund',
            'description' => 'Call cancellation refund',
            'reference_id' => 'REFUND_' . $call->reference_id
        ]);
        
        $call->delete();
        
        return response()->json([
            'success' => true,
            'message' => 'Call cancelled and refunded successfully!'
        ]);
    }

    public function startCall($id)
    {
        $userId = Auth::id();
        
        $call = Call::where('user_id', $userId)
            ->where('id', $id)
            ->where('status', 'scheduled')
            ->firstOrFail();
        
        // Simulate call start
        $call->update([
            'status' => 'in_progress',
            'started_at' => now()
        ]);
        
        return response()->json([
            'success' => true,
            'message' => 'Call started successfully!',
            'call_id' => $call->id
        ]);
    }

    public function endCall($id)
    {
        $userId = Auth::id();
        
        $call = Call::where('user_id', $userId)
            ->where('id', $id)
            ->where('status', 'in_progress')
            ->firstOrFail();
        
        // Simulate call end
        $actualDuration = rand(30, $call->duration);
        $call->update([
            'status' => 'completed',
            'ended_at' => now(),
            'actual_duration' => $actualDuration,
            'quality' => ['Standard', 'Good', 'Excellent'][rand(0, 2)],
            'recording_url' => 'https://example.com/recordings/' . $call->reference_id . '.mp3',
            'transcript' => 'Sample transcript of the call...',
            'sentiment' => ['Positive', 'Neutral', 'Negative'][rand(0, 2)],
            'keywords' => ['business', 'meeting', 'discussion', 'project']
        ]);
        
        return response()->json([
            'success' => true,
            'message' => 'Call completed successfully!',
            'duration' => $actualDuration,
            'recording_url' => $call->recording_url
        ]);
    }

    public function getCallAnalytics()
    {
        $userId = Auth::id();
        
        // Get analytics data
        $analytics = [
            'total_calls' => Call::where('user_id', $userId)->count(),
            'completed_calls' => Call::where('user_id', $userId)->where('status', 'completed')->count(),
            'total_duration' => Call::where('user_id', $userId)->where('status', 'completed')->sum('actual_duration'),
            'total_cost' => Call::where('user_id', $userId)->where('status', 'completed')->sum('cost'),
            'average_duration' => Call::where('user_id', $userId)->where('status', 'completed')->avg('actual_duration'),
            'most_used_package' => Call::where('user_id', $userId)->selectRaw('package, COUNT(*) as count')->groupBy('package')->orderBy('count', 'desc')->first()->package ?? 'basic',
            'calls_this_month' => Call::where('user_id', $userId)->whereMonth('date_time', Carbon::now()->month)->count(),
            'cost_this_month' => Call::where('user_id', $userId)->whereMonth('date_time', Carbon::now()->month)->sum('cost')
        ];
        
        return response()->json($analytics);
    }

    public function bulkCreate()
    {
        $userId = Auth::id();
        $user = Auth::user();
        
        // Check if user has sufficient balance
        $minBalance = 50; // Minimum balance required for calls
        $hasBalance = $user->wallet_balance >= $minBalance;
        
        // Get license status
        $licenseStatus = null;
        if ($user->license) {
            $license = $user->license;
            $licenseStatus = [
                'isActive' => $license->is_active,
                'startsAt' => $license->starts_at,
                'expiresAt' => $license->expires_at,
                'key' => $license->key
            ];
        }
        
        return view('FrontUser.calls.bulk-create', compact('hasBalance', 'licenseStatus'));
    }

    public function bulkStore(Request $request)
    {
        $request->validate([
            'excel_file' => 'required|file|mimes:xlsx,xls,csv|max:10240', // 10MB max
            'package' => 'required|in:basic,premium,enterprise',
            'scheduled_time' => 'nullable|date|after:now'
        ]);

        $userId = Auth::id();
        $user = Auth::user();
        
        // Get package details
        $packages = [
            'basic' => ['price' => 0.50, 'duration' => 60],
            'premium' => ['price' => 1.00, 'duration' => 120],
            'enterprise' => ['price' => 2.00, 'duration' => 300]
        ];
        
        $package = $packages[$request->package];
        $costPerCall = $package['price'];
        
        try {
            // Process Excel file
            $file = $request->file('excel_file');
            $data = $this->processExcelFile($file);
            
            if (empty($data)) {
                return response()->json([
                    'success' => false,
                    'message' => 'No valid phone numbers found in the Excel file.'
                ], 400);
            }
            
            $totalCalls = count($data);
            $totalCost = $totalCalls * $costPerCall;
            
            // Check balance
            if ($user->wallet_balance < $totalCost) {
                return response()->json([
                    'success' => false,
                    'message' => "Insufficient wallet balance. Required: ₹{$totalCost}, Available: ₹{$user->wallet_balance}"
                ], 400);
            }
            
            // Create calls
            $createdCalls = [];
            $scheduledTime = $request->scheduled_time ?? now()->addMinutes(5);
            
            foreach ($data as $index => $phoneNumber) {
                $call = Call::create([
                    'user_id' => $userId,
                    'phone_number' => $phoneNumber,
                    'package' => $request->package,
                    'cost' => $costPerCall,
                    'duration' => $package['duration'],
                    'status' => 'scheduled',
                    'date_time' => $scheduledTime->addMinutes($index * 5), // Stagger calls by 5 minutes
                    'reference_id' => 'BULK_CALL_' . time() . '_' . $userId . '_' . $index
                ]);
                
                $createdCalls[] = $call;
            }
            
            // Deduct total cost from wallet
            $user->decrement('wallet_balance', $totalCost);
            
            // Create transaction record
            WalletTransaction::create([
                'user_id' => $userId,
                'type' => 'debit',
                'amount' => $totalCost,
                'status' => 'completed',
                'payment_method' => 'wallet',
                'description' => "Bulk call booking - {$totalCalls} calls ({$request->package} plan)",
                'reference_id' => 'BULK_TXN_' . time() . '_' . $userId
            ]);
            
            return response()->json([
                'success' => true,
                'message' => "Successfully scheduled {$totalCalls} calls!",
                'total_calls' => $totalCalls,
                'total_cost' => $totalCost,
                'calls' => $createdCalls
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error processing Excel file: ' . $e->getMessage()
            ], 500);
        }
    }
    
    private function processExcelFile($file)
    {
        $data = [];
        $extension = $file->getClientOriginalExtension();
        
        if ($extension === 'csv') {
            $data = $this->processCsvFile($file);
        } else {
            $data = $this->processExcelFileContent($file);
        }
        
        return $data;
    }
    
    private function processCsvFile($file)
    {
        $data = [];
        $handle = fopen($file->getPathname(), 'r');
        
        while (($row = fgetcsv($handle)) !== false) {
            if (isset($row[0]) && !empty(trim($row[0]))) {
                $phoneNumber = trim($row[0]);
                // Basic phone number validation
                if (preg_match('/^[\+]?[0-9\s\-\(\)]{10,15}$/', $phoneNumber)) {
                    $data[] = $phoneNumber;
                }
            }
        }
        
        fclose($handle);
        return $data;
    }
    
    private function processExcelFileContent($file)
    {
        // For Excel files, we'll use a simple approach
        // In production, you might want to use PhpSpreadsheet
        $data = [];
        
        // This is a simplified version - in production, use PhpSpreadsheet
        $csvData = file_get_contents($file->getPathname());
        $lines = explode("\n", $csvData);
        
        foreach ($lines as $line) {
            $phoneNumber = trim($line);
            if (!empty($phoneNumber) && preg_match('/^[\+]?[0-9\s\-\(\)]{10,15}$/', $phoneNumber)) {
                $data[] = $phoneNumber;
            }
        }
        
        return $data;
    }
}