<?php

namespace App\Http\Controllers;

use App\Models\CustomVariable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CustomVariableController extends Controller
{
    public function list()
    {
        $user = Auth::user();
        $user_id = $user->role === 'admin' ? request('user_id', $user->id) : $user->id;

        $variables = CustomVariable::where('user_id', $user_id)
            ->orderBy('key', 'asc')
            ->paginate(20);

        return view('variable-list', compact('variables'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'key' => 'required|string|max:255|regex:/^[a-zA-Z0-9_]+$/',
            'value' => 'required',
            'type' => 'required|in:text,number,date,json',
            'description' => 'nullable|string',
            'is_global' => 'nullable|boolean',
        ]);

        $user = Auth::user();

        // Check for duplicate key
        $existing = CustomVariable::where('user_id', $user->id)
            ->where('key', $request->key)
            ->first();

        if ($existing) {
            return redirect()->back()
                ->with('danger_alert', __('Variable with this key already exists'));
        }

        CustomVariable::create([
            'user_id' => $user->id,
            'key' => $request->key,
            'value' => $request->value,
            'type' => $request->type,
            'description' => $request->description,
            'is_global' => $request->is_global ?? false,
        ]);

        return redirect()->back()
            ->with('success_alert', __('Variable created successfully'));
    }

    public function update(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:custom_variables,id',
            'value' => 'required',
            'type' => 'required|in:text,number,date,json',
            'description' => 'nullable|string',
            'is_global' => 'nullable|boolean',
        ]);

        $user = Auth::user();
        $variable = CustomVariable::findOrFail($request->id);

        if ($user->role !== 'admin' && $variable->user_id !== $user->id) {
            abort(403, 'Unauthorized access');
        }

        $variable->update([
            'value' => $request->value,
            'type' => $request->type,
            'description' => $request->description,
            'is_global' => $request->is_global ?? $variable->is_global,
        ]);

        return redirect()->back()
            ->with('success_alert', __('Variable updated successfully'));
    }

    public function destroy(Request $request)
    {
        $user = Auth::user();
        $variable = CustomVariable::findOrFail($request->id);

        if ($user->role !== 'admin' && $variable->user_id !== $user->id) {
            abort(403, 'Unauthorized access');
        }

        $variable->delete();

        return redirect()->back()
            ->with('success_alert', __('Variable deleted successfully'));
    }

    public function bulkImport(Request $request)
    {
        $request->validate([
            'variables' => 'required|string',
        ]);

        $user = Auth::user();
        $lines = explode("\n", $request->variables);
        $imported = 0;

        foreach ($lines as $line) {
            $line = trim($line);
            if (empty($line)) continue;

            $parts = explode('=', $line, 2);
            if (count($parts) !== 2) continue;

            $key = trim($parts[0]);
            $value = trim($parts[1]);

            if (empty($key)) continue;

            CustomVariable::updateOrCreate(
                [
                    'user_id' => $user->id,
                    'key' => $key,
                ],
                [
                    'value' => $value,
                    'type' => 'text',
                ]
            );

            $imported++;
        }

        return redirect()->back()
            ->with('success_alert', __('Imported') . ' ' . $imported . ' ' . __('variables'));
    }
}
