<?php

namespace Modules\Employees\Controllers;

use core\Controller;
use core\Auth;
use core\Database;

class PerformanceController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index(): void
    {
        $this->requirePermission('performance_view');

        $db = Database::getInstance();
        $employeeId = $this->request->get('employee_id', '');
        $page = max(1, (int)$this->request->get('page', 1));
        $perPage = PAGINATION_LIMIT;

        $query = $db->table('employee_performance pr')
            ->select('pr.*, e.first_name, e.last_name, e.job_title,
                     u.first_name as reviewer_first_name, u.last_name as reviewer_last_name')
            ->leftJoin('employees e', 'pr.employee_id', '=', 'e.id')
            ->leftJoin('users u', 'pr.reviewer_id', '=', 'u.id');

        if (!empty($employeeId)) {
            $query->where('pr.employee_id', $employeeId);
        }

        $reviews = $query->orderBy('pr.created_at', 'DESC')
            ->paginate($perPage, $page);

        $employees = $db->table('employees')
            ->where('is_active', 1)
            ->where('deleted_at', 'IS', null)
            ->orderBy('first_name', 'ASC')
            ->get();

        $this->view('Employees/performance', [
            'title' => 'Performance Reviews',
            'breadcrumb' => ['Performance' => url('performance')],
            'reviews' => $reviews,
            'employeeId' => $employeeId,
            'employees' => $employees,
        ]);
    }

    public function store(): void
    {
        $this->requirePermission('performance_create');

        $validated = $this->validate([
            'employee_id' => 'required|integer',
            'rating' => 'required|numeric|min:1|max:5',
            'feedback' => 'required|max_length:5000',
            'strengths' => 'max_length:2000',
            'areas_for_improvement' => 'max_length:2000',
            'review_date' => 'required|date',
        ]);

        $db = Database::getInstance();

        $reviewId = $db->table('employee_performance')->insert([
            'employee_id' => $validated['employee_id'],
            'reviewer_id' => Auth::id(),
            'rating' => $validated['rating'],
            'feedback' => $validated['feedback'],
            'strengths' => $validated['strengths'] ?? null,
            'areas_for_improvement' => $validated['areas_for_improvement'] ?? null,
            'review_date' => $validated['review_date'],
            'created_at' => date(DATE_TIME_FORMAT),
            'updated_at' => date(DATE_TIME_FORMAT),
        ]);

        $this->logActivity('create_review', 'Created performance review #' . $reviewId);
        $this->logAudit('create', 'employee_performance', $reviewId, null, $validated);

        $this->redirectWith(url('performance'), 'success', 'Performance review created successfully.');
    }
}
