<?php

namespace App\Http\Controllers;

use App\Models\Share;
use App\Models\User;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;
use Maatwebsite\Excel\Facades\Excel;

class ShareController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $shares = Share::with('user')->paginate(15);

        // Calculate dynamic statistics
        $totalShares = Share::sum('number_of_shares');
        $totalValue = Share::sum('total_value');
        $totalMembersWithShares = Share::distinct('user_id')->count('user_id');
        $averageSharesPerMember = $totalMembersWithShares > 0 ? round($totalShares / $totalMembersWithShares, 2) : 0;
        $averageValuePerMember = $totalMembersWithShares > 0 ? round($totalValue / $totalMembersWithShares, 2) : 0;

        // Monthly shares growth (shares purchased this month)
        $currentMonth = now()->format('Y-m');
        $monthlySharesPurchased = Share::whereRaw("DATE_FORMAT(purchase_date, '%Y-%m') = ?", [$currentMonth])->sum('number_of_shares');
        $monthlyValuePurchased = Share::whereRaw("DATE_FORMAT(purchase_date, '%Y-%m') = ?", [$currentMonth])->sum('total_value');

        // Top shareholder by number of shares
        $topShareholderByCount = Share::with('user')
            ->selectRaw('user_id, SUM(number_of_shares) as total_shares')
            ->groupBy('user_id')
            ->orderBy('total_shares', 'desc')
            ->first();

        // Top shareholder by value
        $topShareholderByValue = Share::with('user')
            ->selectRaw('user_id, SUM(total_value) as total_value')
            ->groupBy('user_id')
            ->orderBy('total_value', 'desc')
            ->first();

        // Recent purchases (last 30 days)
        $recentPurchases = Share::with('user')
            ->where('purchase_date', '>=', now()->subDays(30))
            ->count();

        return view('adminlte.shares.index', compact(
            'shares',
            'totalShares',
            'totalValue',
            'totalMembersWithShares',
            'averageSharesPerMember',
            'averageValuePerMember',
            'monthlySharesPurchased',
            'monthlyValuePurchased',
            'topShareholderByCount',
            'topShareholderByValue',
            'recentPurchases'
        ));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $users = User::whereHas('membership')->get();

        return view('adminlte.shares.create', compact('users'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'number_of_shares' => 'required|integer|min:1',
            'share_value' => 'required|numeric|min:0.01',
            'purchase_date' => 'required|date|before_or_equal:today',
            'notes' => 'nullable|string|max:1000',
        ]);

        // Calculate total value
        $totalValue = $request->number_of_shares * $request->share_value;

        Share::create([
            'user_id' => $request->user_id,
            'number_of_shares' => $request->number_of_shares,
            'share_value' => $request->share_value,
            'total_value' => $totalValue,
            'purchase_date' => $request->purchase_date,
            'notes' => $request->notes,
        ]);

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

    /**
     * Display the specified resource.
     */
    public function show(Share $share)
    {
        $share->load('user');

        return view('adminlte.shares.show', compact('share'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Share $share)
    {
        $users = User::whereHas('membership')->get();

        return view('adminlte.shares.edit', compact('share', 'users'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Share $share)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'number_of_shares' => 'required|integer|min:1',
            'share_value' => 'required|numeric|min:0.01',
            'purchase_date' => 'required|date|before_or_equal:today',
            'notes' => 'nullable|string|max:1000',
        ]);

        // Calculate total value
        $totalValue = $request->number_of_shares * $request->share_value;

        $share->update([
            'user_id' => $request->user_id,
            'number_of_shares' => $request->number_of_shares,
            'share_value' => $request->share_value,
            'total_value' => $totalValue,
            'purchase_date' => $request->purchase_date,
            'notes' => $request->notes,
        ]);

        return redirect()->route('shares.index')
                        ->with('success', 'Share updated successfully!');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Share $share)
    {
        $share->delete();

        return redirect()->route('shares.index')
                        ->with('success', 'Share deleted successfully!');
    }

    /**
     * Export shares to PDF
     */
    public function exportPdf()
    {
        $shares = Share::with('user')->get();

        $pdf = Pdf::loadView('adminlte.shares.exports.pdf', compact('shares'))
                  ->setPaper('a4', 'landscape');

        return $pdf->download('shares_report_' . date('Y-m-d_H-i-s') . '.pdf');
    }

    /**
     * Export shares to Excel
     */
    public function exportExcel()
    {
        return Excel::download(new \App\Exports\SharesExport, 'shares_report_' . date('Y-m-d_H-i-s') . '.xlsx');
    }

    /**
     * Export shares to CSV
     */
    public function exportCsv()
    {
        return Excel::download(new \App\Exports\SharesExport, 'shares_report_' . date('Y-m-d_H-i-s') . '.csv');
    }

}
