<?php

namespace App\Http\Controllers;

use App\Models\Barcode;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CategoryController 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;

        // get full category lists
        $records = Category::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('category-list', $response);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('category-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 = false;

        $insert_id = 0;

        $auth_user_id = auth()->user()->id;

        $request->validate([
            'code' => 'required|max:50',
            'name' => 'required|max:100',
            'status' => 'required|in:Active,Inactive',
        ]);
        // ], ['status.in' => 'Status must be Active or Inactive only.',]);

        $code = $request->code;
        $name = $request->name;
        $status = $request->status;

        $exists = Category::where('code', $code)->where('name', $name)->exists();

        if ($exists) {
            $message = 'Category already exists.';
        } else {
            try {
                DB::beginTransaction();

                // insert all requested data into db
                $insert_id = Category::create([
                    'code' => $code,
                    'name' => $name,
                    'status' => $status,
                    'created_by' => $auth_user_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();
            $flag = true;
            $message = 'Category details saved.';
        }

        $response = [
            'flag' => $flag,
            'message' => $message,
            'records' => $records,
            'check_flag' => $check_flag,
            'check' => $check_flag ? $check : '',
        ];
        return response()->json($response);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function show(Category $category)
    {
        //
    }

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

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

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

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

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


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

        $updated = false;

        $auth_user_id = auth()->user()->id;

        $request->validate([
            'id' => 'required|exists:category,id',
            'code' => 'required|max:50',
            'name' => 'required|max:100',
            'status' => 'required|in:Active,Inactive',
        ]);
        // ], ['status.in' => 'Status must be Active or Inactive only.',]);

        $id = $request->id;
        $code = $request->code;
        $name = $request->name;
        $status = $request->status;

        $check .= "id = $id, code = $code, name = $name, status = $status";

        // check category already exists or not
        $exists = Category::where('code', $code)->where('name', $name)->where('id', '!=', $id)->exists();

        if ($exists) {
            $message = 'Category already exists.';
        } else {

            try {
                DB::beginTransaction();

                $updated = Category::where('id', $id)->update([
                    'code' => $code,
                    'name' => $name,
                    'status' => $status,
                    'updated_by' => $auth_user_id,
                    'updated_at' => now(),
                ]);
            } catch (\Exception $e) {
                DB::rollBack();
                $message = $e->getMessage();
            }

            if ($updated) {
                DB::commit();
                $flag = true;
                $message = 'Category details updated.';
            } else {
                DB::rollBack();
                $message = 'Category 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\Category  $category
     * @return \Illuminate\Http\Response
     */

    public function destroy(Category $category)
    {
        //
    }

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

        $deleted = false;

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

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

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

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

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

                if ($deleted) {
                    DB::commit();
                    $flag = true;
                    $message = 'Category details deleted.';
                } else {
                    DB::rollBack();
                    $message = 'Category 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 options()
    {
        // initialize variables
        $response = [];
        $flag = false;
        $message = "";
        $records = [];
        $check = "";
        $check_flag = false;

        // get full category options
        $records = Category::where('status', 'Active')->orderBy('name', 'asc')->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 response()->json($response);
    }
}
