<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Machine;
use App\Models\Branch;
use App\Models\MachineType;

class MachineController extends Controller
{
    public function index()
    {
        $activeCompanyId = session('active_company_id');
        $machines = Machine::with(['branch', 'machineType'])
            ->where('company_id', $activeCompanyId)
            ->get();

        return view('admin.machines.index', compact('machines'));
    }

    public function create()
    {
        if (!session('active_company_id')) {
            return redirect()->route('company.create')->withErrors(['company_name' => 'Please select or create a company first.']);
        }

        $branches = Branch::where('company_id', session('active_company_id'))->get();
        $machineTypes = MachineType::all();

        return view('admin.machines.create', compact('branches', 'machineTypes'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'machine_no' => 'required',
            'machine_type_id' => 'required|exists:machine_types,id',
            'serial_no' => 'nullable',
            'port_no' => 'nullable',
            'machine_name' => 'nullable',
            'branch_id' => 'required|exists:branches,id',
            'timezone' => 'required',
            'in_out_mode' => 'required',
        ]);

        $activeCompanyId = session('active_company_id');
        if (!$activeCompanyId)
            abort(403, 'No active company selected.');

        // Ensure the selected branch belongs to the active company
        $branch = Branch::findOrFail($validated['branch_id']);
        if ($branch->company_id != $activeCompanyId) {
            abort(403, 'Unauthorized branch selection.');
        }

        $validated['company_id'] = $activeCompanyId;
        $validated['superadmin_id'] = \App\Models\User::find($activeCompanyId)->superadmin_id ?? auth()->id();

        Machine::create($validated);

        return redirect()->route('machines.index')->with('success', 'Machine added successfully!');
    }

    public function show(string $id)
    {
        //
    }

    public function edit(string $id)
    {
        $activeCompanyId = session('active_company_id');

        $machine = Machine::findOrFail($id);
        if ($machine->company_id != $activeCompanyId) {
            abort(403, 'Unauthorized action.');
        }

        $branches = Branch::where('company_id', $activeCompanyId)->get();
        $machineTypes = MachineType::all();

        return view('admin.machines.edit', compact('machine', 'branches', 'machineTypes'));
    }

    public function update(Request $request, string $id)
    {
        $activeCompanyId = session('active_company_id');
        $machine = Machine::findOrFail($id);

        if ($machine->company_id != $activeCompanyId) {
            abort(403, 'Unauthorized action.');
        }

        $validated = $request->validate([
            'machine_no' => 'required',
            'machine_type_id' => 'required|exists:machine_types,id',
            'serial_no' => 'nullable',
            'port_no' => 'nullable',
            'machine_name' => 'nullable',
            'branch_id' => 'required|exists:branches,id',
            'timezone' => 'required',
            'in_out_mode' => 'required',
        ]);

        // Ensure the selected branch belongs to the active company
        $branch = Branch::findOrFail($validated['branch_id']);
        if ($branch->company_id != $activeCompanyId) {
            abort(403, 'Unauthorized branch selection.');
        }

        $machine->update($validated);

        return redirect()->route('machines.index')->with('success', 'Machine updated successfully!');
    }

    public function destroy(string $id)
    {
        $activeCompanyId = session('active_company_id');
        $machine = Machine::findOrFail($id);

        if ($machine->company_id != $activeCompanyId) {
            abort(403, 'Unauthorized action.');
        }

        $machine->delete();
        return redirect()->route('machines.index')->with('success', 'Machine deleted successfully!');
    }
}
