<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\Meeting;
use App\Models\SpendingLog;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        
        $clients = Client::all();
        $totalDeposited = $clients->sum('deposited');
        $totalSpent = $clients->sum('spent');
        $totalBalance = $totalDeposited - $totalSpent;
        $activeClients = $clients->where('status', 'Active')->count();
        
        // Agent query functionality
        $agentQuery = $request->get('agent_query', '');
        $agentResults = [];
        if ($agentQuery) {
            $agentResults = $this->runAgentQuery($agentQuery, $clients);
        }
        
        return view('dashboard', compact('clients', 'totalDeposited', 'totalSpent', 'totalBalance', 'activeClients', 'agentQuery', 'agentResults'));
    }
    
    public function runAgentQuery($query, $clients)
    {
        $text = strtolower(trim($query));
        
        // Advanced Bengali/English keyword detection
        $wantPhones = $this->containsKeywords($text, ['হোয়াটসঅ্যাপ', 'হোয়াটসঅ্যাপ', 'whatsapp', 'ফোন', 'নাম্বার', 'নম্বর', 'phone']);
        $wantFbLink = $this->containsKeywords($text, ['ফেসবুক', 'facebook', 'fb', 'পেইজ', 'page']);
        $wantBalance = $this->containsKeywords($text, ['ব্যালেন্স', 'balance', 'current balance', 'কত টাকা বাকি']);
        $wantScopes = $this->containsKeywords($text, ['স্কোপ', 'scope', 'services', 'সার্ভিস']);
        $wantDeposited = $this->containsKeywords($text, ['ডিপোজিট', 'জমা', 'deposited']);
        $wantSpent = $this->containsKeywords($text, ['খরচ', 'spent']);
        
        // Scope mapping for filtering
        $scopeMap = [
            'facebook' => 'Facebook Marketing',
            'facebook marketing' => 'Facebook Marketing',
            'ফেসবুক' => 'Facebook Marketing',
            'consultancy' => 'Business Consultancy',
            'consult' => 'Business Consultancy',
            'ল্যান্ডিং' => 'Landing Page Design',
            'website' => 'Website Development',
            'কোর্স' => 'Course/Training',
        ];
        
        $askedScope = null;
        foreach (array_keys($scopeMap) as $scopeKey) {
            if ($this->containsKeywords($text, [$scopeKey])) {
                $askedScope = $scopeMap[$scopeKey];
                break;
            }
        }
        
        // Filter clients by scope if specified
        $filteredClients = $clients;
        if ($askedScope) {
            $filteredClients = $clients->filter(function($client) use ($askedScope) {
                $scopes = is_string($client->scopes) ? json_decode($client->scopes, true) : $client->scopes;
                return in_array($askedScope, $scopes ?? []);
            });
        }
        
        // Build dynamic columns based on query
        $columns = [['key' => 'name', 'label' => 'নাম']];
        
        if ($wantPhones) $columns[] = ['key' => 'phone', 'label' => 'হোয়াটসঅ্যাপ/ফোন'];
        if ($wantFbLink) $columns[] = ['key' => 'fb', 'label' => 'Facebook Page'];
        if ($wantDeposited) $columns[] = ['key' => 'deposited', 'label' => 'Deposited'];
        if ($wantSpent) $columns[] = ['key' => 'spent', 'label' => 'Spent'];
        if ($wantBalance) $columns[] = ['key' => 'balance', 'label' => 'Balance'];
        
        // Default to scopes if no specific data requested
        if ($wantScopes || (!$wantPhones && !$wantFbLink && !$wantDeposited && !$wantSpent && !$wantBalance)) {
            $columns[] = ['key' => 'scopes', 'label' => 'স্কোপ'];
        }
        
        // Build results
        $results = [];
        foreach ($filteredClients as $client) {
            $scopes = is_string($client->scopes) ? json_decode($client->scopes, true) : $client->scopes;
            $results[] = [
                'name' => $client->name,
                'phone' => $client->phone,
                'fb' => $client->fb_page,
                'deposited' => number_format($client->deposited, 2),
                'spent' => number_format($client->spent, 2),
                'balance' => number_format($client->deposited - $client->spent, 2),
                'scopes' => implode(', ', $scopes ?? []),
            ];
        }
        
        $summary = count($results) . ' result(s)' . ($askedScope ? ' • Scope = ' . $askedScope : '');
        
        return [
            'columns' => $columns,
            'results' => $results,
            'summary' => $summary
        ];
    }
    
    private function containsKeywords($text, $keywords)
    {
        foreach ($keywords as $keyword) {
            if (strpos($text, strtolower($keyword)) !== false) {
                return true;
            }
        }
        return false;
    }
    
    public function agentQuery(Request $request)
    {
        $query = trim($request->get('q', ''));
        
        if (empty($query)) {
            return response()->json(['error' => 'Query is required'], 400);
        }

        $clients = Client::all();
        $queryResult = $this->runAgentQuery($query, $clients);
        
        return response()->json($queryResult);
    }
    
    public function getSpendingChart(Request $request)
    {
        // Get last 7 days spending data
        $days = [];
        $dayNames = ['রবি', 'সোম', 'মঙ্গল', 'বুধ', 'বৃহস্পতি', 'শুক্র', 'শনি'];
        
        for ($i = 6; $i >= 0; $i--) {
            $date = now()->subDays($i);
            $dayName = $dayNames[$date->dayOfWeek];
            
            // Calculate total spending for this day across all clients
            $daySpending = SpendingLog::whereDate('spend_date', $date->format('Y-m-d'))
                            ->sum('amount');
            
            $days[] = [
                'day' => $dayName,
                'spend' => round($daySpending, 2)
            ];
        }
        
        // If no data, add sample data for visualization
        if (collect($days)->sum('spend') == 0) {
            $days = [
                ['day' => 'সোম', 'spend' => 18],
                ['day' => 'মঙ্গল', 'spend' => 21],
                ['day' => 'বুধ', 'spend' => 16.5],
                ['day' => 'বৃহস্পতি', 'spend' => 25],
                ['day' => 'শুক্র', 'spend' => 32],
                ['day' => 'শনি', 'spend' => 14],
                ['day' => 'রবি', 'spend' => 29],
            ];
        }
        
        return response()->json($days);
    }
    
    public function updateSettings(Request $request)
    {
        $request->validate([
            'threshold' => 'required|numeric|min:0'
        ]);
        
        $request->session()->put('low_balance_threshold', $request->threshold);
        
        return redirect()->route('dashboard')->with('success', 'Low balance threshold updated to $' . number_format($request->threshold, 2));
    }
    
    public function toggleDigest(Request $request)
    {
        $enabled = $request->has('auto_digest') && $request->auto_digest;
        $request->session()->put('auto_digest_enabled', $enabled);
        
        $message = $enabled ? 'Auto digest enabled for daily 9 AM delivery' : 'Auto digest disabled';
        return redirect()->route('dashboard')->with('success', $message);
    }
}
