<?php

namespace Modules\Client\Http\Controllers\Api;

use App\Events\ClaimRequested;
use App\Helpers\Helper;
use App\Models\File;
use App\Models\Member;
use App\Models\ClaimRequest;
use App\Services\ClaimRequestService;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;

class ClaimRequestController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    private static $code_prefix = 'CP';
    public function index()
    {
        return view('client::index');
    }

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        return view('client::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request)
    {
        $request->validate([
            'member_id' => 'required|array',
            'member_id.*' => 'required',
            'service_code.*' => 'required|in:OP,IP'
        ]);
        if ($request->member_id){
            foreach($request->member_id as $key => $member_id){

                $code = $this->getNextCode();
                $member = Member::find($member_id);

                DB::beginTransaction();

                try {
                    $newClaimRequest = ClaimRequestService::storeClaimRequest(
                        row: [],
                        code: $code,
                        member: $member,
                        paymentType: 'reimbursement',
                        serviceCode: $request->service_code[$key],
                    );

                    // ClaimRequested::dispatch($newClaimRequest);

                     // Log History
                    $newClaimRequest->histories()->create([
                        'title' => 'New Claim Requested',
                        'description' => "Claim Requested for Member : {$member->member_id} - ({$member->full_name})",
                        'type' => 'info',
                        'system_origin' => 'client-portal'
                    ]);

                    // Claim Log
                    DB::table('claim_logs')
                    ->insert([
                        'claim_request_id' => $newClaimRequest->id,
                        'status' => 'requested',
                        'date' => date('Y-m-d H:i:s'),
                        'description' => "Claim Requested for Member : {$member->member_id} - ({$member->full_name})",
                        'system_origin' => 'hospital-portal',
                        'created_by' => auth()->user()->id,
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at'=> date('Y-m-d H:i:s'),
                    ]);

                    $storage_path = storage_path() . "/app/public";
                    $folder       = "claim/";

                    if (is_dir($storage_path . "/" . $folder) == false) {
                        mkdir($storage_path . "/" . $folder, 0770, true);
                    }

                    if (isset($_FILES['laboratorium'])) {
                        foreach ($_FILES['laboratorium']['error']["member_" .$member_id] as $key => $value) {
                            if ($value == 0) {
                                $new_file_name  = "claim-result-" . time() . "-" . uniqid();
                                $ekstension     =  "." . explode("/", $_FILES['laboratorium']['type']["member_" .$member_id][$key])[1];
                                $pathFile       = $folder . $new_file_name . $ekstension;

                                $tmp_name       = $_FILES['laboratorium']['tmp_name']["member_" .$member_id][$key];
                                $full_path      = $_FILES['laboratorium']['full_path']["member_" .$member_id][$key];

                                if (move_uploaded_file($tmp_name, $storage_path . "/" . $pathFile)) {
                                    $newClaimRequest->files()->updateOrCreate([
                                        'type'          => 'claim-result',
                                        'name'          => $new_file_name,
                                        'original_name' => $full_path,
                                        'extension'     => $ekstension,
                                        'path'          => $pathFile,
                                        'created_by'    => auth()->user()->id,
                                        'updated_by'    => auth()->user()->id,
                                    ]);
                                }
                            }
                        }
                    }

                    if (isset($_FILES['prescription'])) {
                        foreach ($_FILES['prescription']['error']["member_" .$member_id] as $key => $value) {
                            if ($value == 0) {
                                $new_file_name  = "claim-diagnosis-" . time() . "-" . uniqid();
                                $ekstension     =  "." . explode("/", $_FILES['prescription']['type']["member_" .$member_id][$key])[1];
                                $pathFile       = $folder . $new_file_name . $ekstension;

                                $tmp_name       = $_FILES['prescription']['tmp_name']["member_" .$member_id][$key];
                                $full_path      = $_FILES['prescription']['full_path']["member_" .$member_id][$key];

                                if (move_uploaded_file($tmp_name, $storage_path . "/" . $pathFile)) {
                                    $newClaimRequest->files()->updateOrCreate([
                                        'type'          => 'claim-diagnosis',
                                        'name'          => $new_file_name,
                                        'original_name' => $full_path,
                                        'extension'     => $ekstension,
                                        'path'          => $pathFile,
                                        'created_by'    => auth()->user()->id,
                                        'updated_by'    => auth()->user()->id,
                                    ]);
                                }
                            }
                        }
                    }

                    if (isset($_FILES['invoice'])) {
                        foreach ($_FILES['invoice']['error']["member_" .$member_id] as $key => $value) {
                            if ($value == 0) {
                                $new_file_name  = "claim-kondisi-" . time() . "-" . uniqid();
                                $ekstension     =  "." . explode("/", $_FILES['invoice']['type']["member_" .$member_id][$key])[1];
                                $pathFile       = $folder . $new_file_name . $ekstension;

                                $tmp_name       = $_FILES['invoice']['tmp_name']["member_" .$member_id][$key];
                                $full_path      = $_FILES['invoice']['full_path']["member_" .$member_id][$key];

                                if (move_uploaded_file($tmp_name, $storage_path . "/" . $pathFile)) {
                                    $newClaimRequest->files()->updateOrCreate([
                                        'type'          => 'claim-kondisi',
                                        'name'          => $new_file_name,
                                        'original_name' => $full_path,
                                        'extension'     => $ekstension,
                                        'path'          => $pathFile,
                                        'created_by'    => auth()->user()->id,
                                        'updated_by'    => auth()->user()->id,
                                    ]);
                                }
                            }
                        }
                    }

                    DB::commit();
                }
                catch (\Throwable $th) {
                    DB::rollBack();

                    return Helper::responseJson(status: 'failed', statusCode: 500, message: $th->getMessage());
                }
            }
        }

        return Helper::responseJson(data: $request->toArray(), message: 'Claim Request berhasil ajukan!');
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show($id)
    {
        return view('client::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit($id)
    {
        return view('client::edit');
    }

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

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function destroy($id)
    {
        //
    }

    public static function getNextCode()
    {
        // $last_number = ClaimRequest::max('code');
        // $next_number = empty($last_number) ? 1 : ((int) explode('-', $last_number)[2] + 1);
        // return self::makeCode($next_number);

        $last_numeric_code = ClaimRequest::select(DB::raw('MAX(CAST(SUBSTRING_INDEX(code, "-", -1) AS SIGNED)) as max_numeric_code'))
                                    ->whereRaw('SUBSTRING_INDEX(code, "-", -1) REGEXP "^[0-9]+$"')
                                    ->value('max_numeric_code');
        // $next_number = 1;
        if ($last_numeric_code) {
        //     // Jika ada kode sebelumnya, pecah kode dan tambahkan 1 ke angka terakhir
        //     $parts = explode('-', $last_code);
        //     $last_number = (int) end($parts);
            $next_number = $last_numeric_code + 1;
        }

        return self::makeCode($next_number);
    }


    public static function makeCode($next_number)
    {
        // Pastikan $next_number adalah integer positif
        $next_number = max(1, (int) $next_number);

        // Menghasilkan kode dengan format yang diinginkan
        return self::$code_prefix . '-' . str_pad($next_number, 5, '0', STR_PAD_LEFT);
    }
}
