<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\MemberTreeClosure;
use App\Models\User;
use App\Models\UserBinaryCarry;
use App\Models\BinaryLedger;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;

class TreeController extends Controller
{
    public function index(Request $request): View
    {
        $search = trim((string) $request->query('q', ''));
        $mode = $request->query('mode', 'placement');
        $member = null;
        $directs = collect();
        $legTotals = ['left' => 0, 'right' => 0];
        $carry = null;

        if ($search !== '') {
            $member = User::query()
                ->where('member_code', $search)
                ->orWhere('mobile', $search)
                ->orWhere('email', $search)
                ->orWhere('id', $search)
                ->first();

            if ($member) {
                if ($mode === 'sponsor') {
                    $directs = User::query()
                        ->where('sponsor_id', $member->id)
                        ->select(['id', 'member_code', 'name', 'status', 'placement_leg'])
                        ->get()
                        ->map(function ($row) {
                            $row->path_leg = $row->placement_leg ?? 'left';
                            return $row;
                        });
                } else {
                    $directs = MemberTreeClosure::query()
                        ->where('ancestor_id', $member->id)
                        ->where('depth', 1)
                        ->join('users as u', 'u.id', '=', 'member_tree_closure.descendant_id')
                        ->select([
                            'member_tree_closure.path_leg',
                            'u.id',
                            'u.member_code',
                            'u.name',
                            'u.status',
                            'u.placement_leg',
                        ])
                        ->get();
                }

                $legTotals['left'] = (float) BinaryLedger::query()
                    ->where('beneficiary_user_id', $member->id)
                    ->where('leg', 'left')
                    ->selectRaw("COALESCE(SUM(CASE WHEN direction='credit' THEN units ELSE -units END),0) as total")
                    ->value('total');
                $legTotals['right'] = (float) BinaryLedger::query()
                    ->where('beneficiary_user_id', $member->id)
                    ->where('leg', 'right')
                    ->selectRaw("COALESCE(SUM(CASE WHEN direction='credit' THEN units ELSE -units END),0) as total")
                    ->value('total');
                $carry = UserBinaryCarry::query()->where('user_id', $member->id)->first();
            }
        }

        return view('admin.tree', [
            'search' => $search,
            'mode' => $mode,
            'member' => $member,
            'directs' => $directs,
            'legTotals' => $legTotals,
            'carry' => $carry,
        ]);
    }

    public function export(Request $request)
    {
        $search = trim((string) $request->query('q', ''));
        $mode = $request->query('mode', 'placement');

        if ($search === '') {
            return redirect()->route('admin.tree')->withErrors(['q' => 'Search a member to export.']);
        }

        $member = User::query()
            ->where('member_code', $search)
            ->orWhere('mobile', $search)
            ->orWhere('email', $search)
            ->orWhere('id', $search)
            ->first();

        if (! $member) {
            return redirect()->route('admin.tree')->withErrors(['q' => 'Member not found.']);
        }

        if ($mode === 'sponsor') {
            $directs = User::query()
                ->where('sponsor_id', $member->id)
                ->select(['member_code', 'name', 'status', 'placement_leg'])
                ->get()
                ->map(function ($row) {
                    $row->path_leg = $row->placement_leg ?? 'left';
                    return $row;
                });
        } else {
            $directs = MemberTreeClosure::query()
                ->where('ancestor_id', $member->id)
                ->where('depth', 1)
                ->join('users as u', 'u.id', '=', 'member_tree_closure.descendant_id')
                ->select([
                    'member_tree_closure.path_leg',
                    'u.member_code',
                    'u.name',
                    'u.status',
                ])
                ->get();
        }

        $legTotals = [
            'left' => (float) BinaryLedger::query()
                ->where('beneficiary_user_id', $member->id)
                ->where('leg', 'left')
                ->selectRaw("COALESCE(SUM(CASE WHEN direction='credit' THEN units ELSE -units END),0) as total")
                ->value('total'),
            'right' => (float) BinaryLedger::query()
                ->where('beneficiary_user_id', $member->id)
                ->where('leg', 'right')
                ->selectRaw("COALESCE(SUM(CASE WHEN direction='credit' THEN units ELSE -units END),0) as total")
                ->value('total'),
        ];

        $pdf = Pdf::loadView('admin.tree-pdf', [
            'member' => $member,
            'directs' => $directs,
            'legTotals' => $legTotals,
            'mode' => $mode,
        ]);

        return $pdf->download('tree-'.$member->member_code.'.pdf');
    }
}
