<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\Helper;
use App\Helpers\LogActivity;
use App\Http\Controllers\Controller;
use App\Http\Resources\SavingResource;
use App\Models\Client;
use App\Models\CreditOfficer;
use App\Models\Loan;
use App\Models\Saving;
use App\Models\User;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class SavingController extends Controller
{
     function __construct()
    {
         $this->middleware('permission:Saving List', ['only' => ['index']]);
         $this->middleware('permission:Saving Request', ['only' => ['requestSaving']]);
         $this->middleware('permission:Saving Approve', ['only' => ['approveSaving']]);
         $this->middleware('permission:Saving Reject', ['only' => ['rejectSaving']]);
    }
    public function index(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = Saving::where(function($query) use ($request){
            $query->whereIn('branch_id',Helper::byBranch());
            $query->where('currency_id',Helper::byCurrency());
            if(!$request->date==[])
            {
                $query->whereBetween(DB::raw("DATE_FORMAT(date_approved, '%Y-%m-%d')"), $request->date);
            }
            if(!$request->client_id ==[]){
                $query->whereIn('client_id',$request->client_id);
            }
            if(!$request->co_id ==[])
            {
                $query->whereIn('co_id',$request->co_id);
            }
            if(!$request->status ==[])
            {
                $query->whereIn('status',$request->status);
            }
        })
        ->orderBy('id','DESC')
        ->paginate($per_page);
        return SavingResource::collection($data);
    }

    public function requestSaving(Request $request)
    {
        try{
            DB::beginTransaction();
                if($request->type==1)
                {
                    $saving = Saving::find($request->id);
                    $saving->status = 2;
                    $saving->update();
                    $message = 'ស្នើរដក​ប្រាក់សន្សំអតិថិជន';

                }else if($request->type==2){
                    $saving = Saving::find($request->id);
                    $saving->status = 5;
                    $saving->update();

                    $message = 'ស្នើរកាត់​ប្រាក់សន្សំអតិថិជន';
                }
                $client = Client::find($saving->client_id);
                $user = User::find(Auth::user()->id);
                $client = Client::find($saving->client_id);
                $subject = "$message $client->name ដោយជោគជ័យ ដោយ $user->name.";
                $subject_type = get_class($saving);
                $subject_id = $saving->id;
                $causer_type = get_class($user);
                $causer_id = Auth::user()->id;
                $branch = Auth::user()->branch_id;
                $log_name = 'Saving Model';
                LogActivity::addToLog($subject,$subject_type,$subject_id,$causer_type,$causer_id,$branch,$log_name);

                DB::commit();
                $res = [
                    'status' => 1,
                    'message'=>"$message $client->name ដោយជោគជ័យ",
                ];
            }catch(Exception $e){
                DB::rollBack();
                $res = [
                    'status'  => 0,
                    'message' => "$message $client->name បរាជ័យ",
                    'data'    => $e->getMessage(),
                ];
            }
        return response()->json($res,200);
    }
    public function approveSaving(Request $request)
    {
        try{
            DB::beginTransaction();
                $today= date('Y-m-d');
                if($request->type==1)
                {
                    $saving = Saving::find($request->id);
                    $saving->status =3;
                    $saving->status_pay = 1;
                    $saving->date_approved = $today;
                    $saving->update();

                    $message = 'បានដក​ប្រាក់សន្សំអតិថិជន';
                }else if($request->type==2){
                    $saving = Saving::find($request->id);
                    $saving->status = 4;
                    $saving->status_pay = 2;
                    $saving->date_approved = $today;
                    $saving->update();

                    $message = 'បានកាត់​ប្រាក់សន្សំអតិថិជន';
                }
                $client = Client::find($saving->client_id);
                $user = User::find(Auth::user()->id);
                $client = Client::find($saving->client_id);
                $subject = "$message $client->name ដោយជោគជ័យ ដោយ $user->name.";
                $subject_type = get_class($saving);
                $subject_id = $saving->id;
                $causer_type = get_class($user);
                $causer_id = Auth::user()->id;
                $branch = Auth::user()->branch_id;
                $log_name = 'Saving Model';
                LogActivity::addToLog($subject,$subject_type,$subject_id,$causer_type,$causer_id,$branch,$log_name);

                DB::commit();
                $res = [
                    'status' => 1,
                    'message'=>"$message $client->name ដោយជោគជ័យ",
                ];
            }catch(Exception $e){
                DB::rollBack();
                $res = [
                    'status'  => 0,
                    'message' => "$message $client->name បរាជ័យ",
                    'data'    => $e->getMessage(),
                ];
            }
        return response()->json($res,200);
    }
    // public function rejectSaving($id)
    // {
    //     $saving = Saving::find($id);
    //     $saving->status = 1;
    //     $saving->date_approved = Null;
    //     $saving->update();
    //     $client = Client::find($saving->client_id);
    //     $user_id = User::where('id',Auth::user()->id)->first();
    //     LogActivity::addToLog("Reject $client->name saving is Successfully by user name:$user_id->name.");
    //     return response()->json(["message"=>"Reject $client->name saving is Successfully by user name:$user_id->name."]);
    // }
}
