<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ProductCategory;
use App\Models\ProductDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $title = 'Account products';
        $products = Product::with(['productCategory'])
            ->when($request->category_id, fn ($q) => $q->where('product_category_id', $request->category_id))
            ->when($request->filled('search'), fn ($q) => $q->where('name', 'like', '%' . $request->search . '%'))
            ->latest()
            ->paginate(20)->withQueryString();
        $categories = ProductCategory::where('status', true)->orderBy('sort')->get();
        $search = $request->search ?? '';
        return view('backend.products.products.index', compact('title', 'products', 'categories', 'search'));
    }

    public function create()
    {
        $title = 'Add product';
        $categories = ProductCategory::where('status', true)->orderBy('sort')->get();
        return view('backend.products.products.create', compact('title', 'categories'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'product_category_id' => 'required|exists:product_categories,id',
            'price' => 'required|numeric|min:0',
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'status' => 'required|in:0,1',
            'file' => 'nullable|file|mimes:txt|max:10240',
        ]);

        $product = new Product();
        $product->name = $request->name;
        $product->product_category_id = $request->product_category_id;
        $product->price = $request->price;
        $product->description = $request->description;
        $product->status = (bool) $request->status;

        if ($request->hasFile('image')) {
            $file = $request->file('image');
            $filename = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
            $destinationPath = base_path('../assets/backend/images/products');
            if (!file_exists($destinationPath)) {
                mkdir($destinationPath, 0755, true);
            }
            $file->move($destinationPath, $filename);
            $product->image = 'assets/backend/images/products/' . $filename;
        }
        $product->save();

        if ($request->hasFile('file')) {
            $this->importAccountsFromFile($request->file('file'), $product->id);
        }

        return redirect()->route('backend.products.index')->with('success', 'Product added.');
    }

    public function edit($id)
    {
        $title = 'Edit product';
        $product = Product::findOrFail($id);
        $categories = ProductCategory::where('status', true)->orderBy('sort')->get();
        return view('backend.products.products.edit', compact('title', 'product', 'categories'));
    }

    public function update(Request $request, $id)
    {
        $product = Product::findOrFail($id);
        $request->validate([
            'name' => 'required|string|max:255',
            'product_category_id' => 'required|exists:product_categories,id',
            'price' => 'required|numeric|min:0',
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'status' => 'required|in:0,1',
            'file' => 'nullable|file|mimes:txt|max:10240',
        ]);

        $product->name = $request->name;
        $product->product_category_id = $request->product_category_id;
        $product->price = $request->price;
        $product->description = $request->description;
        $product->status = (bool) $request->status;

        if ($request->hasFile('image')) {
            if ($product->image && file_exists(base_path('../'.$product->image))) {
                unlink(base_path('../'.$product->image));
            }
            $file = $request->file('image');
            $filename = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
            $destinationPath = base_path('../assets/backend/images/products');
            if (!file_exists($destinationPath)) {
                mkdir($destinationPath, 0755, true);
            }
            $file->move($destinationPath, $filename);
            $product->image = 'assets/backend/images/products/' . $filename;
        }
        $product->save();

        if ($request->hasFile('file')) {
            $this->importAccountsFromFile($request->file('file'), $product->id);
        }

        return redirect()->route('backend.products.index')->with('success', 'Product updated.');
    }

    public function destroy($id)
    {
        Product::findOrFail($id)->delete();
        return redirect()->back()->with('success', 'Product deleted.');
    }

    public function accounts($id)
    {
        $product = Product::with('productCategory')->findOrFail($id);
        $title = $product->name . ' - In stock: ' . $product->in_stock;
        $accounts = ProductDetail::where('product_id', $product->id)
            ->when(request()->filled('search'), function ($q) {
                $q->where('details', 'like', '%' . request('search') . '%');
            })
            ->orderBy('id', 'desc')
            ->paginate(20)->withQueryString();
        return view('backend.products.accounts.index', compact('title', 'product', 'accounts'));
    }

    public function storeAccounts(Request $request, $id)
    {
        $product = Product::findOrFail($id);
        $request->validate(['file' => 'required|file|mimes:txt|max:10240']);
        $this->importAccountsFromFile($request->file('file'), $product->id);
        return redirect()->route('backend.products.accounts', $product->id)->with('success', 'Accounts imported.');
    }

    public function updateAccount(Request $request)
    {
        $request->validate(['id' => 'required|exists:product_details,id', 'details' => 'required|string']);
        $detail = ProductDetail::findOrFail($request->id);
        $detail->details = $request->details;
        $detail->save();
        return redirect()->back()->with('success', 'Account updated.');
    }

    public function deleteAccount($id)
    {
        $detail = ProductDetail::where('is_sold', false)->findOrFail($id);
        $detail->delete();
        return redirect()->back()->with('success', 'Account deleted.');
    }

    public function downloadDemoTxt()
    {
        $text = "Username:username | Password:password\nUsername:user2 | Password:pass2";
        return response($text, 200, [
            'Content-Type' => 'text/plain',
            'Content-Disposition' => 'attachment; filename="demo_accounts.txt"',
        ]);
    }

    private function importAccountsFromFile($file, int $productId): void
    {
        try {
            $lines = array_filter(array_map('trim', explode("\n", file_get_contents($file->path()))));
            foreach ($lines as $line) {
                if ($line === '') continue;
                ProductDetail::create([
                    'product_id' => $productId,
                    'details' => $line,
                    'is_sold' => false,
                ]);
            }
        } catch (\Throwable $e) {
            Log::warning('Product account import failed: ' . $e->getMessage());
        }
    }
}
