<?php

namespace App\Models;

use CodeIgniter\Model;
use Exception;

class UserModel extends Model
{
    protected $baseUrl = 'http://localhost:3000/api/users/';

    public function login($email, $password)
    {
        $client = \Config\Services::curlrequest();

        try {
            $response = $client->post($this->baseUrl . 'login', [
                'form_params' => [
                    'email' => $email,
                    'password' => $password
                ]
            ]);

            $result = json_decode($response->getBody());
            return $result;
        } catch (Exception $e) {
            // Handle exception
            return false;
        }
    }

    public function registerUser($userData)
    {
        $client = \Config\Services::curlrequest();

        try {
            $response = $client->post($this->baseUrl, [
                'form_params' => $userData
            ]);

            return json_decode($response->getBody());
        } catch (Exception $e) {
            // Handle exception
            return false;
        }
    }

    public function profile($userId)
    {
        $client = \Config\Services::curlrequest();

        try {
            $response = $client->get($this->baseUrl . $userId);
            $result = json_decode($response->getBody());
            return $result;
        } catch (Exception $e) {
            return false;
        }
    }

    public function getFilteredVacancies($skillOne, $skillTwo, $interestName)
    {
        $api = 'http://localhost:3000/api/vacancies/all-vacancies';
        $client = \Config\Services::curlrequest();

        try {
            $response = $client->get($api);
            $vacancyData = json_decode($response->getBody());

            if ($vacancyData->status === 'Success') {
                $filteredVacancies = [];
                foreach ($vacancyData->vacancies as $vacancy) {
                    $keywords = [$skillOne, $skillTwo, $interestName];
                    $matchFound = false;

                    foreach ($keywords as $keyword) {
                        if (
                            strpos(strtolower($vacancy->placement_address), strtolower($keyword)) !== false ||
                            strpos(strtolower($vacancy->skill_one_name), strtolower($keyword)) !== false ||
                            strpos(strtolower($vacancy->skill_two_name), strtolower($keyword)) !== false ||
                            strpos(strtolower($vacancy->interest_name), strtolower($keyword)) !== false
                        ) {
                            $matchFound = true;
                            break;
                        }
                    }

                    if ($matchFound) {
                        $filteredVacancies[] = $vacancy;
                    }
                }

                return $filteredVacancies;
            } else {
                return [];
            }
        } catch (Exception $e) {
            return [];
        }
    }

    public function getJobRecommendations($skillOne, $skillTwo, $interestName)
    {
        $api = 'https://journey-ml-pchfpsfuwq-uc.a.run.app/predict';
        // $api = 'http://localhost:5000/predict';
        $client = \Config\Services::curlrequest();
        $body = [
            'skill_one' => $skillOne,
            'skill_two' => $skillTwo,
            'interest' => $interestName
        ];

        try {
            $response = $client->post($api, [
                'json' => $body
            ]);
            return json_decode($response->getBody());
        } catch (Exception $e) {
            return false;
        }
    }

    public function latestVacancies($page = 1, $limit = 10)
    {
        $api = 'http://localhost:3000/api';
        $client = \Config\Services::curlrequest();

        try {
            // $response = $client->get($api . '/vacancies' . '/latest');
            $response = $client->get($api . '/vacancies' . '/latest', [
                'query' => [
                    'page' => $page,
                    'limit' => $limit
                ]
            ]);

            $result = json_decode($response->getBody());
            return $result;
        } catch (Exception $e) {
            return false;
        }
    }

    public function getVacancyById($vacancyId)
    {
        $api = 'http://localhost:3000/api';
        $client = \Config\Services::curlrequest();

        try {
            $response = $client->get($api . '/vacancies/' . $vacancyId);
            $result = json_decode($response->getBody());
            return $result;
        } catch (Exception $e) {
            return false;
        }
    }

    public function checkApplicationStatus($userId, $vacancyId)
    {
        $api = 'http://localhost:3000/api';
        $client = \Config\Services::curlrequest();

        try {
            $response = $client->get($api . '/users/applicants/' . $userId);
            $applicants = json_decode($response->getBody())->data;

            foreach ($applicants as $applicant) {
                if ($applicant->vacancy_id == $vacancyId) {
                    return $applicant->status;
                }
            }
            return 'Not Applied';  // Default status if no application is found
        } catch (Exception $e) {
            return false;
        }
    }

    public function popular()
    {
        $api = 'http://localhost:3000/api';
        $client = \Config\Services::curlrequest();

        try {
            $response = $client->get($api . '/vacancies' . '/popular');
            $result = json_decode($response->getBody());
            return $result;
        } catch (Exception $e) {
            return false;
        }
    }

    public function applyJobs($userId, $vacancyId)
    {
        $client = \Config\Services::curlrequest();

        try {
            $response = $client->post($this->baseUrl . $userId . '/vacancies/' . $vacancyId . '/apply');
            $result = json_decode($response->getBody());
            return $result;
        } catch (Exception $e) {
            return false;
        }
    }

    public function applyStatus($userId)
    {
        $client = \Config\Services::curlrequest();

        try {
            $response = $client->get($this->baseUrl . 'applicants/' . $userId);
            $result = json_decode($response->getBody());
            return $result;
        } catch (Exception $e) {
            return false;
        }
    }

    public function getUserById($userId)
    {
        $client = \Config\Services::curlrequest();
        $response = $client->get($this->baseUrl . $userId);
        return json_decode($response->getBody());
    }

    public function updateUser($userId, $data)
    {
        $client = \Config\Services::curlrequest();
        $response = $client->put($this->baseUrl . $userId, [
            'json' => $data
        ]);
        return json_decode($response->getBody());
    }

    public function uploadPhoto($userId, $file)
    {
        $client = \Config\Services::curlrequest();
        $formData = [
            'profile_photo_url' => new \CURLFile($file->getRealPath(), $file->getMimeType(), $file->getName())
        ];

        $response = $client->put($this->baseUrl . $userId . '/profile-photo', [
            'multipart' => $formData
        ]);

        return json_decode($response->getBody());
    }

    public function uploadcv($userId, $file)
    {
        $client = \Config\Services::curlrequest();
        $formData = [
            'cv' => new \CURLFile($file->getRealPath(), $file->getMimeType(), $file->getName())
        ];

        $response = $client->put($this->baseUrl . $userId, [
            'multipart' => $formData
        ]);

        return json_decode($response->getBody());
    }
    public function getCompanyDetail($companyId)
    {
        $client = \Config\Services::curlrequest();
        $api = "http://localhost:3000/api/companies/";
        try {
            $response = $client->get($api . $companyId);
            $result = json_decode($response->getBody());
            return $result;
        } catch (Exception $e) {
            return false;
        }
    }
}
