<?php

namespace Modules\Client\Http\Controllers\Api;

use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use App\Models\ClaimRequest;
use Modules\Client\Transformers\ClaimReport\ShowResources;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use App\Models\File;
use Illuminate\Http\Request;

class ClaimReportController extends Controller
{
    public function claimStatus($corporateId)
    {
        $requesteds = ClaimRequest::query()
            ->whereHas('member', function ($query) use ($corporateId) {
                $query->whereHas('employeds', function ($corporateEmployee) use ($corporateId) {
                    $corporateEmployee->where('corporate_id', $corporateId);
                });
            })
            ->where('status', 'requested')
            ->get();
        $approveds = ClaimRequest::query()
            ->whereHas('member', function ($query) use ($corporateId) {
                $query->whereHas('employeds', function ($corporateEmployee) use ($corporateId) {
                    $corporateEmployee->where('corporate_id', $corporateId);
                });
            })
            ->whereHas('claim', fn ($query) => $query->where('status', 'approved'))
            ->where('status', 'approved')
            ->get();

        $rejecteds = ClaimRequest::query()
            ->whereHas('member', function ($query) use ($corporateId) {
                $query->whereHas('employeds', function ($corporateEmployee) use ($corporateId) {
                    $corporateEmployee->where('corporate_id', $corporateId);
                });
            })
            ->whereHas('claim', fn ($query) => $query->where('status', 'declined'))
            ->where('status', 'approved')
            ->get();

        $disbrusments = ClaimRequest::query()
            ->whereHas('member', function ($query) use ($corporateId) {
                $query->whereHas('employeds', function ($corporateEmployee) use ($corporateId) {
                    $corporateEmployee->where('corporate_id', $corporateId);
                });
            })
            ->whereHas('claim', fn ($query) => $query->where('status', 'disbrusmented'))
            ->where('status', 'approved')
            ->get();

        return Helper::responseJson([
            'requesteds' => count($requesteds),
            'approveds' => count($approveds),
            'rejecteds' => count($rejecteds),
            'disbrusments' => count($disbrusments)
        ]);
    }

    public function claimDetail($corporate_id, $claimRequestId)
    {
        $claimRequestId = Crypt::decrypt($claimRequestId);

        $status = DB::table('claim_requests')
                    ->leftJoin('claims', 'claim_requests.id', '=', 'claims.claim_request_id')
                    ->leftJoin('members', 'claim_requests.member_id', '=', 'members.id')
                    ->leftJoin('corporate_employees', 'members.id', '=', 'corporate_employees.member_id')
                    ->leftJoin('corporate_divisions', 'corporate_employees.division_id', '=', 'corporate_divisions.id')
                    ->where('corporate_employees.corporate_id', '=', $corporate_id)
                    ->where('claim_requests.id', '=', $claimRequestId)
                    ->select(
                        'claim_requests.submission_date', 
                        DB::raw('
                            CASE 
                                WHEN claim_requests.status = "requested" THEN "requested"
                                WHEN claim_requests.status = "approved" AND claims.status = "approved" THEN "approved"
                                WHEN claim_requests.status = "approved" AND claims.status = "declined" THEN "declined"
                                WHEN claim_requests.status = "approved" AND claims.status = "disbrusmented" THEN "disbrusmented"
                                /*WHEN claim_requests.status = "approved" AND claims.status = "received" THEN "pending"*/
                                WHEN claim_requests.status = "approved" AND claims.status = "received" THEN "reviewed"
                                ELSE "" 
                            END AS status
                        ')
                    )
                    ->first();
        $results['status'] = $status;
        $timeline = DB::table('claim_logs')
                        ->where('claim_logs.claim_request_id', '=', $claimRequestId)
                        ->select(
                            DB::raw('
                                CASE
                                    WHEN claim_logs.status = "requested" THEN "Request"
                                    WHEN claim_logs.status = "reviewed" THEN "Review"
                                    WHEN claim_logs.status = "approved" THEN "Approval"
                                    WHEN claim_logs.status = "declined" THEN "Decline"
                                    ELSE "-"
                                END AS txt_status
                            '),
                            DB::raw('
                                CASE
                                    WHEN claim_logs.status = "requested" THEN "#159C9C"
                                    WHEN claim_logs.status = "reviewed" THEN "#0C53B7"
                                    WHEN claim_logs.status = "approved" THEN "#229A16"
                                    WHEN claim_logs.status = "declined" THEN "#FF4842"
                                    ELSE "-"
                                END AS txt_status_color
                            '),
                            DB::raw('
                                CASE
                                    WHEN claim_logs.status = "requested" THEN "#00AB5529"
                                    WHEN claim_logs.status = "reviewed" THEN "#1890FF29"
                                    WHEN claim_logs.status = "approved" THEN "#54D62C29"
                                    WHEN claim_logs.status = "declined" THEN "#FF48427A"
                                    ELSE "-"
                                END AS txt_status_backgroundColor
                            '),
                            'claim_logs.date',
                            'claim_logs.description',
                            'claim_logs.status'
                        )
                        ->orderBy('claim_logs.id', 'desc')
                        ->get();
        $results['timeline'] = $timeline;
        $request_files = DB::table('claim_request_files')
                        ->where('claim_request_files.claim_request_id', '=', $claimRequestId)
                        ->select(
                            'claim_request_files.*',
                            DB::raw('(SELECT files.fileable_id FROM files WHERE files.fileable_id = claim_request_files.claim_request_id AND files.type = claim_request_files.type LIMIT 1) AS check_files'),
                        )
                        ->get();
        $results['request_files'] = $request_files;
        $documents = DB::table('files')
                                ->where('fileable_type', 'App\Models\ClaimRequest')
                                ->where('fileable_id', $claimRequestId)
                                ->select('original_name', \DB::raw("CONCAT('" . env('APP_URL') . "/storage/', path) as path"), 'type')
                                ->orderBy('id', 'desc')
                                ->get();
        $results['documents'] = $documents;

        return Helper::responseJson($results);
    }

    public function requestFiles(Request $request, $corporate_id, $claim_id)
    {
       $claim_id = Crypt::decrypt($claim_id);
        if ($request->hasFile('fileDiagnosis')) {
            foreach ($request->fileDiagnosis as $file) {
                $pathFile = File::storeFile('claim-diagnosis', $claim_id, $file);
                File::updateOrCreate([
                    'fileable_type'=>'App\Models\ClaimRequest',
                    'fileable_id' => $claim_id,
                    'type' => 'claim-diagnosis',
                    'name' => File::getFileName('claim-diagnosis', $claim_id, $file),
                    'original_name' => $file->getClientOriginalName(),
                    'extension' => $file->getClientOriginalExtension(),
                    'path' => $pathFile,
                    'created_by' => auth()->user()->id,
                    'updated_by' => auth()->user()->id,
                ]);
            }
        }

        if ($request->hasFile('fileKondisis')) {
            foreach ($request->fileKondisis as $file) {
                $pathFile = File::storeFile('claim-kondisi', $claim_id, $file);
                File::updateOrCreate([
                    'fileable_type'=>'App\Models\ClaimRequest',
                    'fileable_id' => $claim_id,
                    'type' => 'claim-kondisi',
                    'name' => File::getFileName('claim-kondisi', $claim_id, $file),
                    'original_name' => $file->getClientOriginalName(),
                    'extension' => $file->getClientOriginalExtension(),
                    'path' => $pathFile,
                    'created_by' => auth()->user()->id,
                    'updated_by' => auth()->user()->id,
                ]);
            }
        }

        if ($request->hasFile('fileResults')) {
            foreach ($request->fileResults as $file) {
                $pathFile = File::storeFile('claim-result', $claim_id, $file);
                File::updateOrCreate([
                    'fileable_type'=>'App\Models\ClaimRequest',
                    'fileable_id' => $claim_id,
                    'type' => 'claim-result',
                    'name' => File::getFileName('claim-result', $claim_id, $file),
                    'original_name' => $file->getClientOriginalName(),
                    'extension' => $file->getClientOriginalExtension(),
                    'path' => $pathFile,
                    'created_by' => auth()->user()->id,
                    'updated_by' => auth()->user()->id,
                ]);
            }
        }

        return Helper::responseJson(data: $request->toArray(), message: 'Invoice Success Uploaded');
    }

    public function claimDetailHistory($corporate_id, $claimRequestId)
    {
        $claimRequestId = Crypt::decrypt($claimRequestId);

        $member = DB::table('claim_requests')
                    ->leftJoin('claims', 'claim_requests.id', '=', 'claims.claim_request_id')
                    ->leftJoin('members', 'claim_requests.member_id', '=', 'members.id')
                    ->leftJoin('corporate_employees', 'members.id', '=', 'corporate_employees.member_id')
                    ->leftJoin('corporate_divisions', 'corporate_employees.division_id', '=', 'corporate_divisions.id')
                    ->where('corporate_employees.corporate_id', '=', $corporate_id)
                    ->where('claim_requests.id', '=', $claimRequestId)
                    ->select(
                        'claim_requests.code','members.member_id', 'members.name'
                    )
                    ->first();
        $results['member'] = $member;
        $claim_item = DB::table('claim_items')
                        ->leftJoin('claims','claim_items.claim_id', '=', 'claims.id')
                        ->leftJoin('benefits', 'claim_items.claim_itemable_id', '=', 'benefits.id')
                        ->leftJoin('claim_requests', 'claims.claim_request_id', '=', 'claim_requests.id')
                        ->leftJoin('members', 'claim_requests.member_id', '=', 'members.id')
                        ->leftJoin('corporate_employees', 'members.id', '=', 'corporate_employees.member_id')
                        ->where('corporate_employees.corporate_id', '=', $corporate_id)
                        ->where('claim_requests.id', '=', $claimRequestId)
                        ->select(   
                            'claim_items.nominal_ditagihkan',
                            'claim_items.nominal_dicover',
                            'benefits.description',
                            'claim_requests.submission_date'
                        )
                        ->orderBy('claim_items.id', 'desc')
                        ->get();
        $results['claim_item'] = $claim_item;
        $tot_claim_item = DB::table('claim_items')
                        ->leftJoin('claims','claim_items.claim_id', '=', 'claims.id')
                        ->leftJoin('benefits', 'claim_items.claim_itemable_id', '=', 'benefits.id')
                        ->leftJoin('claim_requests', 'claims.claim_request_id', '=', 'claim_requests.id')
                        ->leftJoin('members', 'claim_requests.member_id', '=', 'members.id')
                        ->leftJoin('corporate_employees', 'members.id', '=', 'corporate_employees.member_id')
                        ->where('corporate_employees.corporate_id', '=', $corporate_id)
                        ->where('claim_requests.id', '=', $claimRequestId)
                        ->select( 
                            DB::raw('SUM(claim_items.nominal_ditagihkan) AS nominal_ditagihkan'),
                            DB::raw('SUM(claim_items.nominal_dicover) AS nominal_dicover'),
                            DB::raw('(SUM(claim_items.nominal_ditagihkan) - SUM(claim_items.nominal_dicover)) AS difference'),
                        )
                        ->groupBy('claim_items.id')
                        ->orderBy('claim_items.id', 'desc')
                        ->first();
        $results['tot_claim_item'] = $tot_claim_item;


        return Helper::responseJson($results);
    }

    public function show($corporateId, $claimRequestId)
    {
        $data = ClaimRequest::query()
            ->with([
                'histories:historiable_type,historiable_id,title,description,created_at',
                'member:id,person_id,name_prefix,name,name_suffix' => [
                    'person:id,name_prefix,name,name_suffix,gender'
                ],
                'claim:id,status',
                'claimResults',
                'claimConditions',
                'claimDiagnosis'
            ])
            ->find($claimRequestId, ['id', 'submission_date', 'member_id', 'claim_id', 'status']);

        return Helper::responseJson(new ShowResources($data));
    }
}
