<?php

    class User extends Core {

        function update() {

            $id = $_POST['id'];
            $firstname = $_POST['firstname'];
            $lastname = $_POST['lastname'];
            $password = $_POST['password'];
            $is_admin = $_POST['isAdmin'];

            $sql = "UPDATE leads SET firstname = :firstname, lastname = :lastname, password = :password, is_admin = :is_admin WHERE id = :id";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ 
                'id' => $id,
                'firstname' => $firstname,
                'lastname' => $lastname,
                'password' => $password,
                'is_admin' => $is_admin
             ]);

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

        }

        function save() {

            $email = $_POST['email'];
            $sql = "SELECT * FROM leads WHERE email = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $email ]);

            $company_id = $_POST['companyId'];

            if($stmt->rowCount() == 0) {

                $firstname = $_POST['firstname'];
                $lastname = $_POST['lastname'];
                $password = $_POST['password'];

                $sql = "INSERT leads SET firstname = :firstname, lastname = :lastname, email = :email, is_published = 1, date_added = NOW(), date_identified = NOW(), 
                    account_type = 'company', password = :password";
                $stmt = parent::$conn->prepare($sql);
                $stmt->execute([
                    ':firstname' => $firstname,
                    ':lastname' => $lastname,
                    ':email' => $email,
                    ':password' => $password
                ]);
                $user_id = parent::$conn->lastInsertId();

            } else {

                $result = $stmt->fetch(PDO::FETCH_ASSOC);
                $user_id = $result['id'];

            }
            
            $sql = "INSERT INTO companies_leads(company_id, lead_id, date_added, is_primary) VALUES(?, ?, NOW(), 1)";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $company_id, $user_id ]);
            return ['type' => 'OK'];

        }

        function list() {

            $company_id = $_GET['companyId'];
            $sql = "SELECT * FROM companies_leads as A1 LEFT JOIN leads as A2 ON A2.id = A1.lead_id WHERE company_id = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([$company_id]);

            return ['type' => 'OK', 'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)];

        }

        function delete() {

            $id = $_GET['id'] ?? null;
            $sql = "DELETE FROM leads WHERE id = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $id ]);            

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

        }

    }