<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\DMLog;
use App\Models\OrderTransaction;
use Illuminate\Http\Request;
use App\Models\AccountTransaction;
use App\Models\Store;
use App\Models\DeliveryMan;
use App\Models\AdminWallet;
use App\Models\Admin;
use Illuminate\Support\Facades\Validator;
use App\CentralLogics\Helpers;
use Illuminate\Support\Facades\DB;
use Brian2694\Toastr\Facades\Toastr;
use Rap2hpoutre\FastExcel\FastExcel;

class AccountTransactionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $account_transaction = AccountTransaction::latest()->paginate(config('default_pagination'));
        return view('admin-views.account.index', compact('account_transaction'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'type' => 'required|in:store,deliveryman',
            'method' => 'required',
            'store_id' => 'required_if:type,store',
            'deliveryman_id' => 'required_if:type,deliveryman',
            'amount' => 'required|numeric',
        ]);

        if ($request['store_id'] && $request['deliveryman_id']) {
            $validator->getMessageBag()->add('from type', 'Can not select both deliveryman and store');
            return response()->json(['errors' => Helpers::error_processor($validator)]);
        }


        if($request['type']=='store' && $request['store_id'])
        {
            $store = Store::findOrFail($request['store_id']);
            $data = $store;
            $current_balance = $data->wallet?$data->wallet->collected_cash:0;
        }
        else if($request['type']=='deliveryman' && $request['deliveryman_id'])
        {
            $data = DeliveryMan::findOrFail($request['deliveryman_id']);

            $current_balance = $data->wallet?$data->wallet->collected_cash:0;
        }

        /*if ($current_balance < $request['amount']) {
            $validator->getMessageBag()->add('amount', translate('messages.insufficient_balance'));
            return response()->json(['errors' => Helpers::error_processor($validator)]);
        }*/

        if ($validator->fails()) {
            return response()->json(['errors' => Helpers::error_processor($validator)]);
        }

        $account_transaction = new AccountTransaction();
        $account_transaction->from_type = $request['type'];
        $account_transaction->from_id = $data->id;
        $account_transaction->method = $request['method'];
        $account_transaction->ref = $request['ref'];
        $account_transaction->amount = $request['amount'];
        $account_transaction->current_balance = $current_balance;
        $account_transaction->transaction_date = isset($request->transaction_date) ? $request->transaction_date : null;
        $account_transaction->admin_id = auth('admin')->user()->id;

        if($request['type'] == 'deliveryman'){

            if(!empty($request->dm_log_message)) {
                $getDMLogMessage = $request->dm_log_message;
                if($request->dm_log_message == 'ref'){
                    $getDMLogMessage = $request->ref;
                }
                if(!empty($getDMLogMessage)) {
                    DMLog::createLog($data->id, $getDMLogMessage, $request['amount'], null);
                }
            }
        }

        try
        {
            DB::beginTransaction();
            $account_transaction->save();
            //$data->wallet->decrement('collected_cash', $request['amount']);
            AdminWallet::where('admin_id', Admin::where('role_id', 1)->first()->id)->increment('manual_received', $request['amount']);
            DB::commit();

            $dm = DeliveryMan::where('id', $data->id)->first();
            if($dm->status == '0'){
                $theRemainingBalance = \App\Models\DeliveryMan::getTheRemainingBalanceForDeliveryMan($dm, '', '');
                if($theRemainingBalance < 0) {
                    $dm->status = 1;
                    $dm->save();
                }
            }
        }
        catch(\Exception $e)
        {
            DB::rollBack();
        }

        return response()->json(200);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $account_transaction=AccountTransaction::findOrFail($id);
        return view('admin-views.account.view', compact('account_transaction'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        AccountTransaction::where('id', $id)->delete();
        Toastr::success(translate('messages.account_transaction_removed'));
        return back();
    }

    public function export_account_transaction(Request $request){
        $account_transaction = AccountTransaction::latest()->get();
        if($request->type == 'excel'){
            return (new FastExcel(Helpers::export_account_transaction($account_transaction)))->download('Account_transactions.xlsx');
        }elseif($request->type == 'csv'){
            return (new FastExcel(Helpers::export_account_transaction($account_transaction)))->download('Account_transactions.csv');
        }
    }

    public function export_delivery_man_transaction(Request $request, $delivery_man_id){

        $account_transaction = new AccountTransaction;
        $order_transactions = new OrderTransaction;

        if($delivery_man_id != '0') {
            $account_transaction = $account_transaction->where('from_id', $delivery_man_id)->where('from_type', 'deliveryman');
            $order_transactions = $order_transactions->where('delivery_man_id', $delivery_man_id);
        }else{
            $account_transaction = $account_transaction->where('from_type', 'deliveryman');
        }

        if(session()->has('from_date') && session()->has('to_date') && $request->has('filter') && $request->filter == 'custom') {
            $from = session('from_date');
            $to = session('to_date');
        }

        if($request->has('filter') && $request->filter == 'this_year'){
            $from = date('Y-01-01');
            $to = date('Y-12-31');
        }

        if($request->has('filter') && $request->filter == 'previous_year'){
            $prevYear = date('Y') - 1;
            $from = date($prevYear . '-01-01');
            $to = date($prevYear . '-12-31');
        }

        if($request->has('filter') && $request->filter == 'this_month'){
            $lastDayInMonth = date('t');
            $from = date('Y-m-01');
            $to = date('Y-m-' . $lastDayInMonth);
        }

        if($request->has('filter') && $request->filter == 'this_week'){
            if(date('D')!='Sat') {
                $from = date('Y-m-d',strtotime('last Saturday'));
            }else{
                $from = date('Y-m-d');
            }
            if(date('D')!='Thu') {
                $to = date('Y-m-d',strtotime('next Thursday'));
            }else{
                $to = date('Y-m-d');
            }
        }

        if(isset($from) && isset($to)){
            $account_transaction = $account_transaction->whereBetween('created_at', [$from . " 00:00:00", $to . " 23:59:59"]);
            $order_transactions = $order_transactions->whereBetween('created_at', [$from . " 00:00:00", $to . " 23:59:59"]);
        }

        if($request->has('module_id')){
            $module_id = $request->module_id;
            $order_transactions = $order_transactions->where('module_id', $module_id);
        }

        if($request->has('zone_id')){
            $zone_id = $request->zone_id;
            $order_transactions = $order_transactions->where('zone_id', $zone_id);
        }

        $account_transaction = $account_transaction->orderBy('id', 'DESC')->get();
        $order_transactions = $order_transactions->orderBy('id', 'DESC')->get();

        if($request->type == 'excel'){
            return (new FastExcel(Helpers::export_delivery_man_transaction($account_transaction, $order_transactions)))->download('Account_transactions.xlsx');
        }elseif($request->type == 'csv'){
            return (new FastExcel(Helpers::export_delivery_man_transaction($account_transaction, $order_transactions)))->download('Account_transactions.csv');
        }
    }

    public function search_account_transaction(Request $request){
        $key = explode(' ', $request['search']);
        $account_transaction = AccountTransaction::where(function ($q) use ($key) {
            foreach ($key as $value) {
                $q->orWhere('ref', 'like', "%{$value}%");
            }
        })->get();

        return response()->json([
            'view'=>view('admin-views.account.partials._table', compact('account_transaction'))->render(),
            'total'=>$account_transaction->count()
        ]);
    }
}
