<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AutomationRule;
use App\Models\AutomationLog;
use App\Models\TicketPriority;
use App\Models\TicketStatus;
use App\Models\TicketCategory;
use App\Models\User;
use Illuminate\Http\Request;

class AutomationController extends Controller
{
    private function admin(): void {
        abort_unless(auth()->user()->hasAnyRole(['admin','superadmin']), 403);
    }

    public function index()
    {
        $this->admin();
        $rules = AutomationRule::orderBy('order')->get();
        $recentLogs = AutomationLog::with(['rule','ticket'])->latest('executed_at')->limit(20)->get();
        return view('admin.automations.index', compact('rules','recentLogs'));
    }

    public function create()
    {
        $this->admin();
        return view('admin.automations.create', $this->formData());
    }

    public function store(Request $request)
    {
        $this->admin();
        $data = $request->validate([
            'name'        => 'required|string|max:255',
            'description' => 'nullable|string',
            'trigger'     => 'required|string',
            'active'      => 'boolean',
            'order'       => 'integer',
        ]);

        $data['conditions'] = $this->parseConditions($request);
        $data['actions']    = $this->parseActions($request);
        $data['active']     = $request->boolean('active');

        AutomationRule::create($data);
        return redirect()->route('admin.automations.index')->with('success', 'Regla creada.');
    }

    public function edit(AutomationRule $automation)
    {
        $this->admin();
        return view('admin.automations.edit', array_merge(['rule' => $automation], $this->formData()));
    }

    public function update(Request $request, AutomationRule $automation)
    {
        $this->admin();
        $data = $request->validate([
            'name'        => 'required|string|max:255',
            'description' => 'nullable|string',
            'trigger'     => 'required|string',
            'order'       => 'integer',
        ]);

        $data['conditions'] = $this->parseConditions($request);
        $data['actions']    = $this->parseActions($request);
        $data['active']     = $request->boolean('active');

        $automation->update($data);
        return redirect()->route('admin.automations.index')->with('success', 'Regla actualizada.');
    }

    public function destroy(AutomationRule $automation)
    {
        $this->admin();
        $automation->delete();
        return back()->with('success', 'Regla eliminada.');
    }

    public function toggle(AutomationRule $automation)
    {
        $this->admin();
        $automation->update(['active' => !$automation->active]);
        return back()->with('success', $automation->active ? 'Regla activada.' : 'Regla desactivada.');
    }

    private function formData(): array
    {
        return [
            'triggers'    => AutomationRule::$triggers,
            'conditions'  => AutomationRule::$conditionFields,
            'operators'   => AutomationRule::$operators,
            'actionTypes' => AutomationRule::$actionTypes,
            'priorities'  => TicketPriority::active()->get(),
            'statuses'    => TicketStatus::active()->get(),
            'categories'  => TicketCategory::active()->get(),
            'agents'      => User::role(['agente','jefe_soporte','admin','superadmin'])->orderBy('name')->get(),
        ];
    }

    private function parseConditions(Request $request): array
    {
        $conditions = [];
        foreach ($request->input('conditions', []) as $c) {
            if (!empty($c['field']) && !empty($c['operator'])) {
                $conditions[] = [
                    'field'    => $c['field'],
                    'operator' => $c['operator'],
                    'value'    => $c['value'] ?? '',
                ];
            }
        }
        return $conditions;
    }

    private function parseActions(Request $request): array
    {
        $actions = [];
        foreach ($request->input('actions', []) as $a) {
            if (!empty($a['type'])) {
                $actions[] = [
                    'type'   => $a['type'],
                    'params' => $a['params'] ?? [],
                ];
            }
        }
        return $actions;
    }
}
