<?php

namespace App\Http\Controllers;

use App\Models\MonthlySaving;
use App\Models\Member;
use App\Models\Income;
use App\Models\AuditLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class SavingController extends Controller
{
    // মাসিক সঞ্চয়ের ডিফল্ট পরিমাণ
    protected $monthlySavingAmount = 600;
    
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = MonthlySaving::with(['member' => function($q) {
            $q->withTrashed();
        }]);
        
        // ফিল্টার
        if ($request->filled('month_year')) {
            $query->where('month_year', $request->month_year);
        } else {
            // ডিফল্টভাবে বর্তমান মাস দেখাও
            $query->where('month_year', '>=', date('Y-m', strtotime('-3 months')));
        }
        
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        
        if ($request->filled('member_id')) {
            $query->where('member_id', $request->member_id);
        }
        
        if ($request->filled('collected_by')) {
            $query->where('collected_by', $request->collected_by);
        }
        
        if ($request->filled('payment_method')) {
            $query->where('payment_method', $request->payment_method);
        }
        
        if ($request->filled('from_date')) {
            $query->whereDate('payment_date', '>=', $request->from_date);
        }
        
        if ($request->filled('to_date')) {
            $query->whereDate('payment_date', '<=', $request->to_date);
        }
        
        // অনুসন্ধান
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('transaction_id', 'like', "%{$search}%")
                  ->orWhere('remarks', 'like', "%{$search}%")
                  ->orWhereHas('member', function($q2) use ($search) {
                      $q2->where('name', 'like', "%{$search}%")
                         ->orWhere('member_id', 'like', "%{$search}%")
                         ->orWhere('phone', 'like', "%{$search}%");
                  });
            });
        }
        
        $savings = $query->orderBy('month_year', 'desc')
                ->orderBy('member_id')
                ->paginate(50);
    
        // মাসের লিস্ট
        $months = MonthlySaving::distinct('month_year')
            ->orderBy('month_year', 'desc')
            ->pluck('month_year');
    
        // Members for filter
        $members = Member::where('status', 'active')
            ->orderBy('name')
            ->get();
    
        // Statistics
        $stats = [
            'total' => MonthlySaving::count(),
            'paid' => MonthlySaving::where('status', 'paid')->count(),
            'pending' => MonthlySaving::where('status', 'pending')->count(),
            'total_amount' => MonthlySaving::where('status', 'paid')->sum('amount'),
            'pending_amount' => MonthlySaving::where('status', 'pending')->sum('amount'),
        ];
    
        return view('savings.index', compact(
            'savings', 
            'months', 
            'members', 
            'stats'
        ));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(Request $request)
    {
        $members = Member::active()->approved()->orderBy('name')->get();
        $selectedMember = null;
        
        if ($request->filled('member_id')) {
            $selectedMember = Member::where('member_id', $request->member_id)->first();
        }
        
        // বর্তমান মাস-বছর
        $currentMonthYear = date('Y-m');
        
        // সদস্যের সর্বশেষ সঞ্চয় দেখুন
        $lastSaving = null;
        if ($selectedMember) {
            $lastSaving = $selectedMember->monthlySavings()
                ->orderBy('month_year', 'desc')
                ->first();
        }
        
        return view('savings.create', compact('members', 'selectedMember', 'currentMonthYear', 'lastSaving'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'member_id' => 'required|exists:members,member_id',
            'month_year' => 'required|date_format:Y-m',
            'amount' => 'required|numeric|min:600', // পরিবর্তিত: 620 থেকে 600
            'payment_date' => 'required|date',
            'payment_method' => 'required|in:cash,bank,bkash,nagad,rocket,card,other',
            'transaction_id' => 'nullable|string|max:100',
            'remarks' => 'nullable|string|max:500',
        ], [
            'amount.min' => 'সঞ্চয়ের পরিমাণ কমপক্ষে ৬০০ টাকা হতে হবে।', // পরিবর্তিত: ৬২০ থেকে ৬০০
            'month_year.date_format' => 'মাস-বছর সঠিক ফরমেটে দিন (YYYY-MM)।',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        // চেক করুন যদি ইতিমধ্যে এই মাসের সঞ্চয় দেওয়া হয়ে থাকে
        $existingSaving = MonthlySaving::where('member_id', $request->member_id)
            ->where('month_year', $request->month_year)
            ->first();
            
        if ($existingSaving) {
            if ($existingSaving->status == 'paid') {
                return redirect()->back()
                    ->with('error', 'এই সদস্য ইতিমধ্যে এই মাসের সঞ্চয় দিয়েছেন।')
                    ->withInput();
            } else {
                // পেন্ডিং থাকলে আপডেট করুন
                $existingSaving->update([
                    'amount' => $request->amount,
                    'payment_date' => $request->payment_date,
                    'payment_method' => $request->payment_method,
                    'transaction_id' => $request->transaction_id,
                    'status' => 'paid',
                    'remarks' => $request->remarks,
                    'collected_by' => auth()->id(),
                ]);
                
                $saving = $existingSaving;
            }
        } else {
            $data = $request->all();
            $data['status'] = 'paid';
            $data['collected_by'] = auth()->id();
            
            $saving = MonthlySaving::create($data);
        }
        
        // আয় হিসাবে রেকর্ড করুন
        $member = Member::where('member_id', $request->member_id)->first();
        
        Income::create([
            'income_number' => Income::generateIncomeNumber(),
            'income_date' => $request->payment_date,
            'category' => 'monthly_saving',
            'source' => 'মাসিক সঞ্চয় - ' . $member->name,
            'amount' => $saving->amount,
            'payment_method' => $request->payment_method,
            'transaction_id' => $request->transaction_id,
            'received_by' => auth()->id(),
            'description' => $request->month_year . ' মাসের সঞ্চয় - ' . $member->member_id,
            'remarks' => $request->remarks,
        ]);
        
        // অডিট লগ
        AuditLog::create([
            'user_id' => auth()->id(),
            'user_type' => auth()->user()->user_type,
            'action' => 'নতুন সঞ্চয় সংগ্রহ',
            'table_name' => 'monthly_savings',
            'record_id' => $saving->id,
            'old_values' => null,
            'new_values' => json_encode($saving->toArray()),
            'ip_address' => $request->ip(),
            'remarks' => 'সঞ্চয় সংগ্রহ করা হয়েছে',
        ]);
        
        return redirect()->route('savings.index')
            ->with('success', 'সঞ্চয় সফলভাবে সংগ্রহ করা হয়েছে।')
            ->with('print_saving_id', $saving->id);
    }

    /**
     * Display the specified resource.
     */
    public function show(MonthlySaving $saving)
    {
        $previousSavings = MonthlySaving::where('member_id', $saving->member_id)
            ->where('id', '<', $saving->id)
            ->orderBy('month_year', 'desc')
            ->limit(5)
            ->get();
            
        $nextSavings = MonthlySaving::where('member_id', $saving->member_id)
            ->where('id', '>', $saving->id)
            ->orderBy('month_year', 'asc')
            ->limit(5)
            ->get();
        
        return view('savings.show', compact('saving', 'previousSavings', 'nextSavings'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(MonthlySaving $saving)
    {
        $members = Member::active()->approved()->orderBy('name')->get();
        
        return view('savings.edit', compact('saving', 'members'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, MonthlySaving $saving)
    {
        $validator = Validator::make($request->all(), [
            'amount' => 'required|numeric|min:600', // পরিবর্তিত: 620 থেকে 600
            'payment_date' => 'required|date',
            'payment_method' => 'required|in:cash,bank,bkash,nagad,rocket,card,other',
            'transaction_id' => 'nullable|string|max:100',
            'status' => 'required|in:pending,paid,overdue,cancelled',
            'remarks' => 'nullable|string|max:500',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $oldData = $saving->toArray();
        $oldStatus = $saving->status;
        
        $saving->update($request->all());
        
        // যদি স্ট্যাটাস পেইড হয় এবং আগে পেন্ডিং/ওভারডিউ ছিল
        if ($request->status == 'paid' && in_array($oldStatus, ['pending', 'overdue'])) {
            // আয় হিসাবে রেকর্ড করুন
            $member = $saving->member;
            
            Income::create([
                'income_number' => Income::generateIncomeNumber(),
                'income_date' => $request->payment_date,
                'category' => 'monthly_saving',
                'source' => 'মাসিক সঞ্চয় - ' . $member->name,
                'amount' => $saving->amount,
                'payment_method' => $request->payment_method,
                'transaction_id' => $request->transaction_id,
                'received_by' => auth()->id(),
                'description' => $saving->month_year . ' মাসের সঞ্চয় (আপডেট)',
                'remarks' => $request->remarks,
            ]);
        }
        
        // যদি স্ট্যাটাস ক্যান্সেলড হয় এবং আগে পেইড ছিল
        if ($request->status == 'cancelled' && $oldStatus == 'paid') {
            // আয় ডিলিট বা রিভার্স করুন (বাস্তবায়ন প্রয়োজন)
        }
        
        // অডিট লগ
        AuditLog::create([
            'user_id' => auth()->id(),
            'user_type' => auth()->user()->user_type,
            'action' => 'সঞ্চয় তথ্য আপডেট',
            'table_name' => 'monthly_savings',
            'record_id' => $saving->id,
            'old_values' => json_encode($oldData),
            'new_values' => json_encode($saving->toArray()),
            'ip_address' => $request->ip(),
        ]);
        
        return redirect()->route('savings.show', $saving)
            ->with('success', 'সঞ্চয় তথ্য সফলভাবে আপডেট করা হয়েছে।');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request, MonthlySaving $saving)
    {
        if ($saving->status == 'paid') {
            return redirect()->back()
                ->with('error', 'পরিশোধিত সঞ্চয় ডিলিট করা যাবে না। স্ট্যাটাস "ক্যান্সেলড" করুন।');
        }
        
        $savingData = $saving->toArray();
        $saving->delete();
        
        // অডিট লগ
        AuditLog::create([
            'user_id' => auth()->id(),
            'user_type' => auth()->user()->user_type,
            'action' => 'সঞ্চয় ডিলিট',
            'table_name' => 'monthly_savings',
            'record_id' => $saving->id,
            'old_values' => json_encode($savingData),
            'new_values' => null,
            'ip_address' => $request->ip(),
            'remarks' => $request->input('reason', 'কোনো কারণ উল্লেখ করা হয়নি'),
        ]);
        
        return redirect()->route('savings.index')
            ->with('success', 'সঞ্চয় সফলভাবে ডিলিট করা হয়েছে।');
    }

    /**
     * মাসিক সঞ্চয় সংগ্রহ (বাল্ক)
     */
    public function collectBulk(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'month_year' => 'required|date_format:Y-m',
            'payment_date' => 'required|date',
            'payment_method' => 'required|in:cash,bank,bkash,nagad,rocket,card,other',
            'member_ids' => 'required|array|min:1',
            'member_ids.*' => 'exists:members,member_id',
            'remarks' => 'nullable|string|max:500',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        DB::beginTransaction();
        
        try {
            $monthYear = $request->month_year;
            $paymentDate = $request->payment_date;
            $paymentMethod = $request->payment_method;
            $collectedBy = auth()->id();
            $remarks = $request->remarks;
            
            $successCount = 0;
            $skippedCount = 0;
            $totalAmount = 0;
            
            foreach ($request->member_ids as $memberId) {
                $member = Member::where('member_id', $memberId)->first();
                
                if (!$member) {
                    $skippedCount++;
                    continue;
                }
                
                // চেক করুন যদি ইতিমধ্যে এই মাসের সঞ্চয় দেওয়া হয়ে থাকে
                $existingSaving = MonthlySaving::where('member_id', $memberId)
                    ->where('month_year', $monthYear)
                    ->first();
                    
                if ($existingSaving) {
                    if ($existingSaving->status == 'pending' || $existingSaving->status == 'overdue') {
                        // পেন্ডিং থাকলে আপডেট করুন
                        $existingSaving->update([
                            'amount' => $member->monthly_saving ?? $this->monthlySavingAmount, // পরিবর্তিত
                            'payment_date' => $paymentDate,
                            'payment_method' => $paymentMethod,
                            'status' => 'paid',
                            'remarks' => $remarks,
                            'collected_by' => $collectedBy,
                        ]);
                        
                        $saving = $existingSaving;
                        $successCount++;
                        $totalAmount += $saving->amount;
                    } else {
                        $skippedCount++;
                        continue;
                    }
                } else {
                    $amount = $member->monthly_saving ?? $this->monthlySavingAmount; // পরিবর্তিত
                    
                    $saving = MonthlySaving::create([
                        'member_id' => $memberId,
                        'month_year' => $monthYear,
                        'amount' => $amount,
                        'payment_date' => $paymentDate,
                        'payment_method' => $paymentMethod,
                        'status' => 'paid',
                        'collected_by' => $collectedBy,
                        'remarks' => $remarks,
                    ]);
                    
                    $successCount++;
                    $totalAmount += $amount;
                }
                
                // আয় হিসাবে রেকর্ড করুন
                Income::create([
                    'income_number' => Income::generateIncomeNumber(),
                    'income_date' => $paymentDate,
                    'category' => 'monthly_saving',
                    'source' => 'মাসিক সঞ্চয় - ' . $member->name,
                    'amount' => $saving->amount,
                    'payment_method' => $paymentMethod,
                    'received_by' => $collectedBy,
                    'description' => $monthYear . ' মাসের সঞ্চয় (বাল্ক কালেকশন)',
                    'remarks' => $remarks,
                ]);
            }
            
            DB::commit();
            
            // অডিট লগ
            AuditLog::create([
                'user_id' => auth()->id(),
                'user_type' => auth()->user()->user_type,
                'action' => 'বাল্ক সঞ্চয় সংগ্রহ',
                'table_name' => 'monthly_savings',
                'record_id' => null,
                'old_values' => null,
                'new_values' => json_encode($request->all()),
                'ip_address' => $request->ip(),
                'remarks' => sprintf('সফল: %d, ডুপ্লিকেট: %d, মোট টাকা: %s', 
                    $successCount, $skippedCount, number_format($totalAmount, 2)),
            ]);
            
            $message = $successCount . 'টি সঞ্চয় সংগ্রহ করা হয়েছে। মোট আদায়: ' . number_format($totalAmount, 2) . ' ৳';
            if ($skippedCount > 0) {
                $message .= ' ' . $skippedCount . 'টি সদস্যের ইতিমধ্যে এই মাসের সঞ্চয় দেওয়া আছে বা অন্য সমস্যা।';
            }
            
            return redirect()->route('savings.index')
                ->with('success', $message);
                
        } catch (\Exception $e) {
            DB::rollback();
            
            return redirect()->back()
                ->with('error', 'বাল্ক কালেকশনে সমস্যা হয়েছে: ' . $e->getMessage())
                ->withInput();
        }
    }

    /**
     * সদস্যের সঞ্চয় ইতিহাস
     */
    public function history(Request $request)
    {
        $member = auth()->user()->member;
        
        if (!$member) {
            return redirect()->route('dashboard')
                ->with('error', 'আপনার সদস্য প্রোফাইল পাওয়া যায়নি।');
        }
        
        $query = $member->monthlySavings();
        
        // ফিল্টার
        if ($request->filled('month_year')) {
            $query->where('month_year', $request->month_year);
        }
        
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        
        if ($request->filled('from_date')) {
            $query->whereDate('payment_date', '>=', $request->from_date);
        }
        
        if ($request->filled('to_date')) {
            $query->whereDate('payment_date', '<=', $request->to_date);
        }
        
        if ($request->filled('payment_method')) {
            $query->where('payment_method', $request->payment_method);
        }
        
        $savings = $query->orderBy('month_year', 'desc')->paginate(12);
        
        // সারাংশ
        $totalSavings = $member->monthlySavings()->where('status', 'paid')->sum('amount');
        $totalMonths = $member->monthlySavings()->where('status', 'paid')->count();
        $currentMonthSaving = $member->monthlySavings()
            ->where('month_year', date('Y-m'))
            ->first();
        
        // মাসিক রিপোর্ট
        $monthlyReport = $member->monthlySavings()
            ->select('month_year', DB::raw('COUNT(*) as count'), DB::raw('SUM(amount) as total'))
            ->where('status', 'paid')
            ->groupBy('month_year')
            ->orderBy('month_year', 'desc')
            ->get();
        
        return view('savings.history', compact('savings', 'member', 'totalSavings', 'totalMonths', 'currentMonthSaving', 'monthlyReport'));
    }

    /**
     * বকেয়া সঞ্চয় (অগ্রগত)
     */
    public function overdue(Request $request)
    {
        $query = MonthlySaving::with('member')
            ->where('status', 'pending');
        
        // ফিল্টার
        if ($request->filled('month_year')) {
            $query->where('month_year', $request->month_year);
        } else {
            // ডিফল্ট: গত ৩ মাসের অগ্রগত
            $currentMonth = date('Y-m');
            $threeMonthsAgo = date('Y-m', strtotime('-3 months'));
            $query->where('month_year', '<', $currentMonth)
                  ->where('month_year', '>=', $threeMonthsAgo);
        }
        
        if ($request->filled('member_id')) {
            $query->where('member_id', $request->member_id);
        }
        
        if ($request->filled('overdue_days')) {
            $days = (int) $request->overdue_days;
            $cutoffDate = date('Y-m', strtotime("-{$days} days"));
            $query->where('month_year', '<', $cutoffDate);
        }
        
        $overdueSavings = $query->orderBy('month_year', 'asc')
            ->orderBy('created_at', 'asc')
            ->paginate(50);
        
        // মাসের তালিকা
        $months = MonthlySaving::select('month_year')
            ->where('status', 'pending')
            ->groupBy('month_year')
            ->orderBy('month_year', 'desc')
            ->get()
            ->mapWithKeys(function($item) {
                return [$item->month_year => Carbon::createFromFormat('Y-m', $item->month_year)->format('F Y')];
            });
        
        // সদস্য তালিকা (ফিল্টারের জন্য)
        $members = Member::whereIn('member_id', function($query) {
                $query->select('member_id')
                    ->from('monthly_savings')
                    ->where('status', 'pending');
            })
            ->orderBy('name')
            ->get();
        
        // স্ট্যাটিস্টিক্স
        $stats = [
            'total_overdue' => $overdueSavings->total(),
            'total_amount' => $overdueSavings->sum('amount'),
            'current_month_overdue' => MonthlySaving::where('status', 'pending')
                ->where('month_year', '<', date('Y-m'))
                ->count(),
            'three_months_overdue' => MonthlySaving::where('status', 'pending')
                ->where('month_year', '<', date('Y-m', strtotime('-3 months')))
                ->count(),
            'six_months_overdue' => MonthlySaving::where('status', 'pending')
                ->where('month_year', '<', date('Y-m', strtotime('-6 months')))
                ->count(),
        ];
        
        return view('savings.overdue', compact('overdueSavings', 'months', 'members', 'stats'));
    }

    /**
     * সঞ্চয় রিপোর্ট
     */
    public function report(Request $request)
    {
        $query = MonthlySaving::with('member');
        
        // ফিল্টার
        if ($request->filled('month_year')) {
            $query->where('month_year', $request->month_year);
        }
        
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        
        if ($request->filled('from_date')) {
            $query->whereDate('payment_date', '>=', $request->from_date);
        }
        
        if ($request->filled('to_date')) {
            $query->whereDate('payment_date', '<=', $request->to_date);
        }
        
        if ($request->filled('member_id')) {
            $query->where('member_id', $request->member_id);
        }
        
        if ($request->filled('collected_by')) {
            $query->where('collected_by', $request->collected_by);
        }
        
        $savings = $query->orderBy('month_year', 'desc')->get();
        
        // সারাংশ
        $totalAmount = $savings->where('status', 'paid')->sum('amount');
        $totalMembers = $savings->where('status', 'paid')->groupBy('member_id')->count();
        
        // মাসিক সারাংশ
        $monthlySummary = $savings->where('status', 'paid')
            ->groupBy('month_year')
            ->map(function($items, $monthYear) {
                return [
                    'month' => Carbon::createFromFormat('Y-m', $monthYear)->format('F Y'),
                    'count' => $items->count(),
                    'amount' => $items->sum('amount'),
                    'members' => $items->groupBy('member_id')->count()
                ];
            })
            ->sortByDesc(function($item, $key) {
                return $key;
            })
            ->values();
        
        // সদস্য অনুযায়ী সারাংশ
        $memberSummary = $savings->where('status', 'paid')
            ->groupBy('member_id')
            ->map(function($items, $memberId) {
                $member = $items->first()->member ?? null;
                return [
                    'member_id' => $memberId,
                    'name' => $member ? $member->name : 'N/A',
                    'count' => $items->count(),
                    'amount' => $items->sum('amount'),
                    'last_payment' => $items->max('payment_date')
                ];
            })
            ->sortByDesc('amount')
            ->values();
        
        if ($request->has('export')) {
            return $this->exportReport($savings, $monthlySummary, $memberSummary, $request->export);
        }
        
        return view('savings.report', compact('savings', 'totalAmount', 'totalMembers', 'monthlySummary', 'memberSummary'));
    }

    /**
     * সঞ্চয় রিপোর্ট এক্সপোর্ট
     */
    private function exportReport($savings, $monthlySummary, $memberSummary, $format)
    {
        if ($format == 'excel') {
            // Excel এক্সপোর্ট লজিক এখানে যোগ করুন
            return response()->json(['message' => 'Excel export coming soon']);
        }
        
        // PDF রিটার্ন
        return response()->json(['message' => 'PDF export coming soon']);
    }

    /**
     * স্বয়ংক্রিয় সঞ্চয় রিমাইন্ডার জেনারেট
     */
    public function generateReminders(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'month_year' => 'required|date_format:Y-m',
            'payment_date' => 'required|date',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $monthYear = $request->month_year;
        $paymentDate = $request->payment_date;
        
        // সক্রিয় সদস্যদের তালিকা যাদের এই মাসের সঞ্চয় নেই
        $members = Member::active()->approved()
            ->whereDoesntHave('monthlySavings', function($query) use ($monthYear) {
                $query->where('month_year', $monthYear);
            })
            ->get();
        
        $createdCount = 0;
        $skippedCount = 0;
        
        DB::beginTransaction();
        
        try {
            foreach ($members as $member) {
                // ইতিমধ্যে আছে কিনা চেক করুন
                $existing = MonthlySaving::where('member_id', $member->member_id)
                    ->where('month_year', $monthYear)
                    ->first();
                    
                if ($existing) {
                    $skippedCount++;
                    continue;
                }
                
                MonthlySaving::create([
                    'member_id' => $member->member_id,
                    'month_year' => $monthYear,
                    'amount' => $member->monthly_saving ?? $this->monthlySavingAmount, // পরিবর্তিত
                    'payment_date' => $paymentDate,
                    'status' => 'pending',
                    'remarks' => 'স্বয়ংক্রিয় রিমাইন্ডার জেনারেট করা হয়েছে',
                ]);
                
                $createdCount++;
            }
            
            DB::commit();
            
            // অডিট লগ
            AuditLog::create([
                'user_id' => auth()->id(),
                'user_type' => auth()->user()->user_type,
                'action' => 'রিমাইন্ডার জেনারেট',
                'table_name' => 'monthly_savings',
                'record_id' => null,
                'old_values' => null,
                'new_values' => json_encode(['month_year' => $monthYear, 'payment_date' => $paymentDate]),
                'ip_address' => $request->ip(),
                'remarks' => sprintf('তৈরি: %d, ডুপ্লিকেট: %d', $createdCount, $skippedCount),
            ]);
            
            $message = $createdCount . 'টি সদস্যের জন্য স্বয়ংক্রিয় সঞ্চয় রিমাইন্ডার তৈরি করা হয়েছে।';
            if ($skippedCount > 0) {
                $message .= ' ' . $skippedCount . 'টি সদস্যের ইতিমধ্যে রেকর্ড আছে।';
            }
            
            return redirect()->route('savings.overdue')
                ->with('success', $message);
                
        } catch (\Exception $e) {
            DB::rollback();
            
            return redirect()->back()
                ->with('error', 'রিমাইন্ডার জেনারেটে সমস্যা হয়েছে: ' . $e->getMessage())
                ->withInput();
        }
    }

    /**
     * সঞ্চয় রিসেট (নতুন বছরের জন্য)
     */
    public function resetForNewYear(Request $request)
    {
        // শুধুমাত্র অ্যাডমিনের জন্য
        if (auth()->user()->user_type != 'admin') {
            return redirect()->back()
                ->with('error', 'এই ফিচারটি শুধুমাত্র অ্যাডমিনের জন্য।');
        }
        
        $validator = Validator::make($request->all(), [
            'year' => 'required|integer|min:2020|max:' . (date('Y') + 5),
            'payment_date' => 'required|date',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $year = $request->year;
        $paymentDate = $request->payment_date;
        
        // জানুয়ারি মাসের জন্য
        $firstMonth = $year . '-01';
        
        $members = Member::active()->approved()->get();
        
        $createdCount = 0;
        $skippedCount = 0;
        
        DB::beginTransaction();
        
        try {
            foreach ($members as $member) {
                // চেক করুন যদি ইতিমধ্যে তৈরি করা হয়ে থাকে
                $existing = MonthlySaving::where('member_id', $member->member_id)
                    ->where('month_year', $firstMonth)
                    ->first();
                    
                if ($existing) {
                    $skippedCount++;
                    continue;
                }
                
                MonthlySaving::create([
                    'member_id' => $member->member_id,
                    'month_year' => $firstMonth,
                    'amount' => $member->monthly_saving ?? $this->monthlySavingAmount, // পরিবর্তিত
                    'payment_date' => $paymentDate,
                    'status' => 'pending',
                    'remarks' => 'নতুন বছরের জন্য স্বয়ংক্রিয়ভাবে তৈরি করা হয়েছে',
                ]);
                
                $createdCount++;
            }
            
            DB::commit();
            
            // অডিট লগ
            AuditLog::create([
                'user_id' => auth()->id(),
                'user_type' => auth()->user()->user_type,
                'action' => 'নতুন বছরের সঞ্চয় রিসেট',
                'table_name' => 'monthly_savings',
                'record_id' => null,
                'old_values' => null,
                'new_values' => json_encode(['year' => $year, 'payment_date' => $paymentDate]),
                'ip_address' => $request->ip(),
                'remarks' => sprintf('তৈরি: %d, ডুপ্লিকেট: %d', $createdCount, $skippedCount),
            ]);
            
            $message = 'নতুন বছরের (' . $year . ') জন্য ' . $createdCount . 'টি সদস্যের সঞ্চয় এন্ট্রি তৈরি করা হয়েছে।';
            if ($skippedCount > 0) {
                $message .= ' ' . $skippedCount . 'টি সদস্যের ইতিমধ্যে রেকর্ড আছে।';
            }
            
            return redirect()->back()
                ->with('success', $message);
                
        } catch (\Exception $e) {
            DB::rollback();
            
            return redirect()->back()
                ->with('error', 'সঞ্চয় রিসেটে সমস্যা হয়েছে: ' . $e->getMessage())
                ->withInput();
        }
    }

    /**
     * মার্ক মাল্টিপল সেভিংস পেইড
     */
    public function markMultiplePaid(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'saving_ids' => 'required|array|min:1',
            'saving_ids.*' => 'exists:monthly_savings,id',
            'payment_date' => 'required|date',
            'payment_method' => 'required|in:cash,bank,bkash,nagad,rocket,card,other',
            'remarks' => 'nullable|string|max:500',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        DB::beginTransaction();
        
        try {
            $paymentDate = $request->payment_date;
            $paymentMethod = $request->payment_method;
            $remarks = $request->remarks;
            $collectedBy = auth()->id();
            
            $successCount = 0;
            $failedCount = 0;
            $totalAmount = 0;
            
            foreach ($request->saving_ids as $savingId) {
                $saving = MonthlySaving::find($savingId);
                
                if (!$saving || $saving->status == 'paid') {
                    $failedCount++;
                    continue;
                }
                
                $oldStatus = $saving->status;
                
                $saving->update([
                    'payment_date' => $paymentDate,
                    'payment_method' => $paymentMethod,
                    'status' => 'paid',
                    'remarks' => $remarks,
                    'collected_by' => $collectedBy,
                ]);
                
                // আয় হিসাবে রেকর্ড করুন
                $member = $saving->member;
                
                Income::create([
                    'income_number' => Income::generateIncomeNumber(),
                    'income_date' => $paymentDate,
                    'category' => 'monthly_saving',
                    'source' => 'মাসিক সঞ্চয় - ' . $member->name,
                    'amount' => $saving->amount,
                    'payment_method' => $paymentMethod,
                    'received_by' => $collectedBy,
                    'description' => $saving->month_year . ' মাসের সঞ্চয় (বাল্ক মার্ক পেইড)',
                    'remarks' => $remarks,
                ]);
                
                $successCount++;
                $totalAmount += $saving->amount;
            }
            
            DB::commit();
            
            // অডিট লগ
            AuditLog::create([
                'user_id' => auth()->id(),
                'user_type' => auth()->user()->user_type,
                'action' => 'একাধিক সঞ্চয় মার্ক পেইড',
                'table_name' => 'monthly_savings',
                'record_id' => null,
                'old_values' => null,
                'new_values' => json_encode($request->all()),
                'ip_address' => $request->ip(),
                'remarks' => sprintf('সফল: %d, ব্যর্থ: %d, মোট টাকা: %s', 
                    $successCount, $failedCount, number_format($totalAmount, 2)),
            ]);
            
            $message = $successCount . 'টি সঞ্চয় পরিশোধিত মার্ক করা হয়েছে। মোট আদায়: ' . number_format($totalAmount, 2) . ' ৳';
            if ($failedCount > 0) {
                $message .= ' ' . $failedCount . 'টি রেকর্ড ব্যর্থ হয়েছে (ইতিমধ্যে পেইড বা অন্য সমস্যা)।';
            }
            
            return redirect()->route('savings.overdue')
                ->with('success', $message);
                
        } catch (\Exception $e) {
            DB::rollback();
            
            return redirect()->back()
                ->with('error', 'মার্ক পেইডে সমস্যা হয়েছে: ' . $e->getMessage())
                ->withInput();
        }
    }
}