<?php

namespace App\Http\Controllers\Finance;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Transaction;
use App\Models\Site;
use Carbon\Carbon;
use App\Support\BusinessTime;
use App\Support\SiteCredentialResolver;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        $user = auth()->guard('finance')->user();
        $financeGroup = $user->financeGroup;

        // Get date range from request or use current business day window as default
        if ($request->filled('date_from') || $request->filled('date_to')) {
            $dateFromInput = $request->filled('date_from') ? $request->date_from : $request->date_to;
            $dateToInput = $request->filled('date_to') ? $request->date_to : $request->date_from;
            $fromHasTime = is_string($dateFromInput) && preg_match('/\d{2}:\d{2}/', $dateFromInput);
            $toHasTime = is_string($dateToInput) && preg_match('/\d{2}:\d{2}/', $dateToInput);
            $dateFrom = $fromHasTime
                ? Carbon::parse($dateFromInput)
                : BusinessTime::startOfBusinessDay(Carbon::parse($dateFromInput)->format('Y-m-d'));
            $dateTo = $toHasTime
                ? Carbon::parse($dateToInput)
                : BusinessTime::endOfBusinessDay(Carbon::parse($dateToInput)->format('Y-m-d'));
        } else {
            $businessDate = now('Europe/Istanbul')->subDay()->format('Y-m-d');
            $dateFrom = BusinessTime::startOfBusinessDay($businessDate);
            $dateTo = BusinessTime::endOfBusinessDay($businessDate);
        }

        $dateFromDisplay = $dateFrom->copy();
        $dateToDisplay = $dateTo->copy();

        // Statistics for the selected date range for this finance group only
        $confirmedStatuses = ['approved', 'completed'];

        $periodDeposits = Transaction::deposits()
            ->where('finance_group_id', $financeGroup->id)
            ->whereBetween('created_at', [$dateFrom, $dateTo])
            ->whereIn('status', $confirmedStatuses)
            ->sum('amount');

        $periodWithdrawals = Transaction::withdrawals()
            ->where('finance_group_id', $financeGroup->id)
            ->whereBetween('created_at', [$dateFrom, $dateTo])
            ->whereIn('status', $confirmedStatuses)
            ->sum('amount');

        $periodDepositCount = Transaction::deposits()
            ->where('finance_group_id', $financeGroup->id)
            ->whereBetween('created_at', [$dateFrom, $dateTo])
            ->whereIn('status', $confirmedStatuses)
            ->count();

        $periodWithdrawalCount = Transaction::withdrawals()
            ->where('finance_group_id', $financeGroup->id)
            ->whereBetween('created_at', [$dateFrom, $dateTo])
            ->whereIn('status', $confirmedStatuses)
            ->count();

        $pendingDeposits = Transaction::deposits()
            ->where('finance_group_id', $financeGroup->id)
            ->pending()
            ->count();

        $pendingWithdrawals = Transaction::withdrawals()
            ->where('finance_group_id', $financeGroup->id)
            ->pending()
            ->count();

        $siteStats = Site::orderBy('name')->get()->map(function ($site) use ($dateFrom, $dateTo, $confirmedStatuses, $financeGroup) {
            $siteScope = Transaction::where('finance_group_id', $financeGroup->id)
                ->whereBetween('created_at', [$dateFrom, $dateTo])
                ->where(function ($query) use ($site) {
                    $query->where('site_id', $site->id);
                    if (!empty($site->sid)) {
                        $query->orWhere('sid', $site->sid);
                    }
                    if (!empty($site->api_key)) {
                        $query->orWhere('api_key', $site->api_key);
                    }
                });

            $deposits = (clone $siteScope)->deposits()->whereIn('status', $confirmedStatuses)->sum('amount');
            $withdrawals = (clone $siteScope)->withdrawals()->whereIn('status', $confirmedStatuses)->sum('amount');
            $depositCount = (clone $siteScope)->deposits()->whereIn('status', $confirmedStatuses)->count();
            $withdrawalCount = (clone $siteScope)->withdrawals()->whereIn('status', $confirmedStatuses)->count();
            $autoDepositCount = (clone $siteScope)->deposits()->whereIn('status', $confirmedStatuses)->where('source', 'auto')->count();
            $manualDepositCount = (clone $siteScope)->deposits()->whereIn('status', $confirmedStatuses)->where('source', 'manual')->count();

            return [
                'id' => $site->id,
                'name' => $site->name,
                'is_active' => $site->is_active,
                'deposits' => $deposits,
                'withdrawals' => $withdrawals,
                'deposit_count' => $depositCount,
                'withdrawal_count' => $withdrawalCount,
                'auto_deposit_count' => $autoDepositCount,
                'manual_deposit_count' => $manualDepositCount,
                'kasa_farki' => $deposits - $withdrawals,
            ];
        });

        // Recent transactions for this group in the selected period
        $recentTransactions = Transaction::where('finance_group_id', $financeGroup->id)
            ->whereBetween('created_at', [$dateFrom, $dateTo])
            ->with(['bankAccount', 'approvedBy'])
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        return view('finance.dashboard', compact(
            'user',
            'financeGroup',
            'periodDeposits',
            'periodWithdrawals',
            'periodDepositCount',
            'periodWithdrawalCount',
            'pendingDeposits',
            'pendingWithdrawals',
            'siteStats',
            'recentTransactions',
            'dateFromDisplay',
            'dateToDisplay'
        ));
    }

    public function checkNew(Request $request)
    {
        $since = $request->input('since');

        if (!$since) {
            return response()->json([
                'success' => false,
                'message' => 'Timestamp parametresi gerekli.',
            ], 400);
        }

        $user = auth()->guard('finance')->user();
        $financeGroup = $user->financeGroup;
        $sites = Site::all();

        // Get new transactions for this finance group only
        $newTransactions = Transaction::where('finance_group_id', $financeGroup->id)
            ->where('created_at', '>', $since)
            ->with(['financeGroup', 'bankAccount', 'approvedBy', 'site'])
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function($transaction) use ($sites) {
                $resolvedSite = SiteCredentialResolver::resolveForTransaction($transaction, $sites);
                return [
                    'id' => $transaction->id,
                    'transaction_id' => $transaction->transaction_id,
                    'type' => $transaction->type,
                    'status' => $transaction->status,
                    'amount' => number_format($transaction->amount, 2),
                    'currency' => $transaction->currency,
                    'customer_name' => $transaction->customer_name,
                    'site_name' => $resolvedSite ? $resolvedSite->name : '-',
                    'finance_group' => $transaction->financeGroup ? $transaction->financeGroup->name : '-',
                    'bank_account' => $transaction->bankAccount ? $transaction->bankAccount->account_name : '-',
                    'created_at' => $transaction->created_at->format('d.m.Y H:i'),
                    'created_at_timestamp' => $transaction->created_at->timestamp,
                ];
            });

        // Count new deposits and withdrawals separately
        $newDeposits = $newTransactions->where('type', 'deposit')->count();
        $newWithdrawals = $newTransactions->where('type', 'withdrawal')->count();

        return response()->json([
            'success' => true,
            'count' => $newTransactions->count(),
            'new_deposits' => $newDeposits,
            'new_withdrawals' => $newWithdrawals,
            'data' => $newTransactions->values(),
        ]);
    }
}
