<?php

namespace App\Http\Controllers\Partner;

use App\Http\Controllers\Controller;
use App\Models\SavingsScheme;
use Illuminate\Http\Request;

class SavingsSchemeController extends Controller
{
    public function index()
    {
        $partnerId = auth()->user()->partner_id;
        $schemes = SavingsScheme::where('partner_id', $partnerId)->latest()->paginate(15);
        
        // Get summary counts for all schemes (not just paginated)
        $allSchemes = SavingsScheme::where('partner_id', $partnerId)->get();
        $summary = [
            'rd_count' => $allSchemes->where('savings_type', 'RD')->count(),
            'fd_count' => $allSchemes->where('savings_type', 'FD')->count(),
            'mis_count' => $allSchemes->where('savings_type', 'MIS')->count(),
            'active_count' => $allSchemes->where('status', 'active')->count(),
            'inactive_count' => $allSchemes->where('status', 'inactive')->count(),
        ];
        
        return view('partner.savings-schemes.index', compact('schemes', 'summary'));
    }

    public function create()
    {
        return view('partner.savings-schemes.create');
    }

    public function store(Request $request)
    {
        // Get savings type for conditional validation
        $savingsType = $request->input('savings_type');
        
        if (!$savingsType || !in_array($savingsType, ['RD', 'FD', 'MIS'])) {
            return back()->withErrors(['savings_type' => 'Please select a valid savings type'])->withInput();
        }
        
        // Use type-specific validation rules
        $validated = $request->validate(SavingsScheme::getValidationRules($savingsType));
        
        // Additional validation: compounding_frequency required only for compound interest
        if ($validated['interest_type'] === 'compound' && ($savingsType === 'RD' || $savingsType === 'FD')) {
            $request->validate([
                'compounding_frequency' => 'required|in:monthly,quarterly,yearly',
            ]);
            $validated['compounding_frequency'] = $request->input('compounding_frequency');
        } else {
            // For simple interest, set compounding_frequency to null
            $validated['compounding_frequency'] = null;
        }
        
        // Set partner ID
        $validated['partner_id'] = auth()->user()->partner_id;
        
        // Set duration_type based on savings type
        if ($savingsType === 'RD') {
            // For RD, preserve the user's selection (daily/weekly/monthly)
            $validated['duration_type'] = $request->input('duration_type', 'monthly');
        } else {
            // For FD/MIS, always use monthly
            $validated['duration_type'] = 'monthly';
        }
        
        // Create scheme
        $scheme = SavingsScheme::create($validated);
        
        $typeLabel = match($savingsType) {
            'RD' => 'Recurring Deposit',
            'FD' => 'Fixed Deposit',
            'MIS' => 'Monthly Income Scheme',
        };

        return redirect()->route('partner.savings-schemes.index')
            ->with('success', $typeLabel . ' scheme created successfully: ' . $scheme->name);
    }

    public function show(SavingsScheme $savingsScheme)
    {
        $this->ensurePartnerOwnership($savingsScheme);
        return view('partner.savings-schemes.show', compact('savingsScheme'));
    }

    public function edit(SavingsScheme $savingsScheme)
    {
        $this->ensurePartnerOwnership($savingsScheme);
        return view('partner.savings-schemes.edit', compact('savingsScheme'));
    }

    public function update(Request $request, SavingsScheme $savingsScheme)
    {
        $this->ensurePartnerOwnership($savingsScheme);
        
        // Get savings type from request (or use existing if disabled)
        $requestedType = $request->input('savings_type', $savingsScheme->savings_type);
        $savingsType = $requestedType;
        
        // Prevent changing savings type if accounts exist
        if ($requestedType !== $savingsScheme->savings_type) {
            if ($savingsScheme->savings()->count() > 0) {
                return back()->withErrors([
                    'savings_type' => 'Cannot change savings type when accounts exist under this scheme'
                ])->withInput();
            }
        }
        
        // Use type-specific validation rules
        $validated = $request->validate(SavingsScheme::getValidationRules($savingsType));
        
        // Additional validation: compounding_frequency required only for compound interest
        if ($validated['interest_type'] === 'compound' && ($savingsType === 'RD' || $savingsType === 'FD')) {
            $request->validate([
                'compounding_frequency' => 'required|in:monthly,quarterly,yearly',
            ]);
            $validated['compounding_frequency'] = $request->input('compounding_frequency');
        } else {
            // For simple interest, set compounding_frequency to null
            $validated['compounding_frequency'] = null;
        }
        
        // Set duration_type to monthly for FD/MIS, preserve for RD
        if ($savingsType !== 'RD') {
            $validated['duration_type'] = 'monthly';
        }
        
        // For MIS, force simple interest
        if ($savingsType === 'MIS') {
            $validated['interest_type'] = 'simple';
            $validated['compounding_frequency'] = null;
        }

        $savingsScheme->update($validated);

        return redirect()->route('partner.savings-schemes.index')
            ->with('success', 'Savings scheme updated successfully.');
    }

    public function destroy(SavingsScheme $savingsScheme)
    {
        $this->ensurePartnerOwnership($savingsScheme);
        if ($savingsScheme->savings()->count() > 0) {
            return redirect()->back()->with('error', 'Cannot delete savings scheme with associated savings accounts.');
        }
        $savingsScheme->delete();
        return redirect()->route('partner.savings-schemes.index')->with('success', 'Savings scheme deleted successfully.');
    }

    private function ensurePartnerOwnership(SavingsScheme $savingsScheme)
    {
        if ($savingsScheme->partner_id !== auth()->user()->partner_id) {
            abort(403);
        }
    }
}
