<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Branch;
use App\Models\Company;

class BranchController extends Controller
{
    public function index()
    {
        $activeCompanyId = session('active_company_id');
        $branches = Branch::where('company_id', $activeCompanyId)->get();
        return view('admin.branch.index', compact('branches'));
    }

    public function create()
    {
        if (!session('active_company_id')) {
            return redirect()->route('company.create')->withErrors(['company_name' => 'Please create a company first before adding branches.']);
        }
        return view('admin.branch.create');
    }

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

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

        $superadminId = \App\Models\User::find($activeCompanyId)->superadmin_id ?? auth()->id();
        Branch::create(array_merge($request->all(), [
            'company_id' => $activeCompanyId,
            'superadmin_id' => $superadminId
        ]));

        return redirect()->route('branch.index')->with('success', 'Branch created successfully!');
    }

    public function edit($id)
    {
        $branch = Branch::findOrFail($id);

        if ($branch->company_id != session('active_company_id')) {
            abort(403, 'Unauthorized action.');
        }

        return view('admin.branch.edit', compact('branch'));
    }

    public function update(Request $request, $id)
    {
        $branch = Branch::findOrFail($id);

        if ($branch->company_id != session('active_company_id')) {
            abort(403, 'Unauthorized action.');
        }

        $request->validate([
            'name' => 'required|string|max:255',
            'address' => 'nullable|string|max:255',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
        ]);

        $branch->update($request->except(['company_id']));

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

    public function destroy($id)
    {
        $branch = Branch::findOrFail($id);

        if ($branch->company_id != session('active_company_id')) {
            abort(403, 'Unauthorized action.');
        }

        $branch->delete();

        return redirect()->route('branch.index')->with('success', 'Branch deleted successfully!');
    }
}
