<?php

namespace App\Http\Controllers\Inventory;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\File;
use App\Services\FileUploadService;
use App\Models\Inventory\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\Accounting\AccountingHead;

class ProductController extends Controller
{

    protected $fileUploadService;

    public function __construct(FileUploadService $fileUploadService)
    {
        $this->fileUploadService = $fileUploadService;
    }

    public function index()
    {
        $products = Product::where('branch_id', auth()->user()->branch_id)->get();
        $accountingHeads = AccountingHead::where('branch_id', auth()->user()->branch_id)->get();
        return view('pages.inventory.product.index', compact('products', 'accountingHeads'));
    }

    public function create()
    {
        return view('pages.inventory.product.create');
    }


    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:250|unique:products',
            'current_stock' => 'nullable|numeric',
            'purchase_price' => 'nullable|numeric',
            'sale_price' => 'nullable|numeric',
            'description' => 'nullable|string',
            'attachment.*' => 'file|mimes:jpg,jpeg,png,gif|max:2048', // Add validation for file uploads
            // 'accounting_head_id' => 'required|exists:accounting_heads,id',
        ]);

        // dd($request);

        $uniqueCode = $this->generateUniqueProductCode();

        // Create a new Product instance
        $product = new Product();
        $product->branch_id = auth()->user()->branch_id;
        $product->name = $request->name;
        $product->current_stock = $request->current_stock;
        $product->purchase_price = $request->purchase_price;
        $product->sale_price = $request->sale_price;
        // $product->description = $request->description;
        $product->code = $uniqueCode; // Assign the unique code
        // $product->accounting_head_id = $request->accounting_head_id;
        // Handle file uploads
        if ($request->hasfile('attachment')) {
            $attachments = [];
            $files = $request->file('attachment');

            foreach ($files as $file) {
                $date_time = date('YmdHis');
                $fileName = $file->getClientOriginalName();
                $fileExt = $file->getClientOriginalExtension();
                $fileOrgName = basename($fileName, "." . $fileExt);
                $fileName = Str::slug($fileOrgName) . '-' . $date_time . '.' . $fileExt;

                $file_name = $this->fileUploadService->upload($file, 'uploads/products');

                // Move the file to the public directory
                // $file->move(public_path('/uploads/products/'), $fileName);

                // Add the file name to the attachments array
                $attachments[] = $file_name;
            }
            // dd($attachments);
            // Save the attachments as a JSON string
            $product->image = json_encode($attachments);
        }

        // Save the product to the database
        $product->save();

        // Redirect with success message
        return redirect()->route('product.index')->with('success', 'Product created successfully!');
    }

    public function edit($id)
    {
        $product = Product::Find($id);
        return view('pages.inventory.product.edit', compact('product'));
    }

    public function update(Request $request)
    {
        $product = Product::findOrFail($request->id);
        $request->validate([
            'name' => 'required|string|max:250|unique:products,name,' . $product->id . ',id',
            'current_stock' => 'nullable|numeric',
            'purchase_price' => 'nullable|numeric',
            'sale_price' => 'nullable|numeric',
            // 'description' => 'nullable|string',
            // 'attachment.*' => 'file|mimes:jpg,jpeg,png,gif|max:2048', // Add validation for file uploads
            // 'accounting_head_id' => 'required|exists:accounting_heads,id',
        ]);
        $product->branch_id = auth()->user()->branch_id;
        $product->name = $request->name;
        $product->current_stock = $request->current_stock;
        $product->purchase_price = $request->purchase_price;
        $product->sale_price = $request->sale_price;
        // $product->description = $request->description;
        // $product->accounting_head_id = $request->accounting_head_id;
        // Handle file uploads
        // if ($request->hasfile('attachment')) {

        //     // Decode the JSON array of file paths
        //     $existing_attachments = json_decode($product->image, true);
        //     if (is_array($existing_attachments)) {
        //         foreach ($existing_attachments as $filePath) {
        //             $fullPath = public_path($filePath);
        //             // Check if the file exists and delete it
        //             if (File::exists($fullPath)) {
        //                 File::delete($fullPath);
        //             }
        //         }
        //     }

        //     $attachments = [];
        //     $files = $request->file('attachment');
        //     foreach ($files as $file) {
        //         $file_name = Str::random(40) . '.' . $file->getClientOriginalExtension();
        //         $file->move(public_path('/uploads/products/'), $file_name);
        //         $attachments[] = 'uploads/products/'.$file_name;
        //     }
        //     $product->image = json_encode($attachments);
        // }
        $product->save();
        return redirect()->route('product.index')->with('success', 'Product updated successfully!');
    }

    public function destroy($id)
    {
        $product = Product::Find($id);
        if (!$product) {
            return redirect()->route('product.index')->with('error', 'Product not found.');
        }
        // Decode the JSON array of file paths
        $attachments = json_decode($product->image, true);
        if (is_array($attachments)) {
            foreach ($attachments as $filePath) {
                $fullPath = public_path($filePath);
                // Check if the file exists and delete it
                if (File::exists($fullPath)) {
                    File::delete($fullPath);
                }
            }
        }
        $product->delete();
        return redirect()->route('product.index')->with('success', 'Product deleted successfully!');
    }

    public function show($id)
    {
        $product = Product::Find($id);
        return view('pages.inventory.product.show', compact('product'));
    }


    private function generateUniqueProductCode()
    {
        do {
            $dateCode = date('Ymd');
            $randomNumber = Str::random(5);
            $code = "{$dateCode}-{$randomNumber}";
        } while (Product::where('code', $code)->exists());
        return $code;
    }
}
