<?php

namespace App\Http\Controllers\Academic;

use App\Http\Controllers\Controller;
use App\Models\Academic\Branch;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class BranchController extends Controller
{
    public function index()
    {
        $this->authorize('academic.branches.view');
        $branches = Branch::all();
        return view('pages.academic.branch.index', compact('branches'));
    }

    public function create()
    {
        $this->authorize('academic.branches.create');
        return view('pages.academic.branch.create');
    }

    public function store(Request $request)
    {
        $this->authorize('academic.branches.create');
        $request->validate([
            'branch_name' => 'required',
            'address' => 'required',
            'contact_info' => 'required',
            'status' => 'required',
        ]);

        Branch::create($request->all());
        Cache::forget('branch_data');
        return redirect()->route('branches.index')->with('success', 'Branch created successfully.');
    }

    public function show(Branch $branch)
    {
        $this->authorize('academic.branches.view');
        return view('pages.academic.branch.show', compact('branch'));
    }

    public function edit(Branch $branch)
    {
        $this->authorize('academic.branches.edit');
        return view('pages.academic.branch.edit', compact('branch'));
    }

    public function update(Request $request)
    {
        $this->authorize('academic.branches.edit');
        $request->validate([
            'branch_name' => 'required',
            'address' => 'required',
            'contact_info' => 'required',
            'status' => 'required',
        ]);

        $branch = Branch::findOrFail($request->id);
        $branch->branch_name = $request->branch_name;
        $branch->address = $request->address;
        $branch->contact_info = $request->contact_info;
        $branch->status = $request->status;
        $branch->save();

        Cache::forget('branch_data');

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

    public function destroy(Branch $branch)
    {
        $this->authorize('academic.branches.delete');
        $branch->delete();
        return redirect()->route('branches.index')->with('success', 'Branch deleted successfully.');
    }

    public function branchSwitch(Request $request)
    {
        $branch_id = $request->branch_id;
        $user_id = auth()->user()->id;
        User::where('id', '=', $user_id)->update([
            'branch_id' => $branch_id
        ]);
        
        //forget cache
        Cache::forget('total_employees');
        Cache::forget('total_teachers');

        return response()->json([
            'success' => true,
            'message' => 'Branch Successfully Switch.'
        ]);
    }
}
