<?php

namespace App\Http\Controllers;

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

class WalletController extends Controller
{
    public function addFunds(Request $request)
    {
        $request->validate([
            'client_id' => 'required|exists:clients,client_id',
            'amount' => 'required|numeric|min:0.01'
        ]);

        $client = Client::where('client_id', $request->client_id)->first();
        $client->increment('deposited', $request->amount);

        return redirect()->route('dashboard')->with('success', 'Funds added successfully!');
    }

    public function recordSpend(Request $request)
    {
        $request->validate([
            'client_id' => 'required|exists:clients,client_id',
            'amount' => 'required|numeric|min:0.01',
            'spend_date' => 'required|date',
            'note' => 'nullable|string|max:255'
        ]);

        $client = Client::where('client_id', $request->client_id)->first();
        $client->increment('spent', $request->amount);

        SpendingLog::create([
            'client_id' => $request->client_id,
            'amount' => $request->amount,
            'spend_date' => $request->spend_date,
            'note' => $request->note ?? 'Ad spend'
        ]);

        return redirect()->route('dashboard')->with('success', 'Spending recorded successfully!');
    }

    public function exportCsv($clientId)
    {
        $client = Client::where('client_id', $clientId)->first();
        if (!$client) {
            return response()->json(['error' => 'Client not found'], 404);
        }

        $logs = SpendingLog::where('client_id', $clientId)
                          ->orderBy('spend_date')
                          ->get();

        $filename = str_replace(' ', '_', $client->name) . '_spend_log.csv';
        
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => "attachment; filename=\"$filename\"",
        ];

        $callback = function() use ($logs, $client) {
            $file = fopen('php://output', 'w');
            fputcsv($file, ['Date', 'Spend(USD)', 'Note', 'Running Spent', 'Current Balance']);
            
            $runningSpent = 0;
            foreach ($logs as $log) {
                $runningSpent += $log->amount;
                $currentBalance = $client->deposited - $runningSpent;
                fputcsv($file, [
                    $log->spend_date->format('Y-m-d'),
                    number_format($log->amount, 2),
                    $log->note,
                    number_format($runningSpent, 2),
                    number_format($currentBalance, 2)
                ]);
            }
            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }
    
    public function exportAllClientsCsv()
    {
        $clients = Client::with('spendingLogs')->get();
        
        $filename = 'all_clients_' . date('Y-m-d') . '.csv';
        
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => "attachment; filename=\"$filename\"",
        ];
        
        $callback = function() use ($clients) {
            $file = fopen('php://output', 'w');
            
            // CSV Headers
            fputcsv($file, [
                'Client ID', 'Name', 'Phone', 'Facebook Page', 'Status',
                'Deposited (USD)', 'Spent (USD)', 'Balance (USD)', 'Scopes',
                'Last Activity', 'Total Transactions'
            ]);
            
            foreach ($clients as $client) {
                $scopes = is_array($client->scopes) ? implode('; ', $client->scopes) : ($client->scopes ?: 'None');
                $lastActivity = $client->spendingLogs->count() > 0 ? 
                    $client->spendingLogs->sortByDesc('spend_date')->first()->spend_date->format('Y-m-d') : 
                    'No activity';
                
                fputcsv($file, [
                    $client->client_id,
                    $client->name,
                    $client->phone,
                    $client->fb_page ?: 'Not provided',
                    $client->status,
                    number_format($client->deposited, 2),
                    number_format($client->spent, 2),
                    number_format($client->deposited - $client->spent, 2),
                    $scopes,
                    $lastActivity,
                    $client->spendingLogs->count()
                ]);
            }
            
            fclose($file);
        };
        
        return response()->stream($callback, 200, $headers);
    }
    
    public function exportToGoogleSheets(Request $request)
    {
        // For MVP, we'll create a CSV format that can be easily imported to Google Sheets
        // In future, this could integrate with Google Sheets API
        
        $clients = Client::with(['spendingLogs', 'meetings'])->get();
        
        // Generate CSV data in memory
        $csvData = [];
        
        // Headers
        $csvData[] = [
            'Client ID', 'Client Name', 'Phone/WhatsApp', 'Facebook Page', 'Status',
            'Deposited (USD)', 'Spent (USD)', 'Current Balance (USD)', 'Services/Scopes',
            'Total Meetings', 'Last Spend Date', 'Total Transactions', 'Average Spend',
            'Portal Key', 'Account Health'
        ];
        
        foreach ($clients as $client) {
            $scopes = is_array($client->scopes) ? implode('; ', $client->scopes) : ($client->scopes ?: 'None');
            $balance = $client->deposited - $client->spent;
            $lastSpendDate = $client->spendingLogs->count() > 0 ? 
                $client->spendingLogs->sortByDesc('spend_date')->first()->spend_date->format('Y-m-d') : 
                'No spending';
            $avgSpend = $client->spendingLogs->count() > 0 ? 
                round($client->spent / $client->spendingLogs->count(), 2) : 0;
            
            // Account health indicator
            $health = 'Good';
            if ($balance <= 10) $health = 'Critical';
            elseif ($balance <= 50) $health = 'Low';
            elseif ($balance <= 100) $health = 'Fair';
            
            $csvData[] = [
                $client->client_id,
                $client->name,
                $client->phone,
                $client->fb_page ?: 'Not provided',
                $client->status,
                number_format($client->deposited, 2),
                number_format($client->spent, 2),
                number_format($balance, 2),
                $scopes,
                $client->meetings->count(),
                $lastSpendDate,
                $client->spendingLogs->count(),
                number_format($avgSpend, 2),
                $client->portal_key ?: 'Not generated',
                $health
            ];
        }
        
        // Create properly formatted CSV string
        $csvString = '';
        foreach ($csvData as $row) {
            $csvString .= implode(',', array_map(function($field) {
                return '"' . str_replace('"', '""', (string)$field) . '"';
            }, $row)) . "\n";
        }
        
        // Return JSON response with complete data structure
        return response()->json([
            'success' => true,
            'message' => 'Data prepared for Google Sheets import',
            'instructions' => [
                '1. Copy the CSV data below',
                '2. Go to Google Sheets (sheets.google.com)',
                '3. Create a new sheet',
                '4. Paste the data (Ctrl+V)',
                '5. Use Data > Split text to columns if needed'
            ],
            'csv_data' => $csvString,
            'total_clients' => $clients->count(),
            'timestamp' => now()->format('Y-m-d H:i:s'),
            'sheets_url' => null // Would be actual Google Sheets URL with full API integration
        ]);
    }
}
