<?php

namespace App\Http\Controllers\Admin;

use ZipArchive;
use Illuminate\Http\Request;
use App\Models\MedicineListModel;
use Illuminate\Support\Facades\DB;
use App\Imports\MedicineListImport;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Requests\admin\UpdateMedicineFormRequest;

class MedcineListController extends Controller
{

    public function view()
    {

        return view('admin.medicine.addmedicinecsv');
    }

    // public function store(Request $request)
    // {
    //     $user = auth()->user();
    //     $request->validate([
    //         'file' => 'required|mimes:csv,txt|max:2048'
    //     ]);
    //     $file = $request->file('file');
    //     // return $file;
    //     // Get the file contents as an array of rows
    //     $rows = array_map('str_getcsv', file($file));

    //     // Get the header row and remove it from the data array
    //     $header = array_shift($rows);

    //     // DB::table('tbl_product')->delete();

    //     // return $header;
    //     // Loop through the rows and create a new record for each
    //     foreach ($rows as $row) {
    //         $data = array_combine($header, $row);
    //         $data['created_by'] = $user->id;
    //         // Save the data to the database
    //         // return $data;
    //         DB::table('tbl_product')->updateOrInsert(
    //             ['product_id' => $data['product_id']],
    //             $data
    //         );
    //     }

    //     // Excel::import(new MedicineListImport, $request->file);
    //     return redirect('admin/view-medicine')->with('status', 'Medicine List added successfully');
    // }




    public function store(Request $request)
    {
        $user = auth()->user();
        $extraColumns=[];
        //for initial csv upload
        $requiredColumns = [
            'product_id', 'image', 'title', 'type', 'days','daily_dose',
            'piese_per_dose', 'instruction', 'stock_status', 'price','delete_flag'
        ];  
        //when we reupload the csv
        $requiredColumns2 = [
            'product_id', 'image', 'title', 'type', 'days','daily_dose',
            'piese_per_dose', 'instruction', 'stock_status', 'price','updated_at','delete_flag'
        ];  
        //product_id,image,title,type,daily_dose,piese_per_dose,instruction,stock_status,price,updated_at,delete_flag
        //product_id,image,title,type,days,daily_dose,piese_per_dose,instruction,stock_status,price,updated_at,delete_flag

        $request->validate([
            'csv_file' => 'required|mimes:csv,txt|max:5128'
        ]);
        $file = $request->file('csv_file');
        // return $file;
        // Get the file contents as an array of rows
        $rows = array_map('str_getcsv', file($file));
        // Get the header row and remove it from the data array
        $header = array_shift($rows);
        // Loop through the rows and create a new record for each
        foreach ($rows as $row) {
            if (count($row) == count($header)) {
                // For this error => array_combine(): Argument #1 ($keys) and argument #2 ($values) must have the same number of elements
                $data = array_combine($header, $row);
            }
            else{
                return redirect('admin/add-medicine')->with('status',  "Something missing in the csv or wrong data.");

            }
            
            //without update
            $extraColumns = array_diff(array_keys($data), $requiredColumns);
            $missingColumns = array_diff($requiredColumns, array_keys($data)); 
            //with update
            $extraWithUpdate= array_diff(array_keys($data), $requiredColumns2);
            $missingWithUpdate = array_diff($requiredColumns2, array_keys($data));

            $data['created_by'] = $user->id; 
           

            // return $data;
            //Check if csv is valid
            if ((empty($missingColumns) && empty($extraColumns)) || (empty($missingWithUpdate) && empty($extraWithUpdate))) {
                // Save the data to the database
                if (in_array('', $row, true)) {
                    return redirect('admin/add-medicine')->with('status', "Data is missing in the CSV row.");
                }else{
                    DB::table('tbl_product')->updateOrInsert(
                    [
                        'created_by' => $data['created_by'],
                        'product_id' => $data['product_id']
                    ],
                    $data
                );
                }

            } else {
                // return redirect('admin/add-medicine')->with('status', 'Failed to add Medicine to Medicine List');
                // return redirect('admin/add-medicine')->with('status', "__('customerSection')");
                return redirect('admin/add-medicine')->with('status',  __("unmatchedCSV"));
            }
        }
        return redirect('admin/view-medicine')->with('status', __("MedicineListAdded"));
    }


    public function batch_image_upload(Request $request)
    {

        $request->validate([
            'image_zip' => 'required|mimes:zip|max:5128',
        ]);

        $a_user_id = Auth::User();

        $zipFile = $request->file('image_zip');
        $tempExtractPath = storage_path('app/temp_extracted');
        // $targetDirectory = public_path('../../uploads/shop_'.$a_user_id->id.'/medicines'); // enable it for Live server
        $targetDirectory = public_path('uploads/shop_' . $a_user_id->id . '/medicines'); // enable it for local server

        // Create the target directory if it doesn't exist
        if (!File::isDirectory($targetDirectory)) {
            File::makeDirectory($targetDirectory, 0755, true);
        }
        $zip = new ZipArchive;
        $duplicate= true;
        $noImage= true;
        if ($zip->open($zipFile->getPathname()) === TRUE) {
            for ($i = 0; $i < $zip->numFiles; $i++) {
                $entryName = $zip->getNameIndex($i);
                $entryInfo = pathinfo($entryName);
                $extension = isset($entryInfo['extension']) ? strtolower($entryInfo['extension']) : '';
                $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif']; // Allowed image extensions
    
                if ($extension && in_array($extension, $allowedExtensions)) {
                    // Check if the entry is a valid image
                    if (!preg_match('/(^|\/)\._/', $entryName)) {
                        $imageFileName = basename($entryName);

                        $extractedFilePath = $targetDirectory . '/' . $imageFileName;
    
                        // Check if the image already exists, and if so, skip saving
                        if (!file_exists($extractedFilePath)) {
                            // Extract and save the image to the target directory
                            $imageContent = $zip->getFromIndex($i);
                            file_put_contents($extractedFilePath, $imageContent);
                            $duplicate=false;
                        }
                        
                        $noImage= false;
                    }
                    
                }
            }
            $zip->close();
            if($duplicate&&!$noImage){
                return redirect('admin/view-medicine')->with('status', 'Successfully added image and skipped duplicate images.');
            }
            else if($noImage){
                return redirect('admin/add-medicine')->with('status', 'No image found!');
            }
        } else {
            return redirect('admin/add-medicine')->with('status', 'Failed to add Medicine to Medicine List !!');
        }
        // Clean up the temporary extracted directory
        File::delete($zipFile->getPathname());
        // File::deleteDirectory($tempExtractPath);
        return redirect('admin/view-medicine')->with('status', 'Successfully added image.');
    }


    public function downloadMedicineList()
    {
        // Get the data from the 'medicine_list' table
        // $medicine_list = DB::table('tbl_product')->get();
        $a_user_id = Auth::User();
        // $medicine_list = MedicineListModel::where('delete_flag', 1)->where('created_by', $a_user_id->id)->get();
        $medicine_list = MedicineListModel::where('created_by', $a_user_id->id)->get();

        if ($medicine_list->isEmpty()) {
            return back()->with('error', 'No data available for download.');
        }

        // Set the file name for the downloaded CSV file
        // Generate a unique filename with the current timestamp
        $file_name = 'medicine_list_' . time() . '.csv';

        // Set the response headers for the download
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $file_name . '"',
        ];
        // Old--
        // $callback = function () use ($medicine_list) {
        //     $file = fopen('php://output', 'w');
        //     // fputcsv($file, ['id', 'product_id','image', 'title', 'type', 'daily_dose', 'piese_per_dose', 'instruction', 'stock_status', 'price', 'created_at','updated_at','created_by','delete_flag']);
        //     fputcsv($file, ['id', 'product_id','image', 'title', 'type', 'daily_dose', 'piese_per_dose', 'instruction', 'stock_status', 'price', 'created_at','updated_at','delete_flag']);
        //     foreach ($medicine_list as $row) {

        //         fputcsv($file, (array) $row);
        //     }
        //     fclose($file);
        // };

        //New--
        $callback = function () use ($medicine_list) {
            $file = fopen('php://output', 'w');

            // Specify the columns you want to include in the CSV
            $columnsToInclude = [
                'product_id', 'image', 'title', 'type', 'days', 'daily_dose',
                'piese_per_dose', 'instruction', 'stock_status', 'price',
                'updated_at', 'delete_flag',
            ];

            fputcsv($file, $columnsToInclude);

            foreach ($medicine_list as $row) {
                // Loop through each row and include only the selected columns
                $data = [];
                foreach ($columnsToInclude as $column) {
                    $data[] = $row->$column;
                }

                fputcsv($file, $data);
            }

            fclose($file);
        };

        // Create a download response with the CSV string and headers
        return response()->stream($callback, 200, $headers);
    }



    public function view_medicine_list()
    {
        // $medicineListModel = MedicineListModel::all();
        $a_user_id = Auth::User();
        $medicineListModel = MedicineListModel::where('delete_flag', 1)->where('created_by', $a_user_id->id)->get();
        return view('admin.medicine.viewmedicinecsv', compact('medicineListModel', 'a_user_id'));
    }

    public function destroy($medicine_id)
    {

        // $Medicine_id = MedicineListModel::find($medicine_id);
        // if ($Medicine_id) {
        //     $Medicine_id->delete();
        //     return redirect('admin/view-medicine')->with('status', 'Country Code Deleted Successfully');
        // } else {
        //     return redirect('admin/view-medicine')->with('status', 'Id Not Found');
        // }

        $medicine = MedicineListModel::find($medicine_id);
        if ($medicine) {
            // Set the delete_flag column value to 0
            $medicine->delete_flag = 0;
            $medicine->save();
            return redirect('admin/view-medicine')->with('status', 'Medicine Record Restored Successfully');
        } else {
            return redirect('admin/view-medicine')->with('status', 'Medicine Record Not Found');
        }
    }

    public function edit($medicine_id)
    {
        // return 'This is Dashboard';
        $Medicine_id = MedicineListModel::find($medicine_id);
        return view('admin.medicine.editmedicinecsv', compact('Medicine_id'));
    }

    public function update(UpdateMedicineFormRequest $request, $medicine_id)
    {

        $data = $request->validated();

        $Medicine_id = MedicineListModel::find($medicine_id);

        $Medicine_id->title = $data['title'];
        $Medicine_id->price = $data['price'];
        $Medicine_id->type = $data['type'];
        $Medicine_id->discount = $data['discount'];
        $Medicine_id->stock_status = $data['stock_status'];
        $Medicine_id->description = $data['description'];

        if ($request->hasfile('image')) {
            $destination = 'uploads/medicins/' . $Medicine_id->image;
            if (File::exists($destination)) {
                File::delete($destination);
            }

            $file = $request->file('image');
            $filename = time() . '.' . $file->getClientOriginalExtension();
            $file->move('uploads/medicins/', $filename);
            $Medicine_id->image = 'uploads/medicins/' . $filename;
        }

        //$Medicine_id->created_by = 0;
        $Medicine_id->update();

        return redirect('admin/view-medicine')->with('status', 'Medicine updated successfully');
    }
}
