<?php

namespace App\Controllers;
use App\Models\AttendanceModel;

class Employee extends BaseController
{
    protected $attendance;

    public function __construct() {
        $this->attendance = new AttendanceModel();
    }
    public function dashboard() {
        $user_id = session('user_id');
        $records = $this->attendance->getAllByUser($user_id);

        return view('employee_dashboard', [
            'records' => $records
        ]);
    }
    public function punchIn() {
        $user_id = session('user_id');
        $today = date('Y-m-d');

        $record = $this->attendance->where('user_id', $user_id)
                                   ->where('attendance_date', $today)
                                   ->first();

        if ($record) {
            return redirect()->back()->with('error', 'You already punched in today.');
        }

        $this->attendance->insert([
            'user_id' => $user_id,
            'punch_in' => date('Y-m-d H:i:s'),
            'work_mode' => $this->request->getPost('mode'),
            'attendance_date' => $today,
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return redirect()->back()->with('success', 'Punch in recorded.');
    }
    public function punchOut() {
        $user_id = session('user_id');
        $today = date('Y-m-d');

        $record = $this->attendance->where('user_id', $user_id)
                                   ->where('attendance_date', $today)
                                   ->first();

        if (!$record) {
            return redirect()->back()->with('error', 'You need to punch in first.');
        }

        if ($record['punch_out']) {
            return redirect()->back()->with('error', 'You already punched out today.');
        }

        $this->attendance->update($record['id'], [
            'punch_out' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ]);

        return redirect()->back()->with('success', 'Punch out recorded.');
    }

    public function edit($id) {
        $record = $this->attendance->find($id);

        if (!$record) {
            return redirect()->back()->with('error', 'Record not found.');
        }

        return view('edit_attendance', ['record' => $record]);
    }

    public function update($id) {
        $data = [
            'punch_in' => $this->request->getPost('punch_in'),
            'punch_out' => $this->request->getPost('punch_out'),
            'work_mode' => $this->request->getPost('work_mode'),
            'updated_at' => date('Y-m-d H:i:s')
        ];

        $this->attendance->update($id, $data);

        return redirect()->to('employee/dashboard')->with('success', 'Record updated successfully.');
    }

    public function delete($id) {
        $this->attendance->delete($id);
        return redirect()->back()->with('success', 'Record deleted successfully.');
    }
}
