<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class VendorTransactionController extends Controller
{
    public function index(Request $request)
    {
        // Get the authenticated user
        $user = Auth::user();

        if (!$user || $user->role !== 'vendor') {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $now = Carbon::now();
        $filterType = $request->query('filter_type', 'daily');
        $dataType = $request->query('data_type', 'ledger');

        // Define date ranges for filtering
        $todayStart = $now->copy()->startOfDay();
        $yesterdayStart = $now->copy()->subDay()->startOfDay();
        $pastWeekStart = $now->copy()->subDays(7)->startOfDay();
        $last30DaysStart = $now->copy()->subDays(30)->startOfDay();
        $pastYearStart = $now->copy()->subYear()->startOfDay();

        // Fetch data from relevant tables
        $transactions = DB::select('
            SELECT id, user_id, transaction_date, amount, status, payment_method, created_at 
            FROM transactions 
            WHERE user_id = ?', [$user->user_id]
        );

        $vendorPayments = DB::select('
            SELECT id, vendor_id, amount_paid, payment_date, payment_method, remarks, created_at 
            FROM vendor_payment_histories 
            WHERE vendor_id = ?', [$user->user_id]
        );

        $walletTransactions = DB::select('
            SELECT id, vendor_id, order_id, amount, commission, status, added_at 
            FROM wallet_transactions 
            WHERE vendor_id = ?', [$user->user_id]
        );

        // Initialize response structure
        $combinedData = ['total_amount' => 0, 'ledgers' => []];
        $filteredData = [];

        // Combine and filter data based on type
        $filteredData = array_merge(
            $this->formatTransactions($transactions, $filterType, $todayStart, $yesterdayStart, $pastWeekStart, $last30DaysStart, $pastYearStart, $now),
            $this->formatVendorPayments($vendorPayments, $filterType, $todayStart, $yesterdayStart, $pastWeekStart, $last30DaysStart, $pastYearStart, $now),
            $this->formatWalletTransactions($walletTransactions, $filterType, $todayStart, $yesterdayStart, $pastWeekStart, $last30DaysStart, $pastYearStart, $now)
        );

        // Calculate total amount and structure ledgers
        foreach ($filteredData as $item) {
            $combinedData['total_amount'] += $item['total_amount'];
            $combinedData['ledgers'][] = $item;
        }

        return response()->json($combinedData);
    }

    private function formatTransactions($transactions, $filterType, $todayStart, $yesterdayStart, $pastWeekStart, $last30DaysStart, $pastYearStart, $now)
    {
        $filtered = $this->filterByType($transactions, $filterType, $todayStart, $yesterdayStart, $pastWeekStart, $last30DaysStart, $pastYearStart, $now, 'created_at');
        return array_map(function ($transaction) {
            return [
                'date' => Carbon::parse($transaction->created_at)->format('M d, Y'),
                'type' => 'transaction',
                 'order_id'=>null,
                'total_amount' => $transaction->amount,
                'cleaneo_commission' => null,
                'cleaneo_percent' => null,
                'your_earnings' => $transaction->status === 'completed' ? $transaction->amount : null,
                'status' => $transaction->status,
            ];
        }, $filtered);
    }

    private function formatVendorPayments($vendorPayments, $filterType, $todayStart, $yesterdayStart, $pastWeekStart, $last30DaysStart, $pastYearStart, $now)
    {
        $filtered = $this->filterByType($vendorPayments, $filterType, $todayStart, $yesterdayStart, $pastWeekStart, $last30DaysStart, $pastYearStart, $now, 'created_at');
        return array_map(function ($payment) {
            return [
                'date' => Carbon::parse($payment->created_at)->format('M d, Y'),
                'type' => 'vendor_payment',
                 'order_id'=>null,
                'total_amount' => $payment->amount_paid,
                'cleaneo_commission' => null,
                'cleaneo_percent' => null,
                'your_earnings' => $payment->amount_paid,
                'status' => 'paid',
            ];
        }, $filtered);
    }

private function formatWalletTransactions($walletTransactions, $filterType, $todayStart, $yesterdayStart, $pastWeekStart, $last30DaysStart, $pastYearStart, $now)
{
    $filtered = $this->filterByType($walletTransactions, $filterType, $todayStart, $yesterdayStart, $pastWeekStart, $last30DaysStart, $pastYearStart, $now, 'added_at');
    return array_map(function ($walletTransaction) {
        $totalEarnings = round($walletTransaction->amount + $walletTransaction->commission, 2);
        $commissionPercent = $walletTransaction->commission > 0 ? round(($walletTransaction->commission / $totalEarnings) * 100, 2) : 0;

        return [
            'date' => Carbon::parse($walletTransaction->added_at)->format('M d, Y'),
            'type' => 'wallet_transaction',
            'order_id'=>$walletTransaction->order_id,
            'total_amount' => $totalEarnings, // Sum of amount and commission
            'cleaneo_commission' => $walletTransaction->commission,
            'cleaneo_percent' => $commissionPercent, // Calculated percentage
            'your_earnings' => $walletTransaction->amount, // Total earnings includes commission
            'status' => $walletTransaction->status,
        ];
    }, $filtered);
}



    private function filterByType(array $data, $filterType, Carbon $start, Carbon $yesterdayStart, Carbon $pastWeekStart, Carbon $last30DaysStart, Carbon $pastYearStart, Carbon $now, $dateField)
    {
        switch ($filterType) {
            case 'daily':
                return $this->filterByDateRange($data, $start, $now, $dateField);
            case 'yesterday':
                return $this->filterByDateRange($data, $yesterdayStart, $start, $dateField);
            case 'weekly':
                return $this->filterByDateRange($data, $pastWeekStart, $now, $dateField);
            case 'monthly':
                return $this->filterByDateRange($data, $last30DaysStart, $now, $dateField);
            case 'yearly':
                return $this->filterByDateRange($data, $pastYearStart, $now, $dateField);
            default:
                return $data;
        }
    }
    // public function index_earnings(Request $request)
    // {
    //     // Get the authenticated user
    //     $user = Auth::user();

    //     if (!$user || $user->role !== 'vendor') {
    //         return response()->json(['error' => 'Unauthorized'], 403);
    //     }

    //     $now = Carbon::now();
    //     $filterType = $request->query('filter_type', 'daily');
    //     $dataType = $request->query('data_type', null);

    //     // Define date ranges for filtering
    //     $todayStart = $now->copy()->startOfDay();
    //     $yesterdayStart = $now->copy()->subDay()->startOfDay();
    //     $pastWeekStart = $now->copy()->subDays(7)->startOfDay();
    //     $last30DaysStart = $now->copy()->subDays(30)->startOfDay();
    //     $pastYearStart = $now->copy()->subYear()->startOfDay();

    //     // Fetch data from relevant tables
    //     $transactions = DB::select('
    //         SELECT id, user_id, transaction_date, amount, status, payment_method, created_at 
    //         FROM transactions 
    //         WHERE user_id = ?', [$user->user_id]
    //     );

    //     $vendorPayments = DB::select('
    //         SELECT id, vendor_id, amount_paid, payment_date, payment_method, remarks, created_at 
    //         FROM vendor_payment_histories 
    //         WHERE vendor_id = ?', [$user->user_id]
    //     );

    //     $walletTransactions = DB::select('
    //         SELECT id, vendor_id, order_id, amount, commission, status, added_at 
    //         FROM wallet_transactions 
    //         WHERE vendor_id = ?', [$user->user_id]
    //     );

    //     $referralPoints = DB::select('
    //         SELECT id, referrer_id, referred_id, points, created_at, updated_at 
    //         FROM referral_points 
    //         WHERE referrer_id = ?', [$user->id]
    //     );

    //     // Initialize response structure
    //     $combinedData = ['total_earnings' => 0];
    //     $groupedData = [];
    //     $filteredData = [];

    //     // Filter data based on `data_type`
    //     if ($dataType === 'earnings') {
    //         $referralData = $this->filterByType($referralPoints, $filterType, $todayStart, $yesterdayStart, $pastWeekStart, $last30DaysStart, $pastYearStart, $now, 'created_at');
    //         $filteredData = array_merge(
    //             $this->filterByType($vendorPayments, $filterType, $todayStart, $yesterdayStart, $pastWeekStart, $last30DaysStart, $pastYearStart, $now, 'created_at'),
    //             $this->filterByType($walletTransactions, $filterType, $todayStart, $yesterdayStart, $pastWeekStart, $last30DaysStart, $pastYearStart, $now, 'added_at'),
    //             $referralData
    //         );
    //     }

    //     // Group data by date
    //     foreach ($filteredData as $item) {
    //         $dateKey = Carbon::parse($item->created_at ?? $item->added_at)->format('M d, Y');

    //         if (!isset($groupedData[$dateKey])) {
    //             $groupedData[$dateKey] = [
    //                 'date' => $dateKey,
    //                 'total_earning' => 0,
    //                 'earnings' => []
    //             ];
    //         }

    //         // Map specific data for referral points
    //         if (isset($item->points)) {
    //             $item->amount = $item->points;
    //             $item->payment_method = 'Referral Points';
    //             $item->remarks = 'Referral Earnings';

    //             $referredUser = DB::table('users')->where('id', $item->referred_id)->first();
    //             $item->referred_user_name = $referredUser->name ?? 'Unknown User';
    //             $item->referred_user_id = $referredUser->user_id ?? 'Unknown';
    //         } else {
    //             $item->amount = $item->amount_paid ?? $item->amount ?? 0;

    //             if ($item->amount < 0) {
    //                 $item->remarks = 'Payment to Company';
    //             } elseif (isset($item->amount_paid)) {
    //                 $item->payment_method = $item->payment_method ?? 'Vendor Payment';
    //                 $item->remarks = $item->remarks ?? 'Payment Received';
    //             }
    //         }

    //         $groupedData[$dateKey]['total_earning'] += $item->amount;
    //         $groupedData[$dateKey]['earnings'][] = $item;
    //         $combinedData['total_earnings'] += $item->amount;
    //     }

    //     // Format final response structure
    //     $combinedData['earnings'] = array_values($groupedData);

    //     return response()->json($combinedData);
    // }
 public function index_earnings(Request $request)
{
    // Get the authenticated user
    $user = Auth::user();

    if (!$user || $user->role !== 'vendor') {
        return response()->json(['error' => 'Unauthorized'], 403);
    }

    $now = Carbon::now();
    $filterType = $request->query('filter_type', 'daily');
    $dataType = $request->query('data_type', null);

    // Define date ranges for filtering
    $todayStart = $now->copy()->startOfDay();
    $yesterdayStart = $now->copy()->subDay()->startOfDay();
    $pastWeekStart = $now->copy()->subDays(7)->startOfDay();
    $last30DaysStart = $now->copy()->subDays(30)->startOfDay();
    $pastYearStart = $now->copy()->subYear()->startOfDay();

    // Fetch data from relevant tables
    $transactions = DB::select('SELECT id, user_id, transaction_date, amount, status, payment_method, created_at FROM transactions WHERE user_id = ?', [$user->user_id]);

    $vendorPayments = DB::select('SELECT id, vendor_id, amount_paid, payment_date, payment_method, remarks, created_at FROM vendor_payment_histories WHERE vendor_id = ?', [$user->user_id]);

    $walletTransactions = DB::select('SELECT id, vendor_id, order_id, amount, commission, status, added_at FROM wallet_transactions WHERE vendor_id = ?', [$user->user_id]);

    $referralPoints = DB::select('SELECT id, referrer_id, referred_id, points, created_at, updated_at FROM referral_points WHERE referrer_id = ?', [$user->id]);

    // Initialize response structure
    $combinedData = ['total_amount' => 0];
    $earningsData = [];

    // Filter data based on `data_type`
    if ($dataType === 'earnings') {
        $referralData = $this->filterByType($referralPoints, $filterType, $todayStart, $yesterdayStart, $pastWeekStart, $last30DaysStart, $pastYearStart, $now, 'created_at');
        $filteredData = array_merge(
            $this->filterByType($vendorPayments, $filterType, $todayStart, $yesterdayStart, $pastWeekStart, $last30DaysStart, $pastYearStart, $now, 'created_at'),
            $this->filterByType($walletTransactions, $filterType, $todayStart, $yesterdayStart, $pastWeekStart, $last30DaysStart, $pastYearStart, $now, 'added_at'),
            $referralData
        );
    } else {
        $filteredData = [];
    }

    // Group data by date
    foreach ($filteredData as $item) {
        $dateKey = Carbon::parse($item->created_at ?? $item->added_at)->format('M d, Y');

        // Calculate total amount including commission if applicable
        $totalAmount = ($item->commission ?? 0) + ($item->amount ?? 0);
        $commission = $item->commission ?? 0;
        $cleaneoPercent = $totalAmount > 0 ? round(($commission / $totalAmount) * 100, 2) : null;

        $earning = [
            'date' => $dateKey,
            'type' => isset($item->points) ? 'referral_points' : (isset($item->amount_paid) ? 'vendor_payment' : (isset($item->order_id) ? 'wallet_transaction' : 'transaction')),
            'order_id' => $item->order_id ?? null,
            'total_amount' => $totalAmount,
            'cleaneo_commission' => $commission,
            'cleaneo_percent' => $cleaneoPercent,
            'your_earnings' => isset($item->points) ? $item->points : ($item->amount_paid ?? ($totalAmount - $commission)),
            'status' => $item->status ?? null,
            'remarks' => isset($item->points) ? 'Referral Earnings' : ($item->remarks ?? null)
        ];

        if (isset($item->points)) {
            $referredUser = DB::table('users')->where('id', $item->referred_id)->first();
            $earning['referred_user_name'] = $referredUser->name ?? 'Unknown User';
            $earning['referred_user_id'] = $referredUser->user_id ?? 'Unknown';
        }

        $earningsData[] = $earning;
        $combinedData['total_amount'] += $totalAmount - $commission;
    }

    // Format final response structure
    $combinedData['earnings'] = $earningsData;

    return response()->json($combinedData);
}



    private function filterByDateRange(array $data, Carbon $start, Carbon $end, $dateField)
    {
        return array_filter($data, function ($item) use ($start, $end, $dateField) {
            $date = Carbon::parse($item->$dateField);
            return $date->between($start, $end);
        });
    }
}