<?php

namespace App\Http\Controllers\Admin\Marketing;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class TerritoryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $territories = \App\Models\Territory::with('manager')->get();
        return view('admin.marketing.territories.index', compact('territories'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.marketing.territories.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'user_id' => 'required|exists:users,id',
        ]);

        \App\Models\Territory::create($request->all());

        return redirect()->route('admin.marketing.territories.index')->with('success', 'Territory created successfully.');
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        $territory = \App\Models\Territory::findOrFail($id);
        return view('admin.marketing.territories.edit', compact('territory'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'user_id' => 'required|exists:users,id',
        ]);

        $territory = \App\Models\Territory::findOrFail($id);
        $territory->update($request->all());

        return redirect()->route('admin.marketing.territories.index')->with('success', 'Territory updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $territory = \App\Models\Territory::findOrFail($id);
        $territory->delete();

        return redirect()->route('admin.marketing.territories.index')->with('success', 'Territory deleted successfully.');
    }
}
