<?php

namespace App\Http\Controllers\Accounting;

use App\Http\Controllers\Controller;
use App\Models\Investor;
use App\Models\ShareTransaction;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ShareController extends Controller
{
    public function index()
    {
        $totalCompanyShares = 10000;
        $investors = Investor::withSum('shareTransactions as total_shares', 'shares')->get();

        $soldShares = $investors->sum('total_shares');
        $availableShares = $totalCompanyShares - $soldShares;

        $currentSharePrice = $this->calculateSharePrice();

        return view('accounting.shares.index', compact(
            'investors',
            'totalCompanyShares',
            'soldShares',
            'availableShares',
            'currentSharePrice'
        ));
    }

    public function createInvestor()
    {
        return view('accounting.shares.create_investor');
    }

    public function storeInvestor(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:50',
        ]);

        Investor::create($validated);

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

    public function buyShares(Request $request)
    {
        $validated = $request->validate([
            'investor_id' => 'required|exists:investors,id',
            'shares' => 'required|integer|min:1',
            'price_per_share' => 'required|numeric|min:0.01',
            'date' => 'required|date',
        ]);

        $totalCompanyShares = 10000;
        $soldShares = ShareTransaction::where('type', 'buy')->sum('shares') - ShareTransaction::where('type', 'sell')->sum('shares');

        if ($soldShares + $validated['shares'] > $totalCompanyShares) {
            return back()->with('error', 'Not enough shares available. Max available: ' . ($totalCompanyShares - $soldShares));
        }

        DB::transaction(function () use ($validated) {
            $totalAmount = $validated['shares'] * $validated['price_per_share'];

            ShareTransaction::create([
                'investor_id' => $validated['investor_id'],
                'type' => 'buy',
                'shares' => $validated['shares'],
                'price_per_share' => $validated['price_per_share'],
                'total_amount' => $totalAmount,
                'date' => $validated['date'],
            ]);

            $investor = Investor::find($validated['investor_id']);
            $newTotalShares = $investor->total_shares + $validated['shares'];
            $newTotalInvestment = $investor->total_investment + $totalAmount;

            $investor->update([
                'total_shares' => $newTotalShares,
                'total_investment' => $newTotalInvestment,
                'avg_purchase_price' => $newTotalInvestment / $newTotalShares,
            ]);
        });

        return redirect()->route('accounting.shares.index')
            ->with('success', 'Shares purchased successfully.');
    }

    /**
     * Calculate current share price based on company performance.
     * Logic: (Expected Revenue / 10,000) * Performance multiplier
     */
    protected function calculateSharePrice()
    {
        $expectedAnnualRevenue = Setting::getValue('general', 'expected_annual_revenue', 1000000);
        $basePrice = $expectedAnnualRevenue / 10000;

        // Implementation of performance multiplier based on actual income
        // For simplicity: (Current Year Income / Expected Annual Revenue)
        $currentYearIncome = 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')
            ->whereYear('journal_entries.date', date('Y'))
            ->sum(DB::raw('credit - debit'));

        if ($currentYearIncome > 0) {
            $multiplier = 1 + ($currentYearIncome / $expectedAnnualRevenue);
            return $basePrice * $multiplier;
        }

        return $basePrice;
    }
}
