<?php
    include "../../utils/Database.php";
    include "../../utils/functions.php";
    include "../../models/Message.php";
    include "../../services/MessageService.php";
?>

<?php

    $database = new Database();
    $db = $database->connect();

    $message_service = new MessageService($db);

    if (isset($_POST['delete'])) {
        $action = 'delete';
    }

    switch($action) {
        case 'add':
            if(isset($_POST['add'])){
                $message = new Message(
                    0,
                    $_POST['full_name'],
                    $_POST['email'],
                    $_POST['subject'],
                    $_POST['message']
                );
                
                $result = $message_service->add($message);
            }
            break;
        case 'view':
            $result = $message_service->get($_GET['id']);

            $message = new Message(
                $result['id'],
                $result['full_name'],
                $result['email'],
                $result['subject'],
                $result['message']
            );
            break;
        case 'list':
            $result_list = $message_service->list();
            
            $messages = array();
            
            foreach($result_list as $result) {
                $message = new Message(
                    $result['id'],
                    $result['full_name'],
                    $result['email'],
                    $result['subject'],
                    $result['message']
                );
                array_push($messages, $message);
            }

            break;
        case 'delete':
            $object = $message_service->get($_POST['deleteId']);
                
            $message = new Message(
                $object['id'],
                $object['full_name'],
                $object['email'],
                $object['subject'],
                $object['message']
            );
            if ($message) {
                $result = $message_service->delete($message);
                if($result){
                    set_notification("Message successfully deleted", "success");
                } else {
                    set_notification("Some error occurred", "error");
                }
            }
            redirect("message");
            break;
        default:
            continue;
    }
?>