<?php

namespace App\Http\Controllers\Api;

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

class InvestorController extends Controller
{
    public function index(Request $request)
    {
        $query = Investor::with(['company', 'payments'])
            ->withSum('payments', 'amount');

        if ($request->search) {
            $q = $request->search;
            $query->where(function ($wq) use ($q) {
                $wq->where('name', 'like', "%$q%")
                   ->orWhere('company_name', 'like', "%$q%")
                   ->orWhere('email', 'like', "%$q%")
                   ->orWhere('investor_number', 'like', "%$q%");
            });
        }
        if ($request->status)       $query->where('status', $request->status);
        if ($request->partner_type) $query->where('partner_type', $request->partner_type);
        if ($request->entity_type)  $query->where('entity_type', $request->entity_type);

        $investors = $query->latest()->get()->map(fn($i) => $this->format($i));

        $summary = [
            'total'                => Investor::count(),
            'active'               => Investor::where('status','active')->count(),
            'total_invested'       => (float) Investor::sum('total_investment_value'),
            'total_paid_out'       => (float) InvestorPayment::sum('amount'),
            'total_equity_given'   => (float) Investor::sum('equity_percentage'),
        ];

        return response()->json(['data' => $investors, 'summary' => $summary]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'entity_type'            => 'required|in:individual,company',
            'name'                   => 'required|string|max:255',
            'company_name'           => 'nullable|string|max:255',
            'email'                  => 'nullable|email|max:255',
            'phone'                  => 'nullable|string|max:50',
            'address'                => 'nullable|string|max:500',
            'country'                => 'nullable|string|max:100',
            'nationality'            => 'nullable|string|max:100',
            'date_of_birth'          => 'nullable|date',
            'id_number'              => 'nullable|string|max:100',
            'id_type'                => 'nullable|string|max:50',
            'investment_type'        => 'required|in:money,assets,intellectual_property,mixed',
            'money_amount'           => 'nullable|numeric|min:0',
            'asset_description'      => 'nullable|string',
            'asset_value'            => 'nullable|numeric|min:0',
            'intellectual_description'=> 'nullable|string',
            'intellectual_value'     => 'nullable|numeric|min:0',
            'equity_percentage'      => 'nullable|numeric|min:0|max:100',
            'shares_count'           => 'nullable|integer|min:0',
            'share_price'            => 'nullable|numeric|min:0',
            'expected_dividend_rate' => 'nullable|numeric|min:0|max:100',
            'dividend_frequency'     => 'nullable|in:monthly,quarterly,annually,on_exit',
            'company_id'             => 'nullable|exists:companies,id',
            'status'                 => 'nullable|in:active,inactive,exited,pending',
            'partner_type'           => 'nullable|in:investor,partner,angel,venture_capital,strategic',
            'investment_date'        => 'nullable|date',
            'notes'                  => 'nullable|string',
            'photo'                  => 'nullable|file|mimes:jpg,jpeg,png,webp|max:5120',
            'id_document'            => 'nullable|file|mimes:pdf,jpg,jpeg,png|max:5120',
        ]);

        $data = $validated;
        $data['investor_number'] = 'INV-' . date('Y') . '-' . str_pad(Investor::count() + 1, 4, '0', STR_PAD_LEFT);
        $data['recorded_by']     = $request->user()->id;

        // Total value
        $data['total_investment_value'] = ($data['money_amount'] ?? 0)
            + ($data['asset_value'] ?? 0)
            + ($data['intellectual_value'] ?? 0);

        if ($request->hasFile('photo'))       $data['photo_path']       = $request->file('photo')->store('investor_photos', 'public');
        if ($request->hasFile('id_document')) $data['id_document_path'] = $request->file('id_document')->store('investor_docs', 'public');

        $investor = Investor::create($data);

        return response()->json(['data' => $this->format($investor->load('company','payments')), 'message' => 'Investor added'], 201);
    }

    public function show($id)
    {
        $investor = Investor::with(['company', 'payments'])->findOrFail($id);
        return response()->json(['data' => $this->format($investor)]);
    }

    public function update(Request $request, $id)
    {
        $investor = Investor::findOrFail($id);

        $validated = $request->validate([
            'entity_type'            => 'sometimes|in:individual,company',
            'name'                   => 'sometimes|required|string|max:255',
            'company_name'           => 'nullable|string|max:255',
            'email'                  => 'nullable|email|max:255',
            'phone'                  => 'nullable|string|max:50',
            'address'                => 'nullable|string|max:500',
            'country'                => 'nullable|string|max:100',
            'nationality'            => 'nullable|string|max:100',
            'date_of_birth'          => 'nullable|date',
            'id_number'              => 'nullable|string|max:100',
            'id_type'                => 'nullable|string|max:50',
            'investment_type'        => 'sometimes|in:money,assets,intellectual_property,mixed',
            'money_amount'           => 'nullable|numeric|min:0',
            'asset_description'      => 'nullable|string',
            'asset_value'            => 'nullable|numeric|min:0',
            'intellectual_description'=> 'nullable|string',
            'intellectual_value'     => 'nullable|numeric|min:0',
            'equity_percentage'      => 'nullable|numeric|min:0|max:100',
            'shares_count'           => 'nullable|integer|min:0',
            'share_price'            => 'nullable|numeric|min:0',
            'expected_dividend_rate' => 'nullable|numeric|min:0|max:100',
            'dividend_frequency'     => 'nullable|in:monthly,quarterly,annually,on_exit',
            'company_id'             => 'nullable|exists:companies,id',
            'status'                 => 'nullable|in:active,inactive,exited,pending',
            'partner_type'           => 'nullable|in:investor,partner,angel,venture_capital,strategic',
            'investment_date'        => 'nullable|date',
            'exit_date'              => 'nullable|date',
            'notes'                  => 'nullable|string',
            'photo'                  => 'nullable|file|mimes:jpg,jpeg,png,webp|max:5120',
            'id_document'            => 'nullable|file|mimes:pdf,jpg,jpeg,png|max:5120',
        ]);

        if (isset($validated['money_amount']) || isset($validated['asset_value']) || isset($validated['intellectual_value'])) {
            $validated['total_investment_value'] =
                ($validated['money_amount'] ?? $investor->money_amount) +
                ($validated['asset_value']  ?? $investor->asset_value)  +
                ($validated['intellectual_value'] ?? $investor->intellectual_value);
        }

        if ($request->hasFile('photo'))       $validated['photo_path']       = $request->file('photo')->store('investor_photos', 'public');
        if ($request->hasFile('id_document')) $validated['id_document_path'] = $request->file('id_document')->store('investor_docs', 'public');

        $investor->update($validated);

        return response()->json(['data' => $this->format($investor->fresh(['company','payments'])), 'message' => 'Updated']);
    }

    public function destroy($id)
    {
        Investor::findOrFail($id)->delete();
        return response()->json(['message' => 'Deleted']);
    }

    // ── Payments ─────────────────────────────────────────
    public function payments($id)
    {
        $investor = Investor::findOrFail($id);
        $payments = $investor->payments()->latest()->get();
        return response()->json(['data' => $payments, 'total' => $payments->sum('amount')]);
    }

    public function addPayment(Request $request, $id)
    {
        $investor = Investor::findOrFail($id);
        $validated = $request->validate([
            'payment_type'     => 'required|in:dividend,share_sale,profit_distribution,buyback,bonus,other',
            'amount'           => 'required|numeric|min:0.01',
            'payment_date'     => 'required|date',
            'reference_number' => 'nullable|string|max:255',
            'payment_method'   => 'nullable|string|max:100',
            'notes'            => 'nullable|string',
            'receipt'          => 'nullable|file|mimes:pdf,jpg,jpeg,png|max:5120',
        ]);

        $validated['investor_id']  = $investor->id;
        $validated['recorded_by']  = $request->user()->id;

        if ($request->hasFile('receipt')) {
            $validated['receipt_path'] = $request->file('receipt')->store('investor_receipts', 'public');
        }

        $payment = InvestorPayment::create($validated);
        return response()->json(['data' => $payment, 'message' => 'Payment logged'], 201);
    }

    private function format(Investor $i): array
    {
        return [
            'id'                     => $i->id,
            'investor_number'        => $i->investor_number,
            'entity_type'            => $i->entity_type,
            'name'                   => $i->name,
            'display_name'           => $i->entity_type === 'company' ? ($i->company_name ?: $i->name) : $i->name,
            'company_name'           => $i->company_name,
            'email'                  => $i->email,
            'phone'                  => $i->phone,
            'address'                => $i->address,
            'country'                => $i->country,
            'nationality'            => $i->nationality,
            'date_of_birth'          => $i->date_of_birth?->format('Y-m-d'),
            'id_number'              => $i->id_number,
            'id_type'                => $i->id_type,
            'photo_url'              => $i->photo_path ? asset('storage/' . $i->photo_path) : null,
            'id_document_url'        => $i->id_document_path ? asset('storage/' . $i->id_document_path) : null,
            'investment_type'        => $i->investment_type,
            'money_amount'           => (float) $i->money_amount,
            'asset_description'      => $i->asset_description,
            'asset_value'            => (float) $i->asset_value,
            'intellectual_description'=> $i->intellectual_description,
            'intellectual_value'     => (float) $i->intellectual_value,
            'total_investment_value' => (float) $i->total_investment_value,
            'equity_percentage'      => (float) $i->equity_percentage,
            'shares_count'           => (int) $i->shares_count,
            'share_price'            => (float) $i->share_price,
            'expected_dividend_rate' => (float) $i->expected_dividend_rate,
            'dividend_frequency'     => $i->dividend_frequency,
            'company_id'             => $i->company_id,
            'company'                => $i->company ? ['id' => $i->company->id, 'name' => $i->company->name] : null,
            'status'                 => $i->status,
            'partner_type'           => $i->partner_type,
            'investment_date'        => $i->investment_date?->format('Y-m-d'),
            'exit_date'              => $i->exit_date?->format('Y-m-d'),
            'notes'                  => $i->notes,
            'total_paid_out'         => (float) ($i->payments_sum_amount ?? $i->payments()->sum('amount')),
            'payments_count'         => $i->payments ? $i->payments->count() : 0,
            'created_at'             => $i->created_at,
        ];
    }
}
