<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\FinRoiUser;
use App\Models\User;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\Models\GoldRoiHistory;
use App\Models\FinAccount;
use App\Models\RoiRejectDay;

class GoldController extends Controller
{
    public function gold_generate()
    {
        return view('Admin.gold_generate');
    }

    public function generate_manual_gold_profit(Request $request)
    {
        Log::info('gold_roi_generate_manual function started');

        $request->validate([
            'generate_date' => 'required|date'
        ]);

        $date = $request->generate_date;

        Log::info("Processing Gold ROI generation for date: {$date}");

        $roiGenerated = GoldRoiHistory::whereDate('generate_date', $date)
            ->where('type', 'roi')
            ->count();

        $roiIncomeGenerated = FinAccount::whereDate('entry_date', $date)
            ->where('type', 'roi')
            ->where('remark', 'ROI income')
            ->count();

        if ($roiGenerated || $roiIncomeGenerated) {
            return back()->with(
                'error',
                'Gold ROI already generated for this date.'
            );
        }

        $rejectDates = RoiRejectDay::whereDate('reject_dates', $date)
            ->count();

        $dayNumber = Carbon::parse($date)->dayOfWeekIso;

        if ($rejectDates > 0 || $dayNumber == 6 || $dayNumber == 7) {

            return back()->with(
                'error',
                'Gold ROI generation skipped due to rejection date or weekend.'
            );
        }

        $type = "Manual";

        $this->generateRoi($date, $type);

        return back()->with(
            'success',
            'Gold ROI generated successfully'
        );
    }

    public function generateRoi($date, $type)
    {
        DB::beginTransaction();

        try {

            $deposits = FinRoiUser::where('days', '>', 0)
                ->where('package', 'gold')
                ->whereDate('entry_date', '<', $date)
                ->get();

            $rejectDates = RoiRejectDay::whereDate('reject_dates', $date)
                ->count();

            $insertCount = 0;

            if (
                $rejectDates == 0 &&
                Carbon::parse($date)->dayOfWeekIso != 6 &&
                Carbon::parse($date)->dayOfWeekIso != 7
            ) {
                foreach ($deposits as $dep) {

                    $check = FinAccount::where('user_id', $dep->user_id)
                        ->whereDate('entry_date', $date)
                        ->where('remark', 'ROI income')
                        ->where('description', $dep->roi_id)
                        ->first();

                    if (!$check) {

                        if ($dep->package != 'silver') {

                            FinAccount::create([
                                'user_id'     => $dep->user_id,
                                'credit'      => $dep->roi_amount,
                                'entry_date'  => $date,
                                'remark'      => 'ROI income',
                                'description' => $dep->roi_id,
                                'type'        => 'roi',
                                'percentage'  => $dep->roi_percentage,
                            ]);

                            $insertCount++;

                            Log::info('ROI CREDIT INSERTED', [
                                'user_id' => $dep->user_id,
                                'amount'  => $dep->roi_amount
                            ]);
                        }
                    }
                }

                GoldRoiHistory::create([
                    'type'          => 'roi',
                    'generate_date' => $date,
                    'entry_date'    => now(),
                    'generated_in'  => $type,
                    'count'         => $insertCount,
                ]);
            }

            DB::commit();

            return true;
        } catch (\Exception $e) {

            DB::rollBack();

            Log::error('ROI GENERATION ERROR', [
                'message' => $e->getMessage(),
                'line'    => $e->getLine(),
                'file'    => $e->getFile()
            ]);

            return false;
        }
    }

    public function profit_report_gold()
    {
        return view('Admin.profit_report_gold');
    }

    public function profit_report_gold_data()
    {
        $history = GoldRoiHistory::latest();

        return DataTables::eloquent($history)

            ->addIndexColumn()

            ->editColumn('entry_date', function ($row) {
                return $row->entry_date
                    ? Carbon::parse($row->entry_date)->format('d-m-Y h:i A')
                    : '-';
            })

            ->editColumn('generate_date', function ($row) {
                return $row->generate_date
                    ? Carbon::parse($row->generate_date)->format('d-m-Y')
                    : '-';
            })

            ->addColumn('generated_in', function ($row) {

                $badgeClass = 'bg-label-primary';

                if ($row->generated_in == 'Cron') {
                    $badgeClass = 'bg-label-info';
                } elseif ($row->generated_in == 'Manual') {
                    $badgeClass = 'bg-label-warning';
                }

                return '<span class="badge ' . $badgeClass . '">'
                    . $row->generated_in .
                    '</span>';
            })

            ->addColumn('action', function ($row) {

                return '
                <div class="d-flex flex-column flex-sm-row align-items-stretch align-items-sm-center gap-2 justify-content-center">

                    <a href="' . route('admin.gold_roi_history', [
                    'date' => Carbon::parse($row->generate_date)->format('Y-m-d')
                ]) . '"
                       class="btn btn-sm btn-primary">
                        View
                    </a>

                    <a href="#"
                       data-id="' . $row->id . '"
                       data-bs-toggle="modal"
                       data-bs-target="#deleteConfirmModal"
                           onclick        = "setDeleteId(this)">
                        <i class="ti tabler-trash menu-icon text-danger"></i>
                    </a>

                </div>
            ';
            })

            ->rawColumns(['generated_in', 'action'])
            ->make(true);
    }

    public function gold_roi_history($date)
    {
        return view('Admin.gold_roi_history', compact('date'));
    }

    public function gold_roi_history_data($date)
    {
        $data = FinAccount::with(['user', 'roiUser'])
            ->whereDate('entry_date', $date)
            ->where('type', 'roi')
            ->where('remark', 'ROI income');

        return DataTables::eloquent($data)

            ->addIndexColumn()

            ->editColumn('entry_date', function ($row) {
                return $row->entry_date
                    ? Carbon::parse($row->entry_date)->format('d-m-Y')
                    : '-';
            })

            ->addColumn('user_id', function ($row) {
                return optional($row->user)->user_id;
            })

            ->addColumn('user_name', function ($row) {
                return optional($row->user)->name;
            })

            ->addColumn('investment', function ($row) {
                return number_format($row->roiUser->wallet_value ?? 0, 2);
            })

            // ->addColumn('investment', function ($row) {
            //     return number_format($row->credit / ($row->percentage / 100), 2);
            // })

            ->addColumn('percentage', function ($row) {
                return $row->percentage . '%';
            })

            ->editColumn('credit', function ($row) {
                return number_format($row->credit, 2);
            })

            ->rawColumns([])
            ->make(true);
    }

    public function delete_gold_roi(Request $request)
    {
        $request->validate([
            'id'         => 'required|exists:gold_roi_histories,id',
            'dlt_reason' => 'required|string',
        ]);

        DB::beginTransaction();

        try {

            $history = GoldRoiHistory::findOrFail($request->id);

            $history->dlt_reason = $request->dlt_reason;
            $history->save();

            $date = $history->generate_date;

            Log::info('GOLD ROI DELETE START', [
                'history_id'    => $history->id,
                'generate_date' => $date
            ]);

            // Delete ROI income entries
            $deletedAccounts = FinAccount::whereDate('entry_date', $date)
                ->where('type', 'roi')
                ->where('remark', 'ROI income')
                ->delete();

            Log::info('FIN ACCOUNT ROI DELETED', [
                'rows' => $deletedAccounts
            ]);

            // Soft delete history
            $history->delete();

            Log::info('GOLD ROI HISTORY DELETED', [
                'history_id' => $history->id
            ]);

            DB::commit();

            return back()->with(
                'success',
                'Gold ROI generation reversed successfully'
            );
        } catch (\Exception $e) {

            DB::rollBack();

            Log::error('GOLD ROI DELETE FAILED', [
                'error'      => $e->getMessage(),
                'history_id' => $request->id,
                'line'       => $e->getLine(),
                'file'       => $e->getFile(),
            ]);

            return back()->with(
                'error',
                'Something went wrong'
            );
        }
    }


    public function gold_advance()
    {
        return view('Admin.gold_advance');
    }

    public function gold_advance_data(Request $request)
    {
        try {

            $users = FinRoiUser::with('user')
                ->orderBy('id', 'asc');

            return DataTables::of($users)

                ->addIndexColumn()

                // USER INFO
                ->addColumn('user_info', function ($row) {

                    return '
                <div class="d-flex flex-column gap-3">

                    <div class="label-sm">
                        User Name :&nbsp;' . ($row->user->name ?? '-') . '
                    </div>

                    <div class="label-sm">
                        User ID :&nbsp;' . $row->user_id . '
                    </div>

                </div>
                ';
                })

                // REFERRAL
                ->addColumn('ref_info', function ($row) {

                    $refUser = User::where(
                        'user_id',
                        $row->user->ref_id ?? null
                    )->first();

                    return '
                <div class="d-flex flex-column gap-2">

                    <div>
                        <strong>Referral Name :</strong>
                        ' . ($refUser->name ?? '-') . '
                    </div>

                    <div>
                        <strong>Referral ID :</strong>
                        ' . ($row->user->ref_id ?? '-') . '
                    </div>

                </div>
                ';
                })

                // PHONE
                ->addColumn('phone_number', function ($row) {

                    return '
                <i class="ti tabler-phone me-1 text-primary"></i>
                ' . ($row->user->phone ?? '-') . '
                ';
                })

                // INVESTMENT
                ->addColumn('investment', function ($row) {

                    return '
                <span class="badge bg-label-success">
                    ₹ ' . number_format($row->wallet_value, 2) . '
                </span>
                ';
                })

                // TEAM
                ->addColumn('daily_roi', function ($row) {

                    return '
                <span class="amount">
                    ₹ ' . number_format($row->roi_amount, 2) . '
                </span>
                ';
                })

                // ROI %
                ->addColumn('roi_percentage', function ($row) {

                    return '
                <span class="badge bg-label-success">
                    ' . number_format($row->roi_percentage, 2) . ' %
                </span>
                ';
                })

                // DAYS
                ->addColumn('remaining_days', function ($row) {

                    return '
                <span class="badge bg-label-warning">
                    ' . $row->days . ' Days
                </span>
                ';
                })


                // given Days
                ->addColumn('roi_given_days', function ($row) {

                    $roi_given_days = DB::table('fin_account')
                        ->where('description', $row->roi_id)
                        ->count();
                    return '
                        <span class="badge bg-label-primary">
                            ' . $roi_given_days . '
                        </span>
                    ';
                })



                // BOND
                ->addColumn('bond_info', function ($row) {

                    return '
                     <a href="' . route('admin.bond_details', $row->roi_id) . '"
                    class="btn btn-label-info btn-sm">

                    <i class="ti tabler-file-certificate me-1"></i>

                    Bond

                </a>
                ';
                })

                // ACTION
                ->addColumn('action', function ($row) {

                    return '
                <div class="d-flex gap-2 justify-content-center">

                    <button class="btn btn-sm btn-label-primary"
                        data-bs-toggle="modal"
                        data-bs-target="#percentageModal">

                        <i class="ti tabler-percentage me-1"></i>

                        ROI

                    </button>

                    <button class="btn btn-sm btn-label-info"
                        data-bs-toggle="modal"
                        data-bs-target="#daysModal">

                        <i class="ti tabler-calendar-time me-1"></i>

                        Days

                    </button>

                </div>
                ';
                })

                // DELETE
                ->addColumn('delete_info', function ($row) {

                    return '
                <button class="btn btn-label-danger"
                    data-bs-toggle="modal"
                    data-bs-target="#delete">

                    <i class="ti tabler-trash"></i>

                </button>
                ';
                })

                ->rawColumns([
                    'user_info',
                    'ref_info',
                    'phone_number',
                    'investment',
                    'daily_roi',
                    'roi_percentage',
                    'remaining_days',
                    'roi_given_days',
                    'bond_info',
                    'action',
                    'delete_info'
                ])

                ->make(true);
        } catch (\Exception $e) {

            Log::error('Gold Advance Data Error', [
                'message' => $e->getMessage(),
                'line' => $e->getLine()
            ]);

            return response()->json([
                'error' => 'Something went wrong'
            ], 500);
        }
    }
}
