<?php

namespace App\Controllers;

use App\Models\ProjectModel;
use App\Models\ExpenseModel;
use App\Models\ProjectAssignmentModel;
use App\Models\UserModel;
use App\Models\AttendanceModel;

class Employee extends BaseController
{
    protected $session;

    public function __construct()
    {
        $this->session = session();
        if (!$this->session->get('isLoggedIn') || $this->session->get('role') !== 'employee') {
            // Redirect will be handled by filters ideally, but manual check for now
        }
    }

    public function index()
    {
        if (!$this->session->get('isLoggedIn') || $this->session->get('role') !== 'employee') {
            return redirect()->to('/login');
        }

        $userId = $this->session->get('id');
        $assignModel = new ProjectAssignmentModel();
        $projectModel = new ProjectModel();

        // Get assigned projects
        $assignments = $assignModel->where('user_id', $userId)->findAll();
        $projectIds = array_column($assignments, 'project_id');
        
        $projects = [];
        if (!empty($projectIds)) {
            $projects = $projectModel->whereIn('id', $projectIds)->findAll();
            foreach ($projects as &$project) {
                $allAssigns = $assignModel->where('project_id', $project['id'])->findAll();
                $teammates = [];
                foreach ($allAssigns as $a) {
                    $u = (new UserModel())->find($a['user_id']);
                    if ($u) $teammates[] = $u['name'];
                }
                $project['assigned_employees'] = $teammates;
            }
        }

        $attendanceModel = new AttendanceModel();
        $todayAttendance = $attendanceModel->where('user_id', $userId)
                                           ->where('date', date('Y-m-d'))
                                           ->first();

        $data = [
            'title' => 'Employee Dashboard',
            'user' => (new UserModel())->find($userId),
            'projects' => $projects,
            'project_count' => count($projects),
            'today_attendance' => $todayAttendance,
            'settings' => (new \App\Models\SettingsModel())->asArray()->findAll() ? array_column((new \App\Models\SettingsModel())->findAll(), 'setting_value', 'setting_key') : []
        ];

        return view('employee/dashboard', $data);
    }

    public function my_expenses()
    {
        if (!$this->session->get('isLoggedIn') || $this->session->get('role') !== 'employee') {
            return redirect()->to('/login');
        }

        $userId = $this->session->get('id');
        $expenseModel = new ExpenseModel();
        $settingsModel = new \App\Models\SettingsModel();

        $expenses = $expenseModel->select('project_expenses.*, projects.title as project_title')
                               ->join('projects', 'projects.id = project_expenses.project_id')
                               ->where('employee_id', $userId)
                               ->orderBy('date', 'DESC')
                               ->findAll();

        $data = [
            'title' => 'My Expenses',
            'expenses' => $expenses,
            'settings' => $settingsModel->asArray()->findAll() ? array_column($settingsModel->findAll(), 'setting_value', 'setting_key') : []
        ];

        return view('employee/expenses', $data);
    }

    public function save_attendance()
    {
        if (!$this->session->get('isLoggedIn') || $this->session->get('role') !== 'employee') {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Unauthorized']);
        }

        $userId = $this->session->get('id');
        $status = $this->request->getPost('status') ?: 'Present';
        $imageData = $this->request->getPost('image');

        if (empty($imageData)) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'No image captured']);
        }

        // Save image
        $imageData = str_replace('data:image/jpeg;base64,', '', $imageData);
        $imageData = str_replace(' ', '+', $imageData);
        $imageName = 'att_' . $userId . '_' . time() . '.jpg';
        $filePath = FCPATH . 'uploads/attendance/' . $imageName;
        
        if (!is_dir(FCPATH . 'uploads/attendance')) {
            mkdir(FCPATH . 'uploads/attendance', 0777, true);
        }

        file_put_contents($filePath, base64_decode($imageData));

        $attendanceModel = new AttendanceModel();
        
        // Check if already exists
        $exists = $attendanceModel->where('user_id', $userId)
                                  ->where('date', date('Y-m-d'))
                                  ->first();
        
        if ($exists) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Attendance already marked for today']);
        }

        $attendanceModel->save([
            'user_id' => $userId,
            'date' => date('Y-m-d'),
            'status' => $status,
            'image_path' => 'uploads/attendance/' . $imageName,
            'approval_status' => 'Pending'
        ]);

        return $this->response->setJSON(['status' => 'success', 'message' => 'Attendance marked successfully']);
    }

    public function my_attendance()
    {
        if (!$this->session->get('isLoggedIn') || $this->session->get('role') !== 'employee') {
            return redirect()->to('/login');
        }

        $userId = $this->session->get('id');
        $attendanceModel = new AttendanceModel();
        $settingsModel = new \App\Models\SettingsModel();

        $data = [
            'title' => 'My Attendance History',
            'attendance' => $attendanceModel->where('user_id', $userId)->orderBy('date', 'DESC')->findAll(),
            'settings' => $settingsModel->asArray()->findAll() ? array_column($settingsModel->findAll(), 'setting_value', 'setting_key') : []
        ];

        return view('employee/attendance', $data);
    }

    public function my_projects()
    {
        if (!$this->session->get('isLoggedIn') || $this->session->get('role') !== 'employee') {
            return redirect()->to('/login');
        }

        $userId = $this->session->get('id');
        $assignModel = new ProjectAssignmentModel();
        $projectModel = new ProjectModel();
        $settingsModel = new \App\Models\SettingsModel();

        $assignments = $assignModel->where('user_id', $userId)->findAll();
        $projectIds = array_column($assignments, 'project_id');
        
        $projects = [];
        if (!empty($projectIds)) {
            $projects = $projectModel->whereIn('id', $projectIds)->findAll();
            foreach ($projects as &$project) {
                $allAssigns = $assignModel->where('project_id', $project['id'])->findAll();
                $teammates = [];
                foreach ($allAssigns as $a) {
                    $u = (new UserModel())->find($a['user_id']);
                    if ($u) $teammates[] = $u['name'];
                }
                $project['assigned_employees'] = $teammates;
            }
        }

        $data = [
            'title' => 'My Assigned Projects',
            'projects' => $projects,
            'settings' => $settingsModel->asArray()->findAll() ? array_column($settingsModel->findAll(), 'setting_value', 'setting_key') : []
        ];

        return view('employee/projects', $data);
    }

    public function profile()
    {
        if (!$this->session->get('isLoggedIn') || $this->session->get('role') !== 'employee') {
            return redirect()->to('/login');
        }

        $userId = $this->session->get('id');
        $userModel = new UserModel();
        $settingsModel = new \App\Models\SettingsModel();

        if ($this->request->getMethod() === 'post') {
            $data = [
                'name' => $this->request->getPost('name'),
                'phone' => $this->request->getPost('phone'),
                'address' => $this->request->getPost('address'),
            ];

            $file = $this->request->getFile('profile_pic');
            if ($file && $file->isValid() && !$file->hasMoved()) {
                $newName = $file->getRandomName();
                $file->move('uploads/profiles', $newName);
                $data['profile_pic'] = 'uploads/profiles/' . $newName;
                $this->session->set('profile_pic', base_url($data['profile_pic']));
            }

            $password = $this->request->getPost('password');
            $confirm_password = $this->request->getPost('confirm_password');
            if (!empty($password)) {
                if ($password === $confirm_password) {
                    $data['password'] = password_hash($password, PASSWORD_DEFAULT);
                } else {
                    return redirect()->back()->with('error', 'Passwords do not match!');
                }
            }

            $userModel->update($userId, $data);
            $this->session->set('name', $data['name']);
            return redirect()->to('/employee/profile')->with('success', 'Profile updated successfully!');
        }

        $data = [
            'title' => 'My Profile',
            'user' => $userModel->find($userId),
            'settings' => $settingsModel->asArray()->findAll() ? array_column($settingsModel->findAll(), 'setting_value', 'setting_key') : []
        ];

        return view('employee/profile', $data);
    }

    public function settings()
    {
        if (!$this->session->get('isLoggedIn') || $this->session->get('role') !== 'employee') {
            return redirect()->to('/login');
        }

        $userId = $this->session->get('id');
        $userModel = new UserModel();
        $settingsModel = new \App\Models\SettingsModel();

        if ($this->request->getMethod() === 'post') {
            $password = $this->request->getPost('password');
            $confirm_password = $this->request->getPost('confirm_password');

            if ($password && $password === $confirm_password) {
                $userModel->update($userId, ['password' => password_hash($password, PASSWORD_DEFAULT)]);
                return redirect()->to('/employee/settings')->with('success', 'Password changed successfully!');
            } else {
                return redirect()->to('/employee/settings')->with('error', 'Passwords do not match!');
            }
        }

        $data = [
            'title' => 'Account Settings',
            'settings' => $settingsModel->asArray()->findAll() ? array_column($settingsModel->findAll(), 'setting_value', 'setting_key') : []
        ];

        return view('employee/settings', $data);
    }

    public function project_expenses($projectId)
    {
        if (!$this->session->get('isLoggedIn') || $this->session->get('role') !== 'employee') {
            return redirect()->to('/login');
        }

        $userId = $this->session->get('id');
        $expenseModel = new ExpenseModel();
        $projectModel = new ProjectModel();
        $settingsModel = new \App\Models\SettingsModel();

        $project = $projectModel->find($projectId);
        if (!$project) {
            return redirect()->back()->with('error', 'Project not found.');
        }

        if ($this->request->getMethod() === 'post') {
            $categories = $this->request->getPost('category');
            $descriptions = $this->request->getPost('description');
            $amounts = $this->request->getPost('amount');
            $dates = $this->request->getPost('date');

            if (!empty($amounts)) {
                // Clear previous project expenses for this employee to re-sync
                $expenseModel->where('project_id', $projectId)
                            ->where('employee_id', $userId)
                            ->delete();

                foreach ($amounts as $key => $amount) {
                    if (!empty($amount)) {
                        $expenseModel->insert([
                            'project_id' => $projectId,
                            'employee_id' => $userId,
                            'category' => $categories[$key],
                            'description' => $descriptions[$key],
                            'amount' => $amount,
                            'date' => $dates[$key]
                        ]);
                    }
                }
                return redirect()->to('/employee/project_expenses/' . $projectId)->with('success', 'Project expenses updated successfully!');
            }
        }

        $expenses = $expenseModel->where('project_id', $projectId)
                               ->where('employee_id', $userId)
                               ->orderBy('date', 'DESC')
                               ->findAll();

        $data = [
            'title' => 'Project Expenses: ' . $project['title'],
            'project' => $project,
            'expenses' => $expenses,
            'settings' => $settingsModel->asArray()->findAll() ? array_column($settingsModel->findAll(), 'setting_value', 'setting_key') : []
        ];

        return view('employee/project_expenses', $data);
    }
}
