<?php   

    class MauticProfessionalExperience extends Core {        

        function store() {
            
            $vacancies = json_decode($_POST['vacancies'], true);
            $email = $_POST['email'];
            $firstJob = $_POST['firstJob'];
            $pcd_description = $_POST['pcdDescription'];
            $isPcd = $_POST['isPcd'];
            
            $sql = "SELECT id FROM leads WHERE email = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $email ]);
            $lead = $stmt->fetch(PDO::FETCH_ASSOC);

            if($vacancies) {

                $sql = "INSERT INTO professional_experiences(lead_id, organization, professional_name, branch, role_level, 
                    specialization_name, init_date, final_date, description, salary, office, ocupacao, sinonimo) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                $stmt = parent::$conn->prepare($sql);

                foreach($vacancies as $vacancy) {

                    $stmt->execute([
                        $lead['id'],
                        $vacancy['company'],
                        $vacancy['vacancy'],
                        $vacancy['branch'],
                        $vacancy['roleLevel'],
                        $vacancy['specializationName'],
                        $vacancy['admissionDate'],
                        $vacancy['currentJob'] == 'true' ? null : $vacancy['departureDate'],
                        $vacancy['description'],
                        $vacancy['salary'],
                        $vacancy['office'],
                        $vacancy['ocupacao'],
                        $vacancy['sinonimo']
                        
                    ]);

                }

            }

            if($firstJob) {

                $sql = "UPDATE leads SET first_job = 'true' WHERE id = ?";
                $stmt = parent::$conn->prepare($sql);
                $stmt->execute([$lead['id']]);                

            }

            if($isPcd == 'true') {

                $sql = "UPDATE leads SET is_pcd = 'true' WHERE id = ?";
                $stmt = parent::$conn->prepare($sql);
                $stmt->execute([$lead['id']]);

            }

            if($pcd_description) {

                $sql = "UPDATE leads SET pcd_description = ? WHERE id = ?";
                $stmt = parent::$conn->prepare($sql);
                $stmt->execute([
                    $pcd_description, $lead['id']
                ]);
                
            }

            return ['type' => 'OK'];

        }

    }