<?php

namespace App\Http\Controllers;

use App\Brands;
use App\GoodReceiptTruck;
use App\Products;
use App\ProductsCategory;
use App\MeasurementUnit;
use App\ProductImages;
use App\Sale;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\DB;

class ProductsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($id)
    {
        $brand_id = Crypt::decrypt($id);
        $brand = Brands::findOrFail(Crypt::decrypt($id));
        $products = Products::with(['brand', 'unit', 'category', 'images', 'stocks'])->where('brands_id', $brand_id)->get();
        return view('products.index', compact('products', 'brand_id', 'brand'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
        $brand = Brands::findOrFail(Crypt::decrypt($id));
        $categories = ProductsCategory::where('products_category_status', '1')->get();
        $units = MeasurementUnit::where('measurement_unit_status', '1')->get();
        return view('products.create', compact('brand', 'categories', 'units'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    // public function store(Request $request)
    // {
    //     $validated = $request->validate([
    //         'brands_id' => 'required|integer',
    //         'products_name' => 'required|string|max:255',
    //         'products_sale_price' => 'required|numeric',
    //         'products_purchase_price' => 'required|numeric',
    //         'products_retail_price' => 'required|numeric',
    //         'category_id' => 'nullable|integer',
    //         'products_desc' => 'nullable|string',
    //         'unit_type_id' => 'nullable|integer',
    //         'products_qt_per_unit' => 'required|integer',
    //         'measurement_unit_id' => 'nullable|integer',
    //         'products_threshold' => 'required|integer',
    //         'products_status' => 'required|boolean',
    //         'products_images' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    //         'products_images.*' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
    //     ]);

    //     DB::transaction(function () use ($validated, $request) {
    //         $product = Products::create($validated);

    //         if ($request->hasFile('products_images')) {
    //             foreach ($request->file('products_images') as $image) {
    //                 $imageName = time() . '_' . uniqid() . '.' . $image->getClientOriginalExtension();

    //                 $image->move(public_path('uploads/products_images'), $imageName);

    //                 ProductImages::create([
    //                     'product_id' => $product->id_products,
    //                     'products_images_name' => $imageName,
    //                     'products_images_status' => '1'
    //                 ]);
    //             }
    //         }
    //     });

    //     return redirect()->route('products.list', ['id' => Crypt::encrypt($validated['brands_id'])])
    //         ->with('success', 'Product created successfully');
    // }
    public function store(Request $request)
    {
        $validated = $request->validate([
            'brand_id' => 'required|exists:brands,id_brands',
            'product_name' => 'required|string|max:255',
            'id_products_category' => 'required|exists:products_category,id_products_category',
            'product_unit' => 'nullable|exists:measurement_unit,id_measurement_unit',
            'product_status' => 'required|boolean',
            'product_desc' => 'nullable|string',
        ]);

        $product = new Products();
        $product->brands_id = $validated['brand_id'];
        $product->products_name = $validated['product_name'];
        $product->category_id = $validated['id_products_category'];
        $product->measurement_unit_id = $validated['product_unit'];
        $product->products_status = $validated['product_status'];
        $product->products_desc = $request->input('product_desc');
        $product->save();

        return redirect()->route('products.list', Crypt::encrypt($request->brand_id))
            ->with('alert', 'Product added successfully!')
            ->with('alert-class', 'success');
    }


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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Products  $products
     * @return \Illuminate\Http\Response
     */
    // public function edit($id)
    // {
    //     $product = Products::findOrFail(Crypt::decrypt($id));
    //     return view('products.edit', compact('product'));
    // }
    public function edit($id)
    {
        $product = Products::findOrFail(Crypt::decrypt($id));
        $categories = ProductsCategory::all();
        $units = MeasurementUnit::all();
        return view('products.edit', compact('product', 'categories', 'units'));
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Products  $products
     * @return \Illuminate\Http\Response
     */
    // public function update(Request $request, $id)
    // {
    //     // Validate the incoming request data
    //     $request->validate([
    //         'products_name' => 'required|string|max:255',
    //         'products_sale_price' => 'required|numeric',
    //         'products_purchase_price' => 'required|numeric',
    //         'products_retail_price' => 'required|numeric',
    //         'products_status' => 'required|in:1,0',
    //     ]);

    //     $product = Products::findOrFail(Crypt::decrypt($id));

    //     DB::beginTransaction();

    //     try {
    //         $product->update([
    //             'brands_id' => $request->brands_id,
    //             'products_name' => $request->products_name,
    //             'products_sale_price' => $request->products_sale_price,
    //             'products_purchase_price' => $request->products_purchase_price,
    //             'products_retail_price' => $request->products_retail_price,
    //             'category_id' => $request->category_id,
    //             'measurement_unit_id' => $request->measurement_unit_id,
    //             'products_qt_per_unit' => $request->products_qt_per_unit,
    //             'products_threshold' => $request->products_threshold,
    //             'products_desc' => $request->products_desc,
    //             'products_status' => $request->products_status,
    //         ]);

    //         // Handle product images upload
    //         if ($request->hasFile('products_images')) {
    //             foreach ($request->file('products_images') as $image) {
    //                 $imageName = time() . '_' . uniqid() . '.' . $image->getClientOriginalExtension();

    //                 $image->move(public_path('uploads/products_images'), $imageName);

    //                 ProductImages::create([
    //                     'product_id' => $product->id_products,
    //                     'products_images_name' => $imageName,
    //                     'products_images_status' => '1'
    //                 ]);
    //             }
    //         }

    //         DB::commit();

    //         return redirect()->route('products.list', ['id' => Crypt::encrypt($product->brands_id)])
    //             ->with('success', 'Product updated successfully');
    //     } catch (\Exception $e) {
    //         DB::rollback();
    //         return redirect()->back()->with('error', 'Failed to update product. Please try again.');
    //     }
    // }
    public function update(Request $request, $id)
    {
        // Validate the incoming request data
        $validated = $request->validate([
            'brand_id' => 'required|exists:brands,id_brands',
            'product_name' => 'required|string|max:255',
            'id_products_category' => 'required|exists:products_category,id_products_category',
            'product_unit' => 'nullable|exists:measurement_unit,id_measurement_unit',
            'product_status' => 'required|boolean',
            'product_desc' => 'nullable|string',
        ]);

        $product = Products::findOrFail(Crypt::decrypt($id));

        DB::beginTransaction();

        try {
            $product->update([
                'brands_id' => $validated['brand_id'],
                'products_name' => $validated['product_name'],
                'category_id' => $validated['id_products_category'],
                'measurement_unit_id' => $validated['product_unit'],
                'products_status' => $validated['product_status'],
                'products_desc' => $validated['product_desc'],
            ]);

            // Handle product images upload
            if ($request->hasFile('products_images')) {
                foreach ($request->file('products_images') as $image) {
                    $imageName = time() . '_' . uniqid() . '.' . $image->getClientOriginalExtension();

                    $image->move(public_path('uploads/products_images'), $imageName);

                    ProductImages::create([
                        'product_id' => $product->id_products,
                        'products_images_name' => $imageName,
                        'products_images_status' => '1'
                    ]);
                }
            }

            DB::commit();

            return redirect()->route('products.list', ['id' => Crypt::encrypt($product->brands_id)])
                ->with('success', 'Product updated successfully');
        } catch (\Exception $e) {
            DB::rollback();
            return redirect()->back()->with('error', 'Failed to update product. Please try again.');
        }
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Products  $products
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        // $product_id = Crypt::decrypt($id);
        $product = Products::with('images')->findOrFail($id);

        // Delete associated product images from the folder
        foreach ($product->images as $image) {
            $imagePath = public_path('uploads/products_images/' . $image->products_images_name);

            // Check if the file exists before attempting to delete it
            if (File::exists($imagePath)) {
                unlink($imagePath);
            }
        }

        // Delete the product and cascade delete associated images
        $product->delete();

        return redirect()->back()->with('success', 'Product and associated images deleted successfully');
    }

    public function imagesView($id)
    {
        $product = Products::findOrFail($id);
        return view('products.images_modal', compact('product'));
    }

    public function deleteImage($id)
    {
        $image = ProductImages::findOrFail($id);
        // Delete image from storage

        $imagePath = public_path('uploads/products_images/' . $image->products_images_name);

        if (File::exists($imagePath)) {
            unlink($imagePath);
        }

        $image->delete();
        return response()->json(['success' => 'Image deleted successfully']);
    }

    public function deleteAllImages($id)
    {
        $product = Products::findOrFail($id);
        // Delete all images related to the product from storage
        foreach ($product->images as $image) {
            $imagePath = public_path('uploads/products_images/' . $image->products_images_name);

            if (File::exists($imagePath)) {
                unlink($imagePath);
            }

            $image->delete();
        }

        return response()->json(['success' => 'All images deleted successfully']);
    }

    // public function allProducts()
    // {
    //     $products = Products::with(['brand', 'category', 'images', 'stocks'])->get();
    //     $good_receipts_truck = GoodReceiptTruck::with(['goodReceipts.goodReceiptDetails', 'goodReceipts.supplier'])->get();
    //     $sales = Sale::with(['salesItemsDetails', 'salesPerBoriWeight', 'customer', 'goodReceiptTruck', 'goodReceiptTruck.goodReceiptDetails'])->get();

    //     return view('products.allproducts', compact('good_receipts_truck', 'sales' ,'products'));
    // }
}
