<?php

namespace App\Http\Controllers;

use App\Models\TranslationDictionary;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TranslationDictionaryController extends Controller
{
    public function index(Request $request)
    {
        $query = TranslationDictionary::query();

        if ($request->search) {
            $q = $request->search;
            $query->where(function ($sq) use ($q) {
                $sq->where('english_term', 'like', "%$q%")
                    ->orWhere('arabic_term', 'like', "%$q%");
            });
        }

        if ($request->type) {
            $query->where('type', $request->type);
        }

        $dictionaries = $query->orderBy('english_term')->paginate(50)->withQueryString();
        $types = ['brand', 'product', 'unit', 'packaging', 'flavour', 'size', 'other'];

        return view('settings.translation_dictionary.index', compact('dictionaries', 'types'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'english_term' => 'required|string|max:200|unique:translation_dictionaries,english_term',
            'arabic_term'  => 'required|string|max:200',
            'type'         => 'required|in:brand,product,unit,packaging,flavour,size,other',
        ]);

        TranslationDictionary::create($validated);

        // Clear translation cache for this term
        \App\Models\TranslationCache::where('english_text', 'like', '%' . strtoupper($validated['english_term']) . '%')->delete();

        return redirect()->route('settings.translation-dictionary.index')->with('success', 'Term added to dictionary.');
    }

    public function update(Request $request, TranslationDictionary $translationDictionary)
    {
        $validated = $request->validate([
            'english_term' => 'required|string|max:200|unique:translation_dictionaries,english_term,' . $translationDictionary->id,
            'arabic_term'  => 'required|string|max:200',
            'type'         => 'required|in:brand,product,unit,packaging,flavour,size,other',
        ]);

        $translationDictionary->update($validated);
        \App\Models\TranslationCache::where('english_text', 'like', '%' . strtoupper($validated['english_term']) . '%')->delete();

        return redirect()->route('settings.translation-dictionary.index')->with('success', 'Dictionary updated.');
    }

    public function destroy(TranslationDictionary $translationDictionary)
    {
        $translationDictionary->delete();
        return redirect()->route('settings.translation-dictionary.index')->with('success', 'Term removed.');
    }

    public function importProcess(Request $request)
    {
        $request->validate(['file' => 'required|file|mimes:csv,txt|max:2048']);
        $handle  = fopen($request->file('file')->getRealPath(), 'r');
        $headers = fgetcsv($handle);
        $count   = 0;

        DB::transaction(function () use ($handle, $headers, &$count) {
            while (($row = fgetcsv($handle)) !== false) {
                $data = array_combine(array_map('strtolower', array_map('trim', $headers)), array_map('trim', $row));
                if (empty($data['english term'] ?? '')) continue;
                TranslationDictionary::updateOrCreate(
                    ['english_term' => strtoupper($data['english term'])],
                    ['arabic_term'  => $data['arabic term'] ?? '', 'type' => $data['type'] ?? 'other']
                );
                $count++;
            }
        });

        fclose($handle);
        return redirect()->route('settings.translation-dictionary.index')->with('success', "$count terms imported.");
    }
}
