<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PersonalDetail;
use App\Models\PersonalDocument;
use Storage;
use DB;
use File;
use Exception; // Import the Exception class at the top of your file
class PersonalDetailController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $data['personaldetail']=PersonalDetail::get();
        return view('persoanldetail.index',$data);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $data['document'] =DB::table('document_type')->get();
        return view('persoanldetail.create',$data);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        // try {
            $personal = new PersonalDetail();
            $personal->first_name = $request->first_name;
            $personal->middle_name = $request->middle_name;
            $personal->last_name = $request->last_name;
            $personal->date_of_birth = $request->date_of_birth;
            $personal->gender = $request->gender;
            $personal->email = $request->email;
            $personal->mobile_no = $request->mobile_no;
            $personal->aadhaar_no = $request->aadhaar_no;
            $personal->address = $request->address;
            $personal->retirement_date = $request->retirement_date;
          
             if(isset($request->image)){
                $img = $request->image;
                $image_parts = explode(";base64,", $img);
                $image_type_aux = explode("image/", $image_parts[0]);
                $image_type = $image_type_aux[1];
                $image_base64 = base64_decode($image_parts[1]);
                $fileName = uniqid() . '.png';
        
                $publicPath = public_path();
                $folderPath = $publicPath . "/uploads/documents/";
                if (!file_exists($folderPath)) {
                    mkdir($folderPath, 0755, true);
                }
                $filePath = $folderPath . $fileName;
                file_put_contents($filePath, $image_base64);
                $personal->live_photo = $fileName;
             }
             $personal->save();
        
            
         /** --- document--  **/
            $names  = request('document_type');
            $images = request()->file('document_path');    
            foreach($names as $i => $code) {
                if(isset($images[$i])) {
                    if($request->hasFile('document_path') && isset($images[$i])) {
                            $img_name =$images[$i]->getClientOriginalName();
                            $images[$i]->move('uploads/documents/',$img_name);
                            $candidatedocument = new PersonalDocument([
                            'document_path' => "{$img_name}",
                            'document_type' => $names[$i],
                            'personal_detail_id'=> $personal->id,
                            'date_submited'=> Date('Y-m-d'),
                        ]);
                        $candidatedocument->save();
                    }
                }
            }
          /** --- document--  **/

            return to_route('personaldetail.index')->withSuccess('User Created Successfully');
           

        // } catch (Exception $e) {
        //     // Handle the exception, e.g., log it or return an error response
        //     return response()->json(['error' => 'Unable to save personal detail data'], 500);
        // }
        
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
     $data['personal'] =DB::table('personal_detail')->where('id',$id)->first();
       return view('persoanldetail.show',$data);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $personaldetail = PersonalDetail::find($id);
        $data['document_type'] =DB::table('document_type')->get();
        $data['personal_document'] = DB::table('personal_documents')->where('personal_detail_id',$id)->get();

        return view('persoanldetail.edit',compact('personaldetail'),$data);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
      try {
            $personal=PersonalDetail::find($id);
            $personal->first_name = $request->first_name;
            $personal->middle_name = $request->middle_name;
            $personal->last_name = $request->last_name;
            $personal->date_of_birth = $request->date_of_birth;
            $personal->gender = $request->gender;
            $personal->email = $request->email;
            $personal->mobile_no = $request->mobile_no;
            $personal->aadhaar_no = $request->aadhaar_no;
            $personal->address = $request->address;
            $personal->retirement_date = $request->retirement_date;
            
                 if(isset($request->image)){
                    $img = $request->image;
                    $image_parts = explode(";base64,", $img);
                    $image_type_aux = explode("image/", $image_parts[0]);
                    $image_type = $image_type_aux[1];
                    $image_base64 = base64_decode($image_parts[1]);
                    $fileName = uniqid() . '.png';
                     $folderPath = public_path('uploads/documents/');
                     $filePath = $folderPath . $fileName;
                     file_put_contents($filePath, $image_base64);
                    
                    $filename = public_path('uploads/documents/'.$personal->live_photo); //unlink
                     if (File::exists($filename)){       
                       unlink($filename);
                    }
                    $personal->live_photo = $fileName;
                 }
                 $personal->save();
                 
                 $images = request()->file('document_path');    
                 $names  = request('document_type');
                if(isset($request->document_id)){
                      foreach ($request->document_id as  $index => $value) {
                         if($value!=''){
                               if(isset($images[$index])) {
                                   if($request->hasFile('document_path') && isset($images[$index])){
                                       
                                     //unlink img
                                        $file=  DB::table('personal_documents')->where('document_id',$value)->first();
                                        $filename=public_path('uploads/documents/'.$file->document_path);
                                          if(!empty($file)){
                                               if (File::exists($filename)) {       
                                                   unlink($filename);
                                            }
                                          }
                                      //unlink img
                                       $img_name = $images[$index]->getClientOriginalName();
                                       $images[$index]->move('uploads/documents/',$img_name);
                                       $documentUpdate=array(
                                               'document_path' => "{$img_name}",
                                               'document_type' => $names[$index],
                                               'date_updated'=> strtotime(Date('Y-m-d')),
                                            );
                                        $document=PersonalDocument::where('document_id',$value)->first();
                                        $document->update($documentUpdate);
                                    }
                                }
                          }else{
                             if(isset($images[$index])) {
                                   if($request->hasFile('document_path') && isset($images[$index])) {
                                        $img_name = $images[$index]->getClientOriginalName();
                                        $images[$index]->move('uploads/documents/',$img_name);
                                        $personaldocument = new PersonalDocument([
                                           'document_path' => "{$img_name}",
                                           'document_type' => $names[$index],
                                           'personal_detail_id'=> $personal->id,
                                           'date_submited'=> strtotime(Date('Y-m-d')),
                                            ]);
                                        $personaldocument->save();
                                  }
                                }
                            }
                    }///end of for
                }
            return to_route('personaldetail.index')->withSuccess('User Updated Successfully');
            
        } catch (Exception $e) {
            return response()->json(['error' => 'Unable to save personal detail data'], 500);
        }
 
 
 
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $personal=DB::table('personal_detail')->where('id',$id)->first();
        $personal_doc=DB::table('personal_documents')->where('personal_detail_id',$personal->id)->delete();
        $personalD=DB::table('personal')->where('id',$id)->delete();
    }
    
     public function RejectApplication(Request $request ,$id)
    {
       $record = PersonalDetail::find($id);
       $record->reject_reason = $request->reject_reason;
       $record->save();
       
       return redirect()->back()->with('success','Reason Updated Successfully');

    }
}
