<?php

namespace App\Http\Controllers;

use App\Models\Fee;
use App\Models\Student;
use App\Models\Classes;
use App\Models\Payment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Barryvdh\DomPDF\Facade\Pdf;

class FeeController extends Controller
{
    /**
     * Display fee search page
     */
    public function index()
    {
        $classes = Classes::where('status', 1)->get();
        $recentPayments = Fee::with('student')
                            ->where('payment_status', 'paid')
                            ->where('paid_amount', '>', 0)
                            ->orderBy('updated_at', 'desc')
                            ->limit(10)
                            ->get();
        
        return view('fees.index', compact('classes', 'recentPayments'));
    }

    /**
     * Search fees by student ID
     */
    public function search(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'student_id' => 'required|string|exists:students,student_id',
            'action' => 'required|in:due,all,summary'
        ]);

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

        $student = Student::where('student_id', $request->student_id)
                          ->with('class')
                          ->firstOrFail();

        $query = Fee::with('student')
                    ->where('student_id', $student->id);

        if ($request->action == 'due') {
            $fees = $query->due()->orderBy('month_year')->get();
        } else {
            $fees = $query->orderBy('month_year', 'desc')->get();
        }

        $summary = [
            'total_fees' => $fees->sum('payable_amount'),
            'total_paid' => $fees->sum('paid_amount'),
            'total_due' => $fees->sum('due_amount'),
            'total_late_fee' => $fees->sum('late_fee'),
            'total_discount' => $fees->sum('discount')
        ];

        if ($request->action == 'summary') {
            return view('fees.summary', compact('student', 'fees', 'summary'));
        }

        return view('fees.show', compact('student', 'fees', 'summary'));
    }

    /**
     * Show payment page
     */
    public function pay($id)
    {
        $fee = Fee::with('student', 'class')->findOrFail($id);
        
        // বিলম্ব ফি আপডেট
        if ($fee->payment_status != 'paid') {
            $dueDate = $fee->month_year->copy()->addDays(30);
            $lateFee = Fee::calculateLateFee($fee->payable_amount, $dueDate);
            $fee->late_fee = $lateFee;
            $fee->payable_amount = $fee->total_amount + $lateFee - $fee->discount;
            $fee->due_amount = $fee->payable_amount - $fee->paid_amount;
        }

        return view('fees.pay', compact('fee'));
    }

    /**
     * Process payment
     */
    public function processPayment(Request $request, $id)
    {
        $fee = Fee::with('student')->findOrFail($id);

        $validator = Validator::make($request->all(), [
            'amount' => 'required|numeric|min:1|max:' . $fee->due_amount,
            'payment_method' => 'required|in:cash,bKash,nagad,rocket,bank,other',
            'transaction_id' => 'nullable|string|max:100',
            'mobile_number' => 'nullable|string|max:20',
            'payment_date' => 'required|date',
            'remarks' => 'nullable|string|max:255'
        ]);

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

        DB::beginTransaction();
        
        try {
            // পুরনো পেমেন্ট আপডেট
            $fee->paid_amount += $request->amount;
            $fee->last_payment_date = $request->payment_date;
            $fee->payment_method = $request->payment_method;
            $fee->transaction_id = $request->transaction_id ?? 'MANUAL-' . time();
            $fee->collected_by = auth()->id();
            $fee->remarks = $request->remarks;

            // পেমেন্ট স্ট্যাটাস আপডেট
            if (abs($fee->paid_amount - $fee->payable_amount) < 0.01) {
                $fee->payment_status = 'paid';
                $fee->due_amount = 0;
            } elseif ($fee->paid_amount > 0) {
                $fee->payment_status = 'partial';
                $fee->due_amount = $fee->payable_amount - $fee->paid_amount;
            }

            $fee->save();

            // পেমেন্ট রেকর্ড তৈরি
            $payment = Payment::create([
                'fee_id' => $fee->id,
                'student_id' => $fee->student_id,
                'amount' => $request->amount,
                'payment_method' => $request->payment_method,
                'transaction_id' => $request->transaction_id,
                'mobile_number' => $request->mobile_number,
                'payment_date' => $request->payment_date,
                'collected_by' => auth()->id(),
                'remarks' => $request->remarks
            ]);

            DB::commit();

            // SMS পাঠান (ঐচ্ছিক)
            $this->sendPaymentSMS($fee->student, $request->amount);

            return redirect()->route('fees.receipt', $payment->id)
                           ->with('success', 'পেমেন্ট সফলভাবে সম্পন্ন হয়েছে।');

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Payment failed: ' . $e->getMessage());
            
            return redirect()->back()
                           ->with('error', 'পেমেন্ট প্রক্রিয়াকরণে সমস্যা হয়েছে।')
                           ->withInput();
        }
    }

    /**
     * Show payment receipt
     */
    public function receipt($id)
    {
        $payment = Payment::with('fee.student', 'collector')->findOrFail($id);
        
        if (request()->has('print')) {
            return view('fees.receipt-print', compact('payment'));
        }
        
        return view('fees.receipt', compact('payment'));
    }

    /**
     * Download payment certificate
     */
    public function downloadCertificate($id)
    {
        $fee = Fee::with('student', 'class')->findOrFail($id);
        
        if ($fee->payment_status != 'paid') {
            return redirect()->back()
                           ->with('error', 'শুধুমাত্র পরিশোধিত ফির সার্টিফিকেট ডাউনলোড করা যাবে।');
        }

        $pdf = Pdf::loadView('fees.certificate-pdf', compact('fee'));
        
        return $pdf->download('fee_certificate_' . $fee->fee_no . '.pdf');
    }

    /**
     * Bulk fee generation
     */
    public function bulkGenerate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'class_id' => 'required|exists:classes,id',
            'month' => 'required|integer|between:1,12',
            'year' => 'required|integer|min:2020|max:2030'
        ]);

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

        // চেক করা যে এই মাসের ফি ইতিমধ্যে জেনারেট হয়েছে কিনা
        $exists = Fee::where('class_id', $request->class_id)
                    ->whereYear('month_year', $request->year)
                    ->whereMonth('month_year', $request->month)
                    ->exists();

        if ($exists) {
            return redirect()->back()
                           ->with('warning', 'এই মাসের ফি ইতিমধ্যে জেনারেট করা হয়েছে।');
        }

        try {
            Fee::generateMonthlyFees($request->class_id, $request->month, $request->year);
            
            return redirect()->route('fees.index')
                           ->with('success', 'মাসিক ফি সফলভাবে জেনারেট করা হয়েছে।');
        } catch (\Exception $e) {
            return redirect()->back()
                           ->with('error', 'ফি জেনারেট করতে সমস্যা হয়েছে।');
        }
    }

    /**
     * Fee collection report
     */
    public function collectionReport(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'from_date' => 'required|date',
            'to_date' => 'required|date|after_or_equal:from_date',
            'class_id' => 'nullable|exists:classes,id'
        ]);

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

        $query = Payment::with('student', 'collector')
                       ->whereBetween('payment_date', [$request->from_date, $request->to_date]);

        if ($request->class_id) {
            $query->whereHas('student', function($q) use ($request) {
                $q->where('class_id', $request->class_id);
            });
        }

        $payments = $query->orderBy('payment_date', 'desc')->get();
        
        $summary = [
            'total_amount' => $payments->sum('amount'),
            'total_transactions' => $payments->count(),
            'cash_amount' => $payments->where('payment_method', 'cash')->sum('amount'),
            'bkash_amount' => $payments->where('payment_method', 'bKash')->sum('amount'),
            'nagad_amount' => $payments->where('payment_method', 'nagad')->sum('amount'),
        ];

        return view('fees.collection-report', compact('payments', 'summary', 'request'));
    }
    
    public function report(Request $request)
{
    $query = Payment::with('student');

    // তারিখ অনুযায়ী ফিল্টার
    if ($request->start_date) {
        $query->whereDate('created_at', '>=', $request->start_date);
    }
    if ($request->end_date) {
        $query->whereDate('created_at', '<=', $request->end_date);
    }
    // মেথড অনুযায়ী ফিল্টার
    if ($request->method) {
        $query->where('payment_method', $request->method);
    }

    $payments = $query->get();
    
    // সামারি ক্যালকুলেশন
    $summary = [
        'total_amount' => $payments->sum('amount'),
        'cash_amount' => $payments->where('payment_method', 'cash')->sum('amount'),
        'bkash_amount' => $payments->where('payment_method', 'bKash')->sum('amount'),
        'nagad_amount' => $payments->where('payment_method', 'nagad')->sum('amount'),
    ];

    return view('fees.collection-report', compact('payments', 'summary', 'request'));
}

    /**
     * Due fee report
     */
    public function dueReport(Request $request)
    {
        $query = Fee::with('student', 'class')
                   ->due()
                   ->where('due_amount', '>', 0);

        if ($request->class_id) {
            $query->where('class_id', $request->class_id);
        }

        if ($request->month && $request->year) {
            $query->whereYear('month_year', $request->year)
                  ->whereMonth('month_year', $request->month);
        }

        $dueFees = $query->orderBy('month_year')->get();
        
        $totalDue = $dueFees->sum('due_amount');
        $totalStudents = $dueFees->groupBy('student_id')->count();

        return view('fees.due-report', compact('dueFees', 'totalDue', 'totalStudents'));
    }

    /**
     * Send payment SMS
     */
    private function sendPaymentSMS($student, $amount)
    {
        // SMS গেটওয়ে ইন্টিগ্রেশন
        // $message = "প্রিয় {$student->name_bn}, আপনার {$amount} টাকা পেমেন্ট গৃহীত হয়েছে। ধন্যবাদ।";
        // আপনার SMS API কল করুন
    }
}