<?php

namespace App\Http\Controllers\Admin;

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

use DB;
use Illuminate\Support\Facades\Schema;  //special
use Carbon\Carbon;
use Auth;


class EmployeeController extends Controller
{
   public function create()
   {
       $designations = DB::table('designations')->get();
       return view('employees.create', compact('designations'));
   }

    public function store(Request $request)
    {
        // 1️⃣ Employee create karala ID eka ganna
        $employee_id = DB::table('employees')->insertGetId([
            'name' => $request->name,
            'phone' => $request->phone,
            'email' => $request->email,
            'section' => $request->section,
            'start_date' => $request->start_date,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        // 2️⃣ Designations save karanna
        if($request->designations){

            foreach($request->designations as $designation_id){

                DB::table('employee_designations')->insert([
                    'employee_id' => $employee_id, // 👈 me id eka thamai use karanne
                    'designation_id' => $designation_id,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }
        }

        return redirect('/profiles')->with('success','Employee Created Successfully');
    }

    public function updateDesignations(Request $request)
    {
        $employee_id = $request->employee_id;

        // delete old
        DB::table('employee_designations')
            ->where('employee_id', $employee_id)
            ->delete();

        // insert new
        if($request->designations){
            foreach($request->designations as $designation_id){
                DB::table('employee_designations')->insert([
                    'employee_id' => $employee_id,
                    'designation_id' => $designation_id
                ]);
            }
        }

        return back()->with('success','Designations Updated');
    }
}
