<?php

namespace App\Http\Controllers\Admin;

use App\Models\User;
use App\Models\Group;
use App\Models\Branch;
use App\Models\Client;
use App\Helpers\Helper;
use App\Models\Commune;
use App\Models\Village;
use App\Models\Category;
use App\Models\District;
use App\Models\Province;
use App\Models\Collateral;
use App\Models\LoanStatus;
use Illuminate\Http\Request;
use App\Models\PaymentMethod;
use App\Models\TermCondition;
use App\Http\Controllers\Controller;
use App\Http\Resources\ShowAccReceivableDetailResource;
use App\Http\Resources\ShowPaymentResource;
use App\Models\AccReceivableDetails;
use App\Models\AccReceivables;
use App\Models\CollateralDetail;
use App\Models\Loan;
use Illuminate\Support\Facades\Auth;

class ComponentController extends Controller
{
    public function autoCompleteAddress(Request $request)
    {
        return Village::search($request->searchText)->take(10)->pluck('address_km')->toArray();
    }

    public function getProvince(Request $request)
    {
        $data = Province::all()->map(function($value){
            return [
                'id' => $value->id,
                'value' => $value->id,
                'full_name_km' => $value->full_name_km,
            ];
        });
        // dd($data);
        return response()->json($data);
    }

    public function getDistrict(Request $request)
    {
        return District::where('province_id', $request->province_id)->get()->map(function($value){
            return [
                'id' => $value->id,
                'value' => $value->id,
                'full_name_km' => $value->full_name_km,
            ];
        });
    }

    public function getCommune(Request $request)
    {
        return Commune::where('district_id', $request->district_id)->get()->map(function($value){
            return [
                'id' => $value->id,
                'value' => $value->id,
                'full_name_km' => $value->full_name_km,
            ];
        });
    }

    public function getVillage(Request $request)
    {
        return Village::where('commune_id', $request->commune_id)->get()->map(function($value){
            return [
                'id' => $value->id,
                'value' => $value->id,
                'full_name_km' => $value->full_name_km,
            ];
        });
    }

    public function getVillageClient()
    {
        $client = Client::groupby('village_id')->get();
        $arr_id = [];
        foreach($client as $value){
            $arr_id[] = $value['village_id'];
        }
        return Village::whereIn('id', $arr_id)->get()->map(function($value){
            return [
                'id' => $value->id,
                'value' => $value->id,
                'full_name_km' => $value->full_name_km,
            ];
        });
    }

    public function getClient()
    {
        return Client::whereIn('branch_id',Helper::byBranch())
            ->where(function($query){
                // if(Auth::user()->id!=1 && Auth::user()->type==1 || Auth::user()->type==3){
                //     $query->whereIn('created_by',Helper::group())->orWhere('created_by',Auth::user()->id);
                // }
                if(Auth::user()->type==2){
                    $query->where('created_by',Auth::user()->id);
                    // Client related with loans
                    $query->orWhereHas('clientHasLoan',function($sub){
                        $sub->where('co_id',Auth::user()->id);
                    });
                }
            })
            ->where('status',1)
            ->orderby('id','desc')
            ->get()
            ->map(function($value){
                return [
                    'id'    => $value->id,
                    'value' => $value->id,
                    'name'  => $value->name,
                ];
            });
    }

    public function getCO()
    {
        return User::whereIn('branch_id',Helper::byBranch())
            ->where(function($query){
                if(Auth::user()->type==1 || Auth::user()->type==3){
                    $query->whereIn('id',Helper::group())->orWhere('id',Auth::user()->id);
                } else{
                    $query->where('id',Auth::user()->id);
                }
            })
            ->where('status',1)
            ->where('type',2)
            ->get()
            ->map(function($value){
                return [
                    'id'    => $value->id,
                    'value' => $value->id,
                    'name'  => $value->name,
                ];
            });
    }

    public function getMemberCO()
    {
        return User::whereIn('branch_id',Helper::byBranch())
            ->where('status',1)
            ->where('type',2)
            ->get()
            ->map(function($value){
                return [
                    'id'    => $value->id,
                    'value' => $value->id,
                    'name'  => $value->name,
                ];
            });
    }

    public function getCOLoan(Request $request)
    {
        // dd($request->all());
        return User::whereIn('branch_id',Helper::byBranch())->where('id','<>',$request->co_id)->where('status',1)->where('type',2)->get()->map(function($value){
            return [
                'id'    => $value->id,
                'value' => $value->id,
                'name'  => $value->name,
            ];
        });
    }
 
    public function getLoanStatus(Request $request)
    {
        return LoanStatus::where('id','<',4)->get()->map(function($value){
            return [
                'id' => $value->id,
                'value' => $value->id,
                'title' => $value->title,
            ];
        });
    }

    public function getLoanTermType()
    {
        $data = [
            ['id'=>1, 'value'=> 1,'title'=>'ថ្ងៃ'],
            ['id'=>2, 'value'=> 2,'title'=>'សប្ដាហ៍'],
            ['id'=>3, 'value'=> 3,'title'=>'កន្លះខែ'],
            ['id'=>4, 'value'=> 4,'title'=>'ខែ'],
        ];
        return $data;
    }

    public function getCategory(Request $request)
    {
        return Category::get()->map(function($value){
            return [
                'id' => $value->id,
                'value' => $value->id,
                'title' => $value->title,
            ];
        });
    }

    public function getUser(Request $request)
    {
        return User::whereIn('branch_id',Helper::byBranch())
            ->where(function($query) use ($request){
                if(isset($request->type)){
                    if($request->type==1){
                        $query->where('id','<>',1); // Not admin.
                    }
                    $query->whereIn('type',[1,3]);
                }
            })
            ->where('status',1)
            ->get()
            ->map(function($value){
                return [
                    'id'    => $value->id,
                    'value' => $value->id,
                    'name'  => $value->name,
                ];
        });
    }

    public function getCollateral(Request $request)
    {
        return Collateral::get()->map(function($value){
            return [
                'id' => $value->id,
                'value' => $value->id,
                'title' => $value->title,
            ];
        });
    }
    public function getTermCondition(Request $request)
    {
        return TermCondition::get()->map(function ($value) {
            return [
                'id'      => $value->id,
                'value'   => $value->id,
                'name_km' => $value->name_km,
            ];
        });
    }

    public function getCollateralCustom(Request $request)
    {
        return Collateral::where(function ($query) use ($request) {
            if ($request->cat_id) {
                $query->where('cat_id', $request->cat_id);
            }
        })
        ->get()->map(function($value){
            return [
                'id' => $value->id,
                'value' => $value->id,
                'title' => $value->title,
            ];
        });
    }

    public function getDefaultCurrency(Request $request)
    {
        $data = Auth::user()->currency_id;
        return $data;
    }

    public function getClientNameCode(Request $request)
    {
        return Client::whereIn('branch_id', Helper::byBranch())
            ->where(function ($query) {
                if(Auth::user()->type==2){
                    $query->where('created_by',Auth::user()->id);
                    $query->orWhereHas('clientHasLoan',function($sub){
                        $sub->where('co_id',Auth::user()->id);
                    });
                }
            })
            ->where('status', 1)
            ->whereDoesntHave('clientHasLoan', function ($q) {
                $q->whereIn('loan_status_id', [1, 2, 5, 7, 8]);
            })
            ->orderBy('id', 'desc')
            ->get()
            ->map(function ($value) {
                return [
                    'id'    => $value->id,
                    'value' => $value->id,
                    'name'  => $value->name . ' (' . $value->code . ')',
                ];
            });
    }

    public function getBranch()
    {
        return Branch::get()->map(function($value){
            return [
                'id' => $value->id,
                'value' => $value->id,
                'name_en' => $value->name_en,
            ];
        });
    }

    public function getBranchTransfer()
    {
        return Branch::where('id','<>',Auth::user()->branch_id)->get()->map(function($value){
            return [
                'id' => $value->id,
                'value' => $value->id,
                'name_km' => $value->name_km,
            ];
        });
    }

    public function getCoByBranch(Request $request)
    {
        return User::where('branch_id',$request->branch_id)
            ->where('status',1)
            ->where('type',2)
            ->get()
            ->map(function($value){
                return [
                    'id'    => $value->id,
                    'value' => $value->id,
                    'name'  => $value->name,
                ];
            });
    }
    public function getClientLoan()
    {
        return Loan::where('loan_status_id',2)
            ->whereIn('branch_id',Helper::byBranch())
            ->where('currency_id',Helper::byCurrency())
            ->whereIn('co_id',Helper::group())
            ->where('client_type',1)
            ->get()
            ->map(function($value){
                return [
                    'id'    => $value->id,
                    'value' => $value->id,
                    'client_loan' => $value->client->name.'('.$value->client->code.')'.'-('.$value->loan_code.')',
                ];
            });
    }

    public function getAllClientLoan()
    {
        return Loan::whereIn('loan_status_id',[2,3])
            ->whereIn('branch_id',Helper::byBranch())
            ->where('currency_id',Helper::byCurrency())
            ->whereIn('co_id',Helper::group())
            ->where('client_type',1)
            ->get()
            ->map(function($value){
                return [
                    'id'    => $value->id,
                    'value' => $value->id,
                    'name'  => $value->client->name.'('.$value->loan_code.')'.'-វគ្គទី:'.$value->level_loan,
                ];
            });
    }

    public function showSchedulePayment($id)
    {
        $loans = Loan::find($id);
        $acc_receivables = AccReceivables::where('loan_id',$id)->whereIn('payment_status_id',[1,2,3])->get();
        return [
            'client_name' => $loans->client->name.'('.$loans->loan_code.')'.'-វគ្គទី:'.$loans->level_loan,
            'schedule'    => $acc_receivables?ShowPaymentResource::collection($acc_receivables):[],
        ];
        
    }

    public function showScheduleDetail($id)
    {
        $accReceivable = AccReceivables::find($id);

        $data = AccReceivableDetails::where('acc_id',$id)
            ->whereIn('branch_id',Helper::byBranch())
            ->where('currency_id',Helper::byCurrency())
            ->get();

        $max_received_id = AccReceivableDetails::where('loan_id',$accReceivable->loan_id)
            ->whereIn('branch_id',Helper::byBranch())
            ->where('currency_id',Helper::byCurrency())
            ->get()
            ->max('id');

        return array(
            'client_name'    => $accReceivable->client->name??'',
            'max_id_details' => $max_received_id??'',
            'data'           => ShowAccReceivableDetailResource::collection($data)
        );
    }

    public function getCollateralCustomDetail(Request $request)
    {
        return CollateralDetail::where(function ($query) use ($request) {
            if ($request->client_id) {
                $query->where('client_id', $request->client_id);
            }
        })
        // ->where('status',1)
        ->get()->map(function($value){
            return [
                'id' => $value->id,
                'value' => $value->id,
                'collateral_detail_id' => $value->id,
                'title' => $value->model_type,
                'status' => $value->status,
            ];
        });
    }
}
