<?php

namespace App\Http\Controllers;

use App\Mail\TestMail;
use App\Models\Barcode;
use App\Models\Level;
use App\Models\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

class BarcodeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // initialize variables
        $response = [];
        $flag = false;
        $message = "";
        $records = [];
        $check = "";
        $check_flag = false;

        // fetch auth user details
        $level = auth()->user()->level;
        $auth_level_name = $level?->name;

        $query = Barcode::with([
            'created_user:id,full_name,role_id,level_id',
            'created_user.role:id,name',
            'created_user.level:id,name',
        ]);
        if ($auth_level_name != 'Level I') {
            $query->where('status', '!=', 'Drafted');
        }
        $records = $query->orderBy('created_at', 'desc')->get();

        $count = count($records);
        $flag =  $count > 0 ? true : false;
        $message = $count . ' records found.';

        $check .= "records = " . json_encode($records) . "<br> count = {$count} <br> message = {$message}";

        // prepare response
        $response = [
            'flag' => $flag,
            'message' => $message,
            'records' => $records,
            'check' => $check_flag ? $check : '',
            'check_flag' => $check_flag,
        ];
        // return response
        return view('barcode-list', $response);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('barcode-create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // initialize variables
        $response = [];
        $flag = false;
        $message = "";
        $records = [];
        $check = "";
        $check_flag = true;

        $insert_id = 0;

        // fetch auth user details
        $auth_id = auth()->user()->id;
        $level = auth()->user()->level;
        $auth_level_code = $level?->code;

        // validate requested data
        $request->validate([
            'code' => 'required|unique:barcode,code||max:50',
            'brand_name' => 'required|max:255',
            'product_name' => 'required|max:255',
            'category_id' => 'required|exists:category,id',
            'subcategory_id' => 'required|exists:subcategory,id',
            'product_description' => 'required|max:255',
            'marketing_information' => 'required|max:255',
            'product_image' => 'required|image|mimes:jpg,jpeg,png|max:500',
            'art_work_image' => 'required|image|mimes:jpg,jpeg,png|max:500',
            'net_content_unit' => 'required|max:50',
            'mass_unit' => 'required|max:50',
            'net_weight' => 'required|numeric|gt:0|digits_between:1,10',
            'net_content' => 'required|numeric|gt:0|digits_between:1,10',
            'gross_weight' => 'required|numeric|gt:0|digits_between:1,10',
            'mrp_activation_date' => 'required|date',
            'location' => 'required|max:50',
            'mrp' => 'required|numeric|gt:0|digits_between:1,10',
            'hsn' => 'required|numeric|gt:0|digits_between:1,8',
            'gst' => 'required|max:255',
            'fssai_no' => 'required|max:255',
            'food_type' => 'required|max:255',
            'shelf_life_value' => 'required|numeric|gt:0|digits_between:1,10',
            'shelf_life_unit' => 'required|max:50',
            'shelf_life_based_on' => 'required|max:255',
            'status' => 'required|in:Drafted,Applied',
        ]);
        // ], ['status.in' => 'Status must be Active or Inactive only.',]);

        // store product image in public folder
        $productImage = $request->file('product_image');
        $productImageName = time() . '_product_' . uniqid() . '.' . $productImage->getClientOriginalExtension();
        $productImage->move(public_path('barcode/product'), $productImageName);
        $product_image_path = 'barcode/product/' . $productImageName;

        // store art_work image in public folder
        $artWorkImage = $request->file('art_work_image');
        $artWorkImageName = time() . '_artwork_' . uniqid() . '.' . $artWorkImage->getClientOriginalExtension();
        $artWorkImage->move(public_path('barcode/art_work'), $artWorkImageName);
        $art_work_image_path = 'barcode/art_work/' . $artWorkImageName;

        $check .= "product_image_path = $product_image_path , art_work_image_path = $art_work_image_path";

        try {

            DB::beginTransaction();

            // insert all requested data into db
            $insert_id = Barcode::create([
                'code' => $request->code,
                'brand_name' => $request->brand_name,
                'product_name' => $request->product_name,
                'category_id' => $request->category_id,
                'subcategory_id' => $request->subcategory_id,
                'product_description' => $request->product_description,
                'marketing_information' => $request->marketing_information,
                'product_image' => $product_image_path,
                'art_work_image' => $art_work_image_path,
                'net_content_unit' => $request->net_content_unit,
                'mass_unit' => $request->mass_unit,
                'net_weight' => $request->net_weight,
                'net_content' => $request->net_content,
                'gross_weight' => $request->gross_weight,
                'mrp_activation_date' => $request->mrp_activation_date,
                'location' => $request->location,
                'mrp' => $request->mrp,
                'hsn' => $request->hsn,
                'gst' => $request->gst,
                'fssai_no' => $request->fssai_no,
                'food_type' => $request->food_type,
                'shelf_life_value' => $request->shelf_life_value,
                'shelf_life_unit' => $request->shelf_life_unit,
                'shelf_life_based_on' => $request->shelf_life_based_on,
                'status' => $request->status,
                'created_by' => $auth_id,
                'created_at' => now(),
            ])->id;
            // $check .= "<br> insert_id = $insert_id";

        } catch (\Exception $e) {
            DB::rollBack();
            $message = $e->getMessage();
        }

        if ($insert_id > 0) {
            DB::commit();

            if ($request->status == 'Applied') {
                $next_level_code = $auth_level_code + 1;

                $next_level_mail_ids = Users::join('level', 'users.level_id', '=', 'level.id')
                    ->where('level.code', $next_level_code)
                    ->whereNotNull('users.email')
                    ->pluck('users.email');

                $details = [
                    // 'from' => $auth_user_email ?? config('mail.from.address'),
                    'subject' => 'Barcode Creation Form Code - ' . $request->code,
                    'code' => $request->code,
                    'brand_name' => $request->brand_name,
                    'product_name' => $request->product_name,
                    'status' => $request->status,
                ];
                try {
                    if ($next_level_mail_ids->isNotEmpty()) {
                        foreach ($next_level_mail_ids as $mail_id) {
                            Mail::to($mail_id)->send(new TestMail($details));
                        }

                        $flag = true;
                        $message = 'Barcode creation form saved. Mail sent successfully.';
                    } else {
                        $flag = true;
                        $message = 'Barcode creation form saved. No next-level email found.';
                    }
                } catch (\Exception $e) {
                    $message = $e->getMessage();
                }
            } else {
                $flag = true;
                $message = 'Barcode creation form saved';
            }
        }

        // assign response
        $response = [
            'flag' => $flag,
            'message' => $message,
            'records' => $records,
            'check_flag' => $check_flag,
            'check' => $check_flag ? $check : '',
        ];

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

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Barcode  $barcode
     * @return \Illuminate\Http\Response
     */
    public function show(Barcode $barcode, int $id)
    {
        $response = [];
        $flag = false;
        $message = '';
        $records = [];
        $check = '';
        $check_flag = false;

        $check .= "id = $id, ";
        $records = Barcode::with(['category', 'subcategory'])->where('id', $id)->first();

        if (!$records) {
            $message = 'Barcode Creation details not found.';
        } else {
            $records = [
                'brand_name' => $records->brand_name,
                'product_name' => $records->product_name,
                'category' => $records->category ?? '',
                'subcategory' => $records->subcategory ?? '',
                'marketing_information' => $records->marketing_information,
                'product_description' => $records->product_description,
                'net_content_unit' => $records->net_content_unit,
                'mass_unit' => $records->mass_unit,
                'net_weight' => $records->net_weight,
                'net_content' => $records->net_content,
                'gross_weight' => $records->gross_weight,
                'mrp_activation_date' => $records->mrp_activation_date,
                'location' => $records->location,
                'mrp' => $records->mrp,
                'hsn' => $records->hsn,
                'gst' => $records->gst,
                'fssai_no' => $records->fssai_no,
                'food_type' => $records->food_type,
                'shelf_life_value' => $records->shelf_life_value,
                'shelf_life_unit' => $records->shelf_life_unit,
                'shelf_life_based_on' => $records->shelf_life_based_on,
                'status' => $records->status,
                'product_image_url' => $records->product_image ? asset($records->product_image) : '',
                'art_work_image_url' => $records->art_work_image ? asset($records->art_work_image) : '',
            ];

            $flag = true;
            $message = 'Barcode Creation details found.';
        }

        $response = [
            'flag' => $flag,
            'message' => $message,
            'records' => $records,
            'check_flag' => $check_flag,
            'check' => $check_flag ? $check : '',
        ];

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Barcode  $barcode
     * @return \Illuminate\Http\Response
     */
    public function edit(Barcode $barcode, int $id)
    {
        $response = [];
        $flag = false;
        $message = '';
        $records = [];
        $check = '';
        $check_flag = false;

        $check .= "id = $id, ";
        $records = Barcode::where('id', $id)->first();
        $check .= "category_id = $records->category_id, subcategory_id = $records->subcategory_id";

        if (!$records) {
            $message = 'Barcode Creation details not found.';
        } else {
            $flag = true;
            $message = 'Barcode Creation details found.';
        }

        $response = [
            'flag' => $flag,
            'message' => $message,
            'records' => $records,
            'check_flag' => $check_flag,
            'check' => $check_flag ? $check : '',
        ];

        return view('barcode-edit', $response);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Barcode  $barcode
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Barcode $barcode)
    {
        $response = [];
        $flag = false;
        $message = '';
        $records = [];
        $check = '';
        $check_flag = false;

        $updated = false;

        // fetch auth user details
        $auth_id = auth()->user()->id;
        $level = auth()->user()->level;
        $auth_level_code = $level?->code;

        $barcode_id = $request->id;

        $request->validate([
            'id' => 'required|exists:barcode,id',
            'code' => 'required|max:50|unique:barcode,code,' . $barcode_id,
            'brand_name' => 'required|max:255',
            'product_name' => 'required|max:255',
            'category_id' => 'required|exists:category,id',
            'subcategory_id' => 'required|exists:subcategory,id',
            'product_description' => 'required|max:255',
            'marketing_information' => 'required|max:255',
            'product_image' => 'nullable|image|mimes:jpg,jpeg,png|max:500',
            'art_work_image' => 'nullable|image|mimes:jpg,jpeg,png|max:500',
            'net_content_unit' => 'required|max:50',
            'mass_unit' => 'required|max:50',
            'net_weight' => 'required|numeric|gt:0|digits_between:1,10',
            'net_content' => 'required|numeric|gt:0|digits_between:1,10',
            'gross_weight' => 'required|numeric|gt:0|digits_between:1,10',
            'mrp_activation_date' => 'required|date',
            'location' => 'required|max:50',
            'mrp' => 'required|numeric|gt:0|digits_between:1,10',
            'hsn' => 'required|numeric|gt:0|digits_between:1,8',
            'gst' => 'required|max:255',
            'fssai_no' => 'required|max:255',
            'food_type' => 'required|max:255',
            'shelf_life_value' => 'required|numeric|gt:0|digits_between:1,10',
            'shelf_life_unit' => 'required|max:50',
            'shelf_life_based_on' => 'required|max:255',
            'status' => 'required|in:Drafted,Applied',
        ]);

        try {
            DB::beginTransaction();

            $old_product_image = Barcode::where('id', $barcode_id)->value('product_image');
            $old_art_work_image = Barcode::where('id', $barcode_id)->value('art_work_image');
            $check .= "old_product_image = $old_product_image, old_art_work_image = $old_art_work_image";

            $new_product_image = "";
            $new_art_work_image = "";

            if ($request->hasFile('product_image')) {
                $file = $request->file('product_image');
                $name = time() . '_product_' . uniqid() . '.' . $file->getClientOriginalExtension();
                $file->move(public_path('barcode/product'), $name);
                $new_product_image = 'barcode/product/' . $name;
            }

            if ($request->hasFile('art_work_image')) {
                $file = $request->file('art_work_image');
                $name = time() . '_artwork_' . uniqid() . '.' . $file->getClientOriginalExtension();
                $file->move(public_path('barcode/art_work'), $name);
                $new_art_work_image = 'barcode/art_work/' . $name;
            }

            $product_image = $new_product_image == "" ?  $old_product_image : $new_product_image;
            $art_work_image = $new_art_work_image == "" ? $old_art_work_image : $new_art_work_image;
            $check .= "product_image = $product_image, art_work_image = $art_work_image";

            $updated = Barcode::where('id', $barcode_id)->update([
                'code' => $request->code,
                'brand_name' => $request->brand_name,
                'product_name' => $request->product_name,
                'category_id' => $request->category_id,
                'subcategory_id' => $request->subcategory_id,
                'product_description' => $request->product_description,
                'marketing_information' => $request->marketing_information,
                'product_image' => $product_image,
                'art_work_image' => $art_work_image,
                'net_content_unit' => $request->net_content_unit,
                'mass_unit' => $request->mass_unit,
                'net_weight' => $request->net_weight,
                'net_content' => $request->net_content,
                'gross_weight' => $request->gross_weight,
                'mrp_activation_date' => $request->mrp_activation_date,
                'location' => $request->location,
                'mrp' => $request->mrp,
                'hsn' => $request->hsn,
                'gst' => $request->gst,
                'fssai_no' => $request->fssai_no,
                'food_type' => $request->food_type,
                'shelf_life_value' => $request->shelf_life_value,
                'shelf_life_unit' => $request->shelf_life_unit,
                'shelf_life_based_on' => $request->shelf_life_based_on,
                'status' => $request->status,
                'updated_by' => $auth_id,
                'updated_at' => now(),
            ]);
            $check .= "updated = $updated";
        } catch (\Exception $e) {
            DB::rollBack();
            $message = $e->getMessage();
        }

        if ($updated) {
            DB::commit();


            if ($request->status == 'Applied') {
                $next_level_code = $auth_level_code + 1;

                $next_level_mail_ids = Users::join('level', 'users.level_id', '=', 'level.id')
                    ->where('level.code', $next_level_code)
                    ->whereNotNull('users.email')
                    ->pluck('users.email');

                $details = [
                    // 'from' => $auth_user_email ?? config('mail.from.address'),
                    'subject' => 'Barcode Creation Form Code - ' . $request->code,
                    'code' => $request->code,
                    'brand_name' => $request->brand_name,
                    'product_name' => $request->product_name,
                    'status' => $request->status,
                ];

                try {
                    if ($next_level_mail_ids->isNotEmpty()) {
                        foreach ($next_level_mail_ids as $mail_id) {
                            Mail::to($mail_id)->send(new TestMail($details));
                        }

                        $flag = true;
                        $message = 'Barcode creation form updated. Mail sent successfully.';
                    } else {
                        $flag = true;
                        $message = 'Barcode creation form updated. No next-level email found.';
                    }
                } catch (\Exception $e) {
                    $message = $e->getMessage();
                }
            } else {
                $flag = true;
                $message = 'Barcode creation form updated';
            }
        } else {
            DB::rollBack();
            $message = 'Barcode creation form update failed.';
        }

        $response = [
            'flag' => $flag,
            'message' => $message,
            'records' => $records,
            'check_flag' => $check_flag,
            'check' => $check_flag ? $check : '',
        ];

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Barcode  $barcode
     * @return \Illuminate\Http\Response
     */
    public function destroy(Barcode $barcode)
    {
        //
    }

    public function delete(Request $request)
    {
        $response = [];
        $flag = false;
        $message = "";
        $records = [];
        $check = "";
        $check_flag = false;

        $deleted = false;
        $status = 'Drafted';

        $request->validate([
            'id' => 'required|exists:barcode,id',
        ]);

        $id = $request->id;
        $check .= "<br> id = $id";

        $exists = Barcode::where('id', $id)->where('status', '!=', $status)->exists();

        if ($exists) {
            $message = 'Barcode Creation details cannot be deleted.';
        } else {
            try {
                DB::beginTransaction();

                $deleted = Barcode::where('id', $id)->delete();

                if ($deleted) {
                    DB::commit();
                    $flag = true;
                    $message = 'Barcode Creation details deleted.';
                } else {
                    DB::rollBack();
                    $message = 'Barcode Creation delete failed.';
                }
            } catch (\Exception $e) {
                DB::rollBack();
                $message = $e->getMessage();
            }
        }

        $response = [
            'flag' => $flag,
            'message' => $message,
            'records' => $records,
            'check_flag' => $check_flag,
            'check' => $check_flag ? $check : '',
        ];

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

    public function sendMail()
    {
        $flag = false;
        $message = "";
        $records = [];
        $check_flag = true;
        $check = "";

        $details = [
            // 'from' => $auth_user_email ?? config('mail.from.address'),
            'subject' => 'Hello from Laravel',
            'body' => 'Dear Sir / Madam <br> This is a test email.'
        ];

        try {
            Mail::to('662000megala@gmail.com')->send(new TestMail($details));

            $flag = true;
            $message = 'Mail sent successfully';
        } catch (\Exception $e) {
            DB::rollBack();
            $message = $e->getMessage();
        }

        // assign response
        $response = [
            'flag' => $flag,
            'message' => $message,
            'records' => $records,
            'check_flag' => $check_flag,
            'check' => $check_flag ? $check : '',
        ];

        return view('dashboard', $response);
    }
}
