<?php

namespace App\Controllers;

use App\Models\UserModel;
use App\Models\SkillsModel;
use App\Models\InterestModel;
use Exception;

class UserController extends BaseController
{
    public function __construct()
    {
        helper('url'); // Load the URL helper
        $this->session = \Config\Services::session();
    }
    public function index()
    {
        $session = session();

        // Cek apakah user sudah login
        if ($session->get('loggedIn')) {
            // Pengguna sudah login, arahkan ke dashboard
            return redirect()->to('vacancies');
        }

        // Tampilkan halaman login jika belum login
        return view('login');
    }

    public function profile()
    {
        if (!session()->get('loggedIn')) {
            return redirect()->to('login');
        }
        $judul = [
            'title' => 'Profil'
        ];
        $model = new UserModel();
        $userId = session()->get('userId'); // Make sure this is set

        $data = $model->profile($userId);


        if ($data) {
            return view('profile', array_merge($judul, [
                'id' => $userId,
                'full_name' => $data->user->full_name,
                'email' => $data->user->email,
                'address' => $data->user->address,
                'profile_photo_url' => $data->user->profile_photo_url,
                'gender' => $data->user->gender,
                'age' => $data->user->age,
                'cv' => $data->user->cv,
                'phone_number' => $data->user->phone_number,
                'interest_name' => $data->user->interest_name,
                'skill_one_name' => $data->user->skill_one_name,
                'skill_two_name' => $data->user->skill_two_name,
                'education' => $data->user->education,
                'is_verified' => $data->user->is_verified,
            ]));
        } else {
            return view('profile', ['user' => []]);
        }
    }

    public function editProfile($vacancyId)
    {
        if (!session()->get('loggedIn')) {
            return redirect()->to('login');
        }

        $judul = [
            'title' => 'Edit Profile'
        ];

        $model = new UserModel();
        $userId = session()->get('userId');
        $skillsModel = new SkillsModel();
        $interestModel = new InterestModel();

        $skill = $skillsModel->getSkills();
        $interest = $interestModel->getInterest();

        $data = $model->getUserById($userId, $vacancyId);

        if ($data && $data->status == 'Success') {
            return view('user_edit', array_merge($judul, ['user' => $data->user, 'skill' => $skill, 'interest' => $interest]));
        } else {
            return view('user_edit', ['user' => []]);
        }
    }

    public function updateProfile($userId) // Adjust the parameter here
    {
        $model = new UserModel();
        $data = $this->request->getPost(); // Get post data

        // Ensure only ids are submitted
        // $data['id_interest'] = $this->request->getPost('id_interest');
        // $data['skill_one'] = $this->request->getPost('skill_one');
        // $data['skill_two'] = $this->request->getPost('skill_two');

        $response = $model->updateUser($userId, $data); // Pass userId and data

        if ($response && $response->message == 'Update Successful') {
            session()->setFlashdata('pesan', 'Data Berhasil Diupload');
        } else {
            session()->setFlashdata('error', 'Failed to update profile');
        }

        // Re-fetch the updated user data
        $updatedData = $model->getUserById($userId);
        $skillsModel = new SkillsModel();
        $interestModel = new InterestModel();

        $skill = $skillsModel->getSkills();
        $interest = $interestModel->getInterest();

        $judul = [
            'title' => 'Edit Profile'
        ];

        return view('user_edit', array_merge($judul, ['user' => $updatedData->user, 'skill' => $skill, 'interest' => $interest]));
    }



    public function uploadPhoto($userId)
    {
        $model = new UserModel();
        $file = $this->request->getFile('profile_photo_url');
        log_message('debug', 'Uploading logo for company ID: ' . $userId);

        if ($file && $file->isValid() && !$file->hasMoved()) {
            $uploadResponse = $model->uploadPhoto($userId, $file);
            if ($uploadResponse->message == 'Update Successful') {
                return redirect()->to('profile')->with('message', 'Logo updated successfully.');
            } else {
                return redirect()->back()->withInput()->with('error', $uploadResponse->message ?? 'Failed to upload logo');
            }
        } else {
            return redirect()->back()->withInput()->with('error', 'Invalid file or file upload error.');
        }
    }

    public function uploadcv($userId)
    {
        $model = new UserModel();
        $file = $this->request->getFile('cv');
        log_message('debug', 'Uploading cv for company ID: ' . $userId);

        if ($file && $file->isValid() && !$file->hasMoved()) {
            $uploadResponse = $model->uploadcv($userId, $file);
            if ($uploadResponse->message == 'Update Successful') {
                return redirect()->to('profile')->with('message', 'cv updated successfully.');
            } else {
                return redirect()->back()->withInput()->with('error', $uploadResponse->message ?? 'Failed to upload cv');
            }
        } else {
            return redirect()->back()->withInput()->with('error', 'Invalid file or file upload error.');
        }
    }

    public function auth()
    {
        $session = session();
        $model = new UserModel();
        $email = $this->request->getVar('email');
        $password = $this->request->getVar('password');
        $data = $model->login($email, $password);

        if ($data && $data->status == 'Success') {
            $ses_data = [
                'userId'   => $data->id,
                'full_name'   => $data->name,
                'profile_photo_url'   => $data->profile_photo_url,
                'userEmail' => $email,
                'roleId' => $data->roleId,
                'token' => $data->token,
                'loggedIn' => true
            ];
            $session->set($ses_data);
            return redirect()->to('vacancies');
        } else {
            $session->setFlashdata('error', 'Email atau Password salah/Akun Belum Aktif');
            return redirect()->to('login');
        }
    }

    public function registerUser()
    {
        $skilModel = new SkillsModel();
        $interestModel = new InterestModel();
        $skil['skil'] = $skilModel->getSkills();
        $interest['interest'] = $interestModel->getInterest();
        return view('register', array_merge($skil, $interest));
    }

    public function sendWhatsAppNotification($phoneNumber, $message)
    {
        $client = \Config\Services::curlrequest();

        try {
            $response = $client->post('https://api.kuotavpn.com/api/create-message', [
                'form_params' => [
                    'appkey' => 'aeddea6e-6b28-43ac-bcfb-a6211783d45b',
                    'authkey' => 'mhuiWc2Aqhp12TB9tgqhVuGYeG6iT2iGSlFOsDzHel8f8KxXRY',
                    'to' => $phoneNumber,
                    'message' => $message
                ]
            ]);

            return json_decode($response->getBody())->success;
        } catch (\Exception $e) {
            log_message('error', 'Failed to send WhatsApp message: ' . $e->getMessage());
            return false;
        }
    }

    public function submitUserRegister()
    {
        $session = session();
        $model = new UserModel();
        $userData = $this->request->getPost();
        $newCompanyName = $userData['full_name'];

        $response = $model->registerUser($userData);

        if ($response && $response->status == 'Success') {
            $whatsAppMessage = "Pencaker *$newCompanyName* berhasil mendaftar. Mohon untuk diperiksa kelengkapan datanya.";
            $phoneNumber = "6285946362394"; // Nomor yang menerima notifikasi
            $this->sendWhatsAppNotification($phoneNumber, $whatsAppMessage);
            $session->setFlashdata('success', 'Pendaftaran Berhasil, silakan login');
            return redirect()->to('login');
        } else {
            $session->setFlashdata('error', 'Pendaftaran gagal, pastikan data yang dimasukan benar!');
            return redirect()->to('register');
        }
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to('login');
    }

    public function dashboard()
    {
        if (!session()->get('loggedIn')) {
            return redirect()->to('login');
        }
        $judul = [
            'title' => 'Dashboard'
        ];
        $data = array_merge($judul);
        return view('dashboard', $data);
    }

    public function vacancies()
    {
        if (!session()->get('loggedIn')) {
            return redirect()->to('login');
        }
        $judul = [
            'title' => 'Vacancies'
        ];
        $userId = session()->get('userId'); // Make sure this is set

        $page = $this->request->getGet('page') ?? 1;
        $limit = 10; // Atur jumlah data per halaman

        $model = new UserModel();

        $dataUser = $model->profile($userId);
        $data = $model->latestVacancies($page, $limit);
        if ($data && $dataUser && $data->status == 'Success') {
            // Potong deskripsi sebelum mengirimkan ke view
            foreach ($data->vacancies as &$vacancy) {
                $vacancy->description = $this->truncateWords($vacancy->description, 20);
                $vacancy->deadline_time = $this->truncateCharacters($vacancy->deadline_time, 10);

                // Ubah deadline_time jika melewati tanggal hari ini
                $deadline = new \DateTime($vacancy->deadline_time);
                $today = new \DateTime();

                if ($deadline < $today) {
                    $vacancy->deadline_time = 'Ditutup';
                }
            }
            $viewData = array_merge($judul, [
                'vacancies' => $data->vacancies,
                'totalPages' => $data->totalPages,
                'currentPage' => $page,
                'users' => $dataUser->user->is_verified
            ]);
        } else {
            $viewData = array_merge($judul, [
                'vacancies' => [],
                'totalPages' => 1,
                'currentPage' => 1
            ]);
        }

        $final = array_merge($viewData);

        return view('vacancies', $final);
    }

    private function truncateWords($text, $limit)
    {
        $words = explode(' ', $text);
        if (count($words) > $limit) {
            return implode(' ', array_slice($words, 0, $limit)) . '...';
        }
        return $text;
    }

    private function truncateCharacters($text, $limit)
    {
        // Mengecek apakah panjang teks lebih besar dari batas yang ditentukan
        if (strlen($text) > $limit) {
            // Memotong teks sesuai dengan batas yang ditentukan dan menambahkan '...'
            return substr($text, 0, $limit);
        }
        return $text;
    }


    public function popular()
    {
        if (!session()->get('loggedIn')) {
            return redirect()->to('login');
        }
        $judul = [
            'title' => 'Popular vacancies'
        ];
        $model = new UserModel();
        $companyId = session()->get('userId'); // Make sure this is set

        $page = $this->request->getGet('page') ?? 1;
        $limit = 10; // Atur jumlah data per halaman

        $data = $model->popular($page, $limit);
        if ($data && $data->status == 'Success') {
            // Potong deskripsi sebelum mengirimkan ke view dan atur pagination
            foreach ($data->vacancies as &$vacancy) {
                $vacancy->description = $this->truncateWords($vacancy->description, 20);
            }
            $viewData = array_merge($judul, [
                'vacancies' => $data->vacancies,
                'totalPages' => $data->totalPages,
                'currentPage' => $page
            ]);
        } else {
            $viewData = array_merge($judul, [
                'vacancies' => [],
                'totalPages' => 1,
                'currentPage' => 1
            ]);
        }

        return view('popular', $viewData);
    }



    public function applyStatus()
    {
        if (!session()->get('loggedIn')) {
            return redirect()->to('login');
        }
        $judul = [
            'title' => 'Apply Status'
        ];
        $model = new UserModel();
        $userId = session()->get('userId'); // Make sure this is set

        $data = $model->applyStatus($userId);
        if ($data && $data->status == 'Success') {
            return view('apply_status', array_merge($judul, ['data' => $data->data]));
        } else {
            return view('apply_status', ['data' => []]);
        }
    }

    public function applyJobs($userId, $vacancyId)
    {
        $model = new UserModel();
        $result = $model->applyJobs($userId, $vacancyId);

        if ($result && $result->message == 'Job application successful') {
            return redirect()->to(base_url('status'))->with('message', 'Lamaran berhasil dikirim dan sedang ditinjau oleh perusahaan!');
        } else {
            return redirect()->back()->with('error', 'Akun belum diverifikasi karena dokumen belum dilengkapi, silakan lengkapi dokumen anda di menu profil!');
        }
    }

    public function detail_vacancy($vacancyId)
    {
        $model = new UserModel();
        $userId = session()->get('userId');

        $vacancyData = $model->getVacancyById($vacancyId);
        $applicationStatus = $model->checkApplicationStatus($userId, $vacancyId);

        if ($vacancyData && $vacancyData->status == 'Success') {
            return view('detail_vacancy', [
                'userId' => $userId,
                'id' => $vacancyData->vacancy->id,
                'placement_address' => $vacancyData->vacancy->placement_address,
                'description' => $vacancyData->vacancy->description,
                'created_at' => $vacancyData->vacancy->created_at,
                'updated_at' => $vacancyData->vacancy->updated_at,
                'deadline_time' => $vacancyData->vacancy->deadline_time,
                'job_type' => $vacancyData->vacancy->job_type,
                'skill_one_name' => $vacancyData->vacancy->skill_one_name,
                'skill_two_name' => $vacancyData->vacancy->skill_two_name,
                'interest_name' => $vacancyData->vacancy->interest_name,
                'company_logo' => $vacancyData->vacancy->company_logo,
                'company_name' => $vacancyData->vacancy->company_name,
                'sector_name' => $vacancyData->vacancy->sector_name,
                'applicationStatus' => $applicationStatus  // Adding application status to data passed to view
            ]);
        } else {
            return view('detail_vacancy', ['data' => []]);
        }
    }

    // public function recommendJobs()
    // {
    //     $model = new UserModel();
    //     $userId = session()->get('userId');
    //     $userProfile = $model->profile($userId);

    //     if ($userProfile && $userProfile->status == 'Success') {
    //         $recommendations = $model->getJobRecommendations(
    //             $userProfile->user->skill_one_name,
    //             $userProfile->user->skill_two_name,
    //             $userProfile->user->interest_name
    //         );

    //         return view('recommend_jobs', [
    //             'recommendations' => $recommendations->predictions ?? []
    //         ]);
    //     } else {
    //         return view('recommend_jobs', ['error' => 'Failed to fetch user profile or recommendations']);
    //     }
    // }

    public function recommendJobs()
    {
        if (!session()->get('loggedIn')) {
            return redirect()->to('login');
        }
        $judul = [
            'title' => 'Rekomendasi Pekerjaan'
        ];

        $model = new UserModel();
        $userId = session()->get('userId');
        $userProfile = $model->profile($userId);

        if ($userProfile && $userProfile->status == 'Success') {
            $recommendations = $model->getJobRecommendations(
                $userProfile->user->skill_one_name,
                $userProfile->user->skill_two_name,
                $userProfile->user->interest_name
            );

            $vacancyModel = new UserModel();
            $filteredVacancies = $vacancyModel->getFilteredVacancies(
                $userProfile->user->skill_one_name,
                $userProfile->user->skill_two_name,
                $userProfile->user->interest_name
            );

            // Potong deskripsi sebelum mengirimkan ke view
            foreach ($filteredVacancies as &$vacancy) {
                $vacancy->description = $this->truncateWords($vacancy->description, 20);
            }

            return view('recommend_jobs', array_merge($judul, [
                'recommendations' => $recommendations->predictions ?? [],
                'filteredVacancies' => $filteredVacancies
            ]));
        } else {
            return view('recommend_jobs', ['error' => 'Failed to fetch user profile or recommendations']);
        }
    }

    public function detail_vacancy_with_company($vacancyId)
    {
        if (!session()->get('loggedIn')) {
            return redirect()->to('login');
        }
        $judul = [
            'title' => 'Detail Vacancy'
        ];
        $model = new UserModel();
        $userId = session()->get('userId');

        // Mendapatkan detail lowongan pekerjaan
        $vacancyData = $model->getVacancyById($vacancyId);
        // Mendapatkan status aplikasi
        $applicationStatus = $model->checkApplicationStatus($userId, $vacancyId);

        // Pastikan vacancyData dan vacancyData->vacancy valid sebelum mengambil company_id
        if ($vacancyData && $vacancyData->status == 'Success' && isset($vacancyData->vacancy->company_id)) {
            $companyId = $vacancyData->vacancy->company_id;

            // Mendapatkan detail perusahaan
            $companyData = $model->getCompanyDetail($companyId);

            if ($companyData && $companyData->status == 'Success') {
                return view('detail_vacancy_with_company', array_merge($judul, [
                    'userId' => $userId,
                    'vacancy' => $vacancyData->vacancy,
                    'applicationStatus' => $applicationStatus,
                    'company' => $companyData->company
                ]));
            }
        }

        return view('detail_vacancy_with_company', ['data' => [], 'company' => []]);
    }

    public function tes($vacancyId)
    {
        $judul = [
            'title' => 'Vacancies'
        ];
        $model = new UserModel();
        $userId = session()->get('userId');

        // Mendapatkan detail lowongan pekerjaan
        $vacancyData = $model->getVacancyById($vacancyId);
        // Mendapatkan status aplikasi
        $applicationStatus = $model->checkApplicationStatus($userId, $vacancyId);

        // Pastikan vacancyData dan vacancyData->vacancy valid sebelum mengambil company_id
        if ($vacancyData && $vacancyData->status == 'Success' && isset($vacancyData->vacancy->company_id)) {
            $companyId = $vacancyData->vacancy->company_id;

            // Mendapatkan detail perusahaan
            $companyData = $model->getCompanyDetail($companyId);

            if ($companyData && $companyData->status == 'Success') {
                return view('tes', array_merge($judul, [
                    'userId' => $userId,
                    'vacancy' => $vacancyData->vacancy,
                    'applicationStatus' => $applicationStatus,
                    'company' => $companyData->company
                ]));
            }
        }

        return view('tes', ['data' => [], 'company' => []]);
    }
}
