<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\SellerWithdrawal;
use Gate;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use App\Imports\SellerWalletImport;
use App\Exports\SellerWalletExport;
use Maatwebsite\Excel\Facades\Excel;
use DB;

class SellerWalletController extends Controller
{

    public function index(Request $request)
    {
        //abort_if(Gate::denies('make_access'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        if ($request->ajax()) {
            $query = User::query()->select(sprintf('%s.*', (new User)->table));
            $query->whereHas('roles', function ($q) use ($request) {
                $q->where('title', 'Seller');
            });
            if($request->name){
                $query = $query->where('first_name', 'like', '%' . $request->name . '%')->orWhere('last_name', 'like', '%' . $request->name . '%');
            }
            if($request->full_phone){
                $query = $query->where('phone', 'like', '%' . $request->full_phone . '%');
            }
            if(isset($request->form_current_balance) && $request->to_current_balance == ''){
                $query = $query->where('current_balance','>=',$request->form_current_balance);
            }
            if(isset($request->to_current_balance) && $request->form_current_balance == ''){
                $query = $query->where('current_balance','<=',$request->to_current_balance);
            }
            if(isset($request->to_current_balance) && isset($request->form_current_balance)){
                $query = $query->whereBetween('current_balance',[$request->form_current_balance, $request->to_current_balance]);
            }

            $table = Datatables::of($query);

            $table->editColumn('id', function ($row) {
                return $row ? $row->id : '';
            });
            $table->editColumn('user', function ($row) {
                return $row ? $row->first_name.' '.$row->last_name : '';
            });
            $table->editColumn('phone', function ($row) {
                return $row ? $row->phone : '';
            });
            $table->editColumn('current_balance', function ($row) {
                return $row->current_balance ? 'BHD '.number_format($row->current_balance, 2) : '0';
            });
            $table->editColumn('pending_balance', function ($row) {
                return $row->pending_balance ? 'BHD '.number_format($row->pending_balance, 2) : '0';
            });
            $table->editColumn('last_withdrawal', function ($row) {
                $lastWith = SellerWithdrawal::where('user_id', $row->id)->latest()->first();
                return $lastWith ? 'BHD '.number_format($lastWith->amount, 2) : 0;
            });
            $table->editColumn('total_earnings', function ($row) {
                return $row->total_earnings ? 'BHD '.number_format($row->total_earnings, 2) : '0';
            });
        
            return $table->make(true);
        }

        return view('admin.seller_wallet.index');
    }

    public function export(Request $request){
        $filters = $request->all();
        return Excel::download(new SellerWalletExport($filters), 'seller_wallet.xlsx');
    }

    public function show($id)
    {
        $user = User::find($id);
        $lastWith = SellerWithdrawal::where('user_id', $id)->latest()->first();
        $lastWithData = $lastWith ? $lastWith->amount : 0;

        return view('admin.seller_wallet.show', compact('user','lastWithData'));
    }

    public function importSellerWallet(Request $request){
        try {
            $request->validate([
                'import_file' => 'required|mimes:xlsx,csv',
            ]);

            Excel::import(new SellerWalletImport, $request->file('import_file'));

            return redirect()->back()->with('success', 'File imported successfully!');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
}
