<?php
    include "../../utils/Database.php";
    include "../../utils/functions.php";
    include "../../models/About.php";
    include "../../services/AboutService.php";
    include "../../models/Image.php";
    include "../../services/ImageService.php";
?>

<?php

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

    $about_service = new AboutService($db);

    if (isset($_POST['update'])) {
        
        if ($_FILES['fileToUpload']['name'] == "") {
            $get_image = $image_service->get($_POST['oldImage']);
            $image = new Image(
                $get_image['id'],
                $get_image['caption'],
                $get_image['filename']
            );

            $about = new About(
                1,
                $image->id,
                $_POST['description'],
                $_POST['content']
            );
    
            $result = $about_service->update($about);
    
            if($result){
                set_notification("Successfully updated","success");
            } else {
                set_notification("Some error occurred");
            }
        } else {
            $new_image = new Image(0, 'aboutus', $_FILES['fileToUpload']['name']);
            $image_service->add($new_image);
            
            $result_list = $image_service->getLatest();
            foreach($result_list as $result) {
                $image = new Image(
                    $result['id'],
                    $result['caption'],
                    $result['filename']
                );
            }

            $about = new About(
                1,
                $image->id,
                $_POST['description'],
                $_POST['content']
            );

            if (upload_file($_FILES, 'images')) {
                $result = $about_service->update($about);
                if($result){
                    set_notification("Successfully updated","success");
                } else {
                    set_notification("Some error occurred");
                }
            }
        }
        } else {

            $result = $about_service->get();

            $about = new About(
                $result['id'],
                $result['image'],
                $result['description'],
                $result['content']
            );

            $object = $image_service->get($about->image);
            $image = new Image(
                $object['id'],
                $object['caption'],
                $object['filename']
            );
        }
?>