<?php

    class QuizFilters extends Core {

        function list() {

            $company_id = $_GET['companyId'] ?? null;

            $sql_quiz_filters = "SELECT *
                FROM quiz_filters
                WHERE company_id = :company_id";
                
            $stmt = parent::$conn->prepare($sql_quiz_filters);
            $stmt->execute(['company_id' => $company_id]);
            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

            return ['type' => 'OK', 'data' => $result];

        }

        function save() {

            $data = $_POST;
            $name = $data['name'] ?? null;
            $company_id = $data['companyId'] ?? null;
            $criteria = $data['criteria'] ?? null;

            if (is_null($name) || is_null($company_id) || is_null($criteria)) {
                http_response_code(400);
                echo json_encode(['error' => 'Name, Company ID, and Criteria are required']);
                return;
            }

            $filter_insert = "INSERT INTO quiz_filters (company_id, name, data) 
                VALUES (:company_id, :name, :criteria)";

            $stmt = parent::$conn->prepare($filter_insert);
            $stmt->execute([
                'company_id' => $company_id,
                'name' => $name,
                'criteria' => $criteria
            ]);
            $last_id = parent::$conn->lastInsertId();

            return ['type' => 'OK', 'data' => ['filterId' => $last_id]];

        }

        function update () {
        
            $data = $_POST;
            $id = $data['id'] ?? null;
            $name = $data['name'] ?? null;
            $company_id = $data['companyId'] ?? null;
            $criteria = $data['criteria'] ?? null;

            if (is_null($id)) {
                http_response_code(400);
                echo json_encode(['error' => 'Filter ID is required']);
                return;
            }

            $filter_update = "UPDATE quiz_filters 
                SET name = :name, data = :criteria 
                WHERE id = :id AND company_id = :company_id";

            $stmt = parent::$conn->prepare($filter_update);
            $stmt->execute([
                'name' => $name,
                'criteria' => $criteria,
                'id' => $id,
                'company_id' => $company_id
            ]);

            return ['type' => 'OK', 'data' => 'Filter updated successfully'];

        }

        function delete() {
            $id = $_GET['id'] ?? null;
            if (is_null($id)) {
                http_response_code(400);
                echo json_encode(['error' => 'Filter ID is required']);
                return;
            }

            $delete_query = "DELETE FROM quiz_filters WHERE id = :id";
            $stmt = parent::$conn->prepare($delete_query);
            $stmt->execute(['id' => $id]);

            return ['type' => 'OK', 'data' => 'Filter deleted successfully'];
        }

    }