<?php

namespace App\Http\Controllers;

use App\Models\Reimbursement;
use Illuminate\Http\Request;
use App\Models\UserProfile;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;

class ReimbursementController extends Controller
{
    public function __construct()
    {
        $this->middleware('checkStaff');
    }

    public function create_reimb(Request $request, $id)
    {

        try {

	    $loggedInUser = Auth::user();

        if ($loggedInUser->id != $id) {
            return response()->json(['message' => 'Unauthorized access'], 403); 
        }
            $user = UserProfile::find($id);

            $validatedData = $request->validate([
                'jenis' => 'required',
                'desc' => 'required',
                'bukti' => 'nullable|file',
                'nominal' => 'required',
            ]);

            // $validatedData['bukti'] = $this->uploadFile($request->file('bukti'), 'izin')->nullable();
            $validatedData['bukti'] = $request->file('bukti') ? $this->uploadFile($request->file('bukti'), 'izin') : null;

            $validatedData['id_pemohon'] = $user->id;
            $validatedData['nama_pemohon'] = $user->name;

            $validatedData['status'] = 'pending';
            $vldIz = Reimbursement::create($validatedData);

            return response()->json(['message' => 'izin created succes', 'izin' => $vldIz], 201);

        } catch (\Throwable $th) {
            return response()->json(['message' => 'error to create', 'error' => $th->getMessage()], 500);
        }
    }

    public function update_reimb(Request $request, $id)
    {
        try {

            $reim = Reimbursement::findOrFail($id);
            if($request->hasFile('bukti')) {
                $this->deleteFile(public_path('storage/images/reimburs/'. basename($reim->bukti)));
                $reim['bukti'] = $this->uploadFile($request->file('bukti'), 'bukti-r');
            }

            $reim->update($request->except('status'));

            if ($request->hasFile('bukti')) {
                $reim->update(['bukti' => $reim['bukti']]);
            }

            // $izin->update($request->all());
            return response()->json(['message' => 'reimbursement status updated succes', 'reimbus' => $reim], 200);
        } catch (\Throwable $th) {
            return response()->json(['message' => 'error to update', 'error' => $th->getMessage()], 500);
        }
    }
    public function update_reimb_adm(Request $request, $id)
    {
        try {
            $izin = Reimbursement::findOrFail($id);

            // if ($request->hasFile('bukti')) {
                
            //     $this->deleteFile(public_path('storage/images/reimburs/'. basename($izin->bukti)));
               
            //     $validatedData['bukti'] = $this->uploadFile($request->file('bukti'), 'bukti-r');
            // }
          
            // $izin->update($request->all()); 
            $izin->update($request->except('bukti')); 

            
            // if (isset($validatedData['bukti'])) {
            //     $izin->update(['bukti' => $validatedData['bukti']]);
            // }

            return response()->json(['message' => 'izin updated succes', 'izin' => $izin], 200);
        } catch (\Throwable $th) {
            return response()->json(['message' => 'error to update', 'error' => $th->getMessage()], 500);
        }
    }
    
    public function delete_reimb($id)
    {
        try {
            $izin = Reimbursement::findOrFail($id);
            $this->deleteFile(public_path('storage/images/reimburs/'. basename($izin->bukti)));
            $izin->delete();
            return response()->json(['message' => 'reimbust deleted succes'], 200);
        } catch (\Throwable $th) {
            return response()->json(['message' => 'error to delete', 'error' => $th->getMessage()], 500);
        }
    }

    public function get_all_reimb()
    {
        $user = Auth::user();
        if ($user && in_array($user->user_type_id, [1, 2, 3, 4])) {
            try {
                $izin = Reimbursement::all();
                return response()->json(['message' => 'uccess', 'reimb' => $izin], 200);
            } catch (\Throwable $th) {
                return response()->json(['message' => 'error', 'error' => $th->getMessage()], 500);
            }
        } else {
            return response()->json(['message' => 'Unauthorized'], 401);
        }
    }

    public function get_reimb_byid($id_pemohon)
    {
        try {
            $izin = Reimbursement::where('id_pemohon', $id_pemohon)->get();
            return response()->json(['message' => 'success', 'reimbur' => $izin], 200);
        } catch (\Throwable $th) {
            return response()->json(['message' => 'error', 'error' => $th->getMessage()], 500);
        }
    }

    private function uploadFile($file, $type){
        $file_name = time() . $type . '.' . $file->getClientOriginalExtension();
        $file->move(public_path('storage/images/reimburs/'), $file_name);
        return Storage::url('images/reimburs/' . $file_name);
    }

    private function deleteFile($path){
        if(File::exists($path)){
            File::delete($path);
        }
    }
}
