<?php

namespace App\Http\Controllers;

use App\Models\Company;
use App\Models\Project;
use App\Models\User;
use Illuminate\Http\Request;

class CompanyController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware(function ($request, $next) {
            if (!auth()->user()->isAdmin()) {
                abort(403, 'No autorizado');
            }
            return $next($request);
        });
    }

    public function index()
    {
        $companies = Company::withCount(['projects', 'users', 'tickets'])->get();
        
        return view('companies.index', compact('companies'));
    }

    public function create()
    {
        return view('companies.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'contact_email' => 'nullable|email',
            'contact_phone' => 'nullable|string|max:20',
            'address' => 'nullable|string',
        ]);

        $company = Company::create($request->all());

        return redirect()->route('companies.show', $company)->with('success', 'Empresa creada exitosamente');
    }

    public function show(Company $company)
    {
        $company->load(['projects', 'users', 'tickets']);
        
        return view('companies.show', compact('company'));
    }

    public function edit(Company $company)
    {
        return view('companies.edit', compact('company'));
    }

    public function update(Request $request, Company $company)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'contact_email' => 'nullable|email',
            'contact_phone' => 'nullable|string|max:20',
            'address' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        $company->update($request->all());

        return redirect()->route('companies.show', $company)->with('success', 'Empresa actualizada exitosamente');
    }

    public function destroy(Company $company)
    {
        // Check if company has active projects
        if ($company->projects()->where('is_active', true)->exists()) {
            return back()->with('error', 'No se puede eliminar una empresa con proyectos activos');
        }

        $company->delete();

        return redirect()->route('companies.index')->with('success', 'Empresa eliminada exitosamente');
    }

    /**
     * Assign default technicians to a project within a company
     */
    public function assignTechnicians(Request $request, Company $company, Project $project)
    {
        $request->validate([
            'default_technician_id' => 'nullable|exists:users,id',
            'default_supervisor_id' => 'nullable|exists:users,id',
            'auto_assign' => 'boolean',
        ]);

        $project->update([
            'default_technician_id' => $request->default_technician_id,
            'default_supervisor_id' => $request->default_supervisor_id,
            'auto_assign' => $request->has('auto_assign'),
        ]);

        return back()->with('success', 'Configuración de asignación actualizada');
    }
    
    /**
     * Get projects for a company (API endpoint for AJAX)
     */
    public function getProjects(Company $company)
    {
        $projects = $company->projects()
            ->where('is_active', true)
            ->select('id', 'name', 'status')
            ->orderBy('name')
            ->get();
        
        return response()->json($projects);
    }
}
