<?php

namespace Modules\Internal\Http\Controllers\Api;

use App\Models\Drug;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\Helpers\Helper;
use Maatwebsite\Excel\Facades\Excel;

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

    /**
     * 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)
    {
        //
    }

    /**
     * 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($id)
    {
        return view('internal::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 function activation(Request $request, $drug_id)
    {
        $request->validate([
            'active' => 'required',
            'reason' => 'required',
        ]);

        $drug = Drug::findOrFail($drug_id);
        $drug->active = $request->active;
        $drug->reason = $request->reason;

        if ($drug->save()) {
            return response()->json([
                'hostpital' => $drug,
                'message' => 'Status Updated Successfully'
            ]);
        }
    }
    public function downloadTemplate() 
    {
        return Helper::responseJson([
            'file_name' => "Template - Drugs.xlsx",
            "file_url" => url('files/Template - Drugs.xlsx')
        ]);
    }
    public function import(Request $request)
    {
        if ($request->hasFile('file')) {
            $file = $request->file('file');
            $data = Excel::toArray([], $file);

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

            $importedRows = 0;
            $failedRows = [];

            foreach ($processedData as $row) {
                try {
                    Drug::create(
                        [
                            'name' => $row['name'],
                            'code' => $row['code'],
                            'generic_name' => $row['generic_name'],
                            'description' => $row['description'],
                            'mims_class' => $row['mims_class'],
                            'indications' => $row['indications'],
                            'atc_code' => $row['atc_code'],
                            'segmentation' => $row['segmentation'],
                            'type' => $row['type'],
                            'dosage' => $row['dosage'],
                            'remark' => $row['remark'],
                        ]
                    );
                    $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;
    }    
}
