<?php

namespace App\Http\Controllers\Accounting;

use App\Http\Controllers\Controller;
use App\Models\Partner;
use App\Models\JournalEntry;
use App\Models\Account;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PartnerController extends Controller
{
    public function index()
    {
        $partners = Partner::withCount('profitDistributions')->get();
        return view('accounting.partners.index', compact('partners'));
    }

    public function create()
    {
        return view('accounting.partners.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:50',
            'ownership_percent' => 'required|numeric|min:0|max:100',
            'capital_invested' => 'required|numeric|min:0',
        ]);

        Partner::create($validated);

        return redirect()->route('accounting.partners.index')
            ->with('success', 'Partner added successfully.');
    }

    public function edit(Partner $partner)
    {
        return view('accounting.partners.edit', compact('partner'));
    }

    public function update(Request $request, Partner $partner)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:50',
            'ownership_percent' => 'required|numeric|min:0|max:100',
            'capital_invested' => 'required|numeric|min:0',
            'is_active' => 'boolean',
        ]);

        $partner->update($validated);

        return redirect()->route('accounting.partners.index')
            ->with('success', 'Partner updated successfully.');
    }

    public function destroy(Partner $partner)
    {
        if ($partner->profitDistributions()->exists()) {
            return back()->with('error', 'Cannot delete partner with existing profit distributions.');
        }

        $partner->delete();
        return redirect()->route('accounting.partners.index')
            ->with('success', 'Partner deleted successfully.');
    }

    /**
     * Calculate and show potential profit for partners based on a period.
     */
    public function calculateProfits(Request $request)
    {
        $startDate = $request->input('start_date', now()->startOfMonth()->toDateString());
        $endDate = $request->input('end_date', now()->toDateString());

        // Simple profit calculation: Revenue - Expenses
        $revenue = DB::table('journal_entry_lines')
            ->join('accounts', 'journal_entry_lines.account_id', '=', 'accounts.id')
            ->join('journal_entries', 'journal_entry_lines.journal_entry_id', '=', 'journal_entries.id')
            ->where('accounts.type', 'revenue')
            ->whereBetween('journal_entries.date', [$startDate, $endDate])
            ->sum(DB::raw('credit - debit'));

        $expenses = DB::table('journal_entry_lines')
            ->join('accounts', 'journal_entry_lines.account_id', '=', 'accounts.id')
            ->join('journal_entries', 'journal_entry_lines.journal_entry_id', '=', 'journal_entries.id')
            ->where('accounts.type', 'expense')
            ->whereBetween('journal_entries.date', [$startDate, $endDate])
            ->sum(DB::raw('debit - credit'));

        $totalProfit = $revenue - $expenses;
        $partners = Partner::where('is_active', true)->get();

        return view('accounting.partners.calculate', compact('partners', 'totalProfit', 'startDate', 'endDate'));
    }

    /**
     * Record a profit distribution and create Journal Entries.
     */
    public function storeDistribution(Request $request)
    {
        $validated = $request->validate([
            'partner_id' => 'required|exists:partners,id',
            'amount' => 'required|numeric|min:0.01',
            'date' => 'required|date',
            'period_start' => 'required|date',
            'period_end' => 'required|date|after_or_equal:period_start',
            'notes' => 'nullable|string',
        ]);

        DB::transaction(function () use ($validated) {
            $partner = Partner::find($validated['partner_id']);

            // Create Distribution record
            $distribution = \App\Models\ProfitDistribution::create([
                'partner_id' => $validated['partner_id'],
                'type' => 'partner',
                'amount' => $validated['amount'],
                'date' => $validated['date'],
                'period_start' => $validated['period_start'],
                'period_end' => $validated['period_end'],
                'notes' => $validated['notes'],
            ]);

            // Create Journal Entry
            $retainedEarnings = Account::where('code', '3200')->first();
            $capital = Account::where('code', '3100')->first();

            if ($retainedEarnings && $capital) {
                $entry = JournalEntry::create([
                    'date' => $validated['date'],
                    'description' => "Profit Distribution to Partner: {$partner->name} for period {$validated['period_start']} to {$validated['period_end']}",
                    'reference' => 'DIST-' . $distribution->id,
                    'is_manual' => false,
                    'user_id' => auth()->id() ?? 1,
                ]);

                // Debit Retained Earnings (Decrease Equity)
                $entry->lines()->create([
                    'account_id' => $retainedEarnings->id,
                    'debit' => $validated['amount'],
                    'credit' => 0,
                    'description' => 'Distribution from Retained Earnings',
                ]);

                // Credit Capital (Increase Partner's Equity)
                $entry->lines()->create([
                    'account_id' => $capital->id,
                    'debit' => 0,
                    'credit' => $validated['amount'],
                    'description' => "Capital increase for {$partner->name}",
                ]);
            }
        });

        return back()->with('success', 'Profit distribution recorded and accounting entries generated.');
    }
}
