<?php

namespace Modules\Internal\Http\Controllers\Api;

use App\Models\CorporateHospital;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\DB;
use App\Helpers\Helper;
use Maatwebsite\Excel\Facades\Excel;

class HospitalController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request, $corporate_id)
    {
        $datas = CorporateHospital::query()
            ->filter($request->all())
            ->where('corporate_id', $corporate_id)
            ->orderBy('id', 'DESC')
            ->paginate(0)
            ->appends($request->all());

        return $datas;
    }

    public function activation(Request $request, $hospital_id)
    {
        $request->validate([
            'active' => 'required',
            'reason' => 'required',
        ]);

        // abort(404);

        $hostpital = CorporateHospital::findOrFail($hospital_id);
        $hostpital->active = $request->active;
        $hostpital->reason = $request->reason;

        if ($hostpital->save()) {
            return response()->json([
                'hostpital' => $hostpital,
                'message' => 'Status Updated Successfully'
            ]);
        }
    }

    public function dataHospital(Request $request, $corporate_id)
    {
        $data = DB::table('organizations')
        ->where('type', 'hospital')
        ->where('status', 'active')
        ->orderBy('id', 'desc')
        ->get();
        return $data;
    }

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

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request, $corporate_id)
    {
        $request->validate([
            'corporate_id' => 'required',
            'code' => 'required',
            'name' => 'required',
            'organization_id' => 'required',
        ]);

        $newCorporateHospital = CorporateHospital::create([
            'corporate_id' => $corporate_id,
            'code' => $request->code,
            'name' => $request->name,
            'organization_id' => $request->organization_id,
            'description' => $request->description ? $request->description : null,
        ]);

        return $newCorporateHospital;
    }

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

    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit($corporate_id, $id)
    {
        $corporatePlan = CorporateDivision::findOrFail($id);

        return $corporatePlan;
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request, $corporate_id, $id)
    {
        $corporatePlan = CorporateHospital::findOrFail($id);
        $request->validate([
            'corporate_id' => 'required',
            'code' => 'required',
            'name' => 'required',
            'organization_id' => 'required',
        ]);

        $corporatePlan->fill([
            'corporate_id' => $corporate_id,
            'code' => $request->code,
            'name' => $request->name,
            'organization_id' => $request->organization_id,
            'description' => $request->description ? $request->description : null,
        ])->save();

        return $corporatePlan;
    }

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function destroy($id)
    {
        //
    }
    public function downloadTemplate() 
    {
        return Helper::responseJson([
            'file_name' => "Template - Hospitals.xlsx",
            "file_url" => url('files/Template - Hospitals.xlsx')
        ]);
    }

    public function import(Request $request, $corporate_id)
    {
        if ($request->hasFile('file')) {
            $file = $request->file('file');
            $data = Excel::toArray([], $file);

            $processedData = $this->processCategoryNames($data);

            $importedRows = 0;
            $failedRows = [];

            foreach ($processedData as $row) {
                $q_check =  DB::table('corporate_hospitals')
                ->where('code', '=', $row['code'])
                ->select('code')
                ->first();
                $q = DB::table('organizations')
                ->where('code', '=', $row['code'])
                ->where('type', '=', 'hospital')
                ->where('status', '=', 'active')
                ->select('id', 'code', 'name')
                ->first();
                try {
                    if($q_check)
                    {
                        DB::table('corporate_hospitals')
                        ->where('code','=', $q_check->code)
                        ->update(
                            [
                                'corporate_id' => $corporate_id,
                                'code' => $q->code,
                                'name' => $q->name,
                                'organization_id' => $q->id,
                                'description' => $request->description ? $request->description : null,
                                'updated_by' =>auth()->user()->id,
                                'updated_at' => date('Y-m-d H:i:s'),
                            ]
                        );
                    }
                    else
                    {
                        CorporateHospital::create(
                            [
                                'corporate_id' => $corporate_id,
                                'code' => $q->code,
                                'name' => $q->name,
                                'organization_id' => $q->id,
                                'description' => $request->description ? $request->description : null,
                            ]
                        );
                    }
                    $importedRows++;
                } catch (\Exception $e) {
                    $failedRows[] = $row;
                }
            }

            $response = [
                'message' => 'File uploaded and data saved to database',
                'data' => [
                    'total_success_row' => $importedRows,
                    'total_failed_row' => count($failedRows),
                    'failed_rows' => $failedRows,
                ],
            ];

            return response()->json($response);
        }

        return response()->json(['error' => 'No file uploaded.']);
    }

    private function processCategoryNames($data)
    {
        $header = [];
        $row = [];
        for ($i = 1; $i < count($data[0]); $i++) {
            $row[] = $data[0][$i];
            $header[] = $data[0][0];
        }
        
        $filed = [];
        foreach ($header[0] as $value)
        {
            $modelColumn = strtolower(preg_replace('/\s+/', '_', trim($value)));
            $modelColumn = str_replace(['*', ' '], '', $modelColumn);
            if($modelColumn)
            {
                $filed[] = $modelColumn;
            }
        }
        
        $result = [];
        foreach ($row as $subarray) {
            $trimmedSubarray = [];
            for ($i = 0; $i < count($filed); $i++) {
                $trimmedSubarray[$filed[$i]] = $subarray[$i] ? $subarray[$i] : null;
            }
        
            $result[] = $trimmedSubarray;
        }
        return $result;
    }  
}
