<?php 
    if ( !$user['admin'] ) {
        session_start();
        $_SESSION['error'] = "Unauthorized";

        header('Location: '.URL_APP.'/dashboard/');
        exit;
    }

    session_start();
    if ( isset($_SESSION['error']) ) {
        $error = $_SESSION['error'];
        unset($_SESSION['error']);
    } else {
        $error = false;
    }

    $pages = [
        'ai',
        'p',
        'c',
        'u',
        'w',
        'pp',
    ];
    $page = ( isset($_GET['page']) && in_array($_GET['page'], $pages) )
        ? $_GET['page']
        : 'p'
    ;

    $views = [
        't',
        // 'c'
    ];
    $view = ( isset($_GET['view']) && in_array($_GET['view'], $views) )
        ? $_GET['view'] 
        : $_COOKIE['btbAdminView'] ?? 't'
    ;
    setcookie('btbAdminView', $view, time() + (60*60*24*30*12), '/clients', URL_COOKIES);

    $pdo = $db->getPdo();
    switch ( $page ) {
        case 'ai' :
            if ( !$user['superAdmin'] ) {
                session_start();
                $_SESSION['error'] = "Unauthorized";

                header('Location: '.URL_APP_ADMIN."/?page=p&view=$view");
                exit;
            }
            if ( isset($_GET['conversationId']) ) {
                $conversation = $db->row("SELECT * FROM ai_conversation WHERE id = ? AND createdBy = ?", $_GET['conversationId'], $user['id']);
                if ( $conversation ) {
                    $conversationTokens = $db->cell("SELECT SUM(tokens) FROM ai_message WHERE conversationId = ?", $conversation['id']);
                    $conversation['messages'] = $db->run("SELECT * FROM ai_message WHERE conversationId = ? AND parentId IS NULL ORDER BY id ASC", $conversation['id']);
                    $i = 0;
                    foreach ( $conversation['messages'] as $message ) {
                        $conversation['messages'][$i]['prompt'] = $db->row("SELECT * FROM ai_message WHERE parentId = ?", $message['id']);
                        $conversation['messages'][$i]['prompt']['attachments'] = $db->run("SELECT * FROM ai_attachment WHERE messageId = ?", $conversation['messages'][$i]['prompt']['id']);
                        $i++;
                    }
                } else {
                    session_start();
                    $_SESSION['error'] = "You did not start that conversation";
        
                    header('Location: '.URL_APP_ADMIN."/?page=ai&view=$view");
                    exit;
                }
            }

            $i = 0;
            $conversations = $db->run("SELECT * FROM ai_conversation WHERE createdBy = ? ORDER BY id DESC", $user['id']);
            foreach ( $conversations as $key => $value ) {
                $conversations[$i]['message'] = $db->cell("SELECT text FROM ai_message WHERE conversationId = ? ORDER BY createdAt ASC LIMIT 0,1", $conversations[$i]['id']);
                $conversations[$i]['messageCount'] = $db->cell("SELECT COUNT(text) FROM ai_message WHERE conversationId = ?", $conversations[$i]['id']);
                $i++;
            }

            $toolbar  = 'toolbar-ai.php';
            $template = 'ai-console.php';
            break;
        case 'p' :
            $toolbar  = 'toolbar-projects.php';
            $projects = $db->run("SELECT * FROM project ORDER BY id ASC");

            $completed = [];
            foreach ( $projects as $key => $project ) {
                $stmt = $pdo->prepare("SELECT client.id, client.userId, client.email, client.createdBy, client.createdAt, user.name FROM client, client_project, user WHERE client_project.projectId = ? AND client_project.clientId = client.id AND client.userId = user.id ORDER BY user.name ASC;");
                $exec = $stmt->execute([$project['id']]);

                $projects[$key]['clients']    = $stmt->fetchAll(\PDO::FETCH_ASSOC);
                $projects[$key]['webhook']    = $db->row("SELECT * FROM webhook WHERE projectId = ?", $project['id']);
                $projects[$key]['attachment'] = $db->row("SELECT * FROM attachment WHERE projectId = ? AND (mimeType = 'image/jpeg' OR mimeType = 'image/png') ORDER BY createdAt DESC LIMIT 0,1", $project['id']);

                $stmt = $pdo->prepare("SELECT user.id, user.name FROM user, project_email_notification WHERE project_email_notification.projectId = ? AND project_email_notification.userId = user.id ORDER BY user.name ASC;");
                $exec = $stmt->execute([$project['id']]);

                $projects[$key]['notifications'] = $stmt->fetchAll(\PDO::FETCH_ASSOC);
                $clientUsers                     = $db->run("SELECT * FROM user WHERE clientId > 0 ORDER BY id ASC");

                $projects[$key]['plan'] = $db->row("SELECT * FROM plan WHERE projectId = ? LIMIT 0,1", $project['id']);

                if ( $projects[$key]['status'] === 'Completed' ) {
                    $completed[] = $projects[$key];
                    unset($projects[$key]);
                }
            }

            $projects = array_merge($projects, $completed);
            // echo "<pre>"; print_r($projects); echo "</pre>";
            // echo "<pre>"; print_r($completed); echo "</pre>";

            $template = ( $view === 't' )
                ? 'projects-table-test.php'
                : 'projects-cards.php'
            ;

            break;
        case 'c' :
            $toolbar  = 'toolbar-clients.php';
            $projects = $db->run("SELECT * FROM project");
            $clients  = $db->run("SELECT * FROM client ORDER BY id ASC");
            foreach ( $clients as $key => $client ) {
                $clients[$key]['user'] = $db->row("SELECT * FROM user WHERE id = ?", $client['userId']);
            }

            $template = ( $view === 't' )
                ? 'clients-table-test.php'
                : 'clients-cards.php'
            ;

            break;
        case 'u' :
            if ( !$user['superAdmin'] ) {
                session_start();
                $_SESSION['error'] = "Unauthorized";

                header('Location: '.URL_APP_ADMIN."/?page=p&view=$view");
                exit;
            }

            $toolbar       = 'toolbar-users.php';
            $viewOnlyUsers = $db->run("SELECT * FROM user WHERE clientId = 0 ORDER BY id ASC");

            $template = ( $view === 't' )
                ? 'users-table-test.php'
                : 'users-cards.php'
            ;

            break;
        case 'w' :
            if ( !$user['superAdmin'] ) {
                session_start();
                $_SESSION['error'] = "Unauthorized";

                header('Location: '.URL_APP_ADMIN."/?page=p&view=$view");
                exit;
            }

            $toolbar  = 'toolbar-webhooks.php';
            $webhooks = $db->run("SELECT * FROM webhook");

            $template = ( $view === 't' )
                ? 'webhooks-table-test.php'
                : 'webhooks-cards.php'
            ;

            break;
        case 'pp' :
            if ( !$user['superAdmin'] ) {
                session_start();
                $_SESSION['error'] = "Unauthorized";

                header('Location: '.URL_APP_ADMIN."/?page=p&view=$view");
                exit;
            }

            $toolbar  = 'toolbar-public-projects.php';

            $projects = $db->run("SELECT * FROM project");

            $publicProjects = $db->run("SELECT * FROM public_project");

            $i = 0;
            foreach ( $publicProjects as $publicProject ) {
                $publicProjects[$i]['shares'] = $db->run("SELECT share.id, share.uri, share.note, share.createdBy, share.createdAt, share.expiresAt FROM share, public_project_share WHERE share.id = public_project_share.shareId AND public_project_share.publicProjectId = ?", $publicProject['id']);
                if ( $publicProject['projectId'] ) {
                    $publicProjects[$i]['project'] = $db->row("SELECT * FROM project WHERE id = ?", $publicProject['projectId']);
                }
                $i++;
            }

            $shares = $db->run("SELECT * FROM share");

            $i = 0;
            foreach ( $shares as $share ) {
                $shares[$i]['publicProjects'] = $db->run("SELECT public_project.id, public_project.projectId, public_project.title, public_project.status, public_project.city, public_project.value, public_project.type FROM public_project, public_project_share WHERE public_project.id = public_project_share.publicProjectId AND public_project_share.shareId = ?", $share['id']);
                $shares[$i]['user'] = $db->row("SELECT * FROM user WHERE id = ?", $share['createdBy']);
                $i++;
            }

            $template = ( $view === 't' )
                ? 'public-projects-table-test.php'
                : 'public-projects-cards.php'
            ;
            break;
        default :
            break;
    }

    include 'layout/header.php'; 
?>

<style>
</style>

<div class="container-fluid px-0">
    <?php
        // if ( $user['email'] === 'lambo117@gmail.com' )
        //     include "template/$toolbar";
        // else
            include "template/toolbar.php";
    ?>
</div>

<?php if ( $error ) : ?>
    <div class="container-fluid container-lg">
        <div class="alert alert-warning alert-dismissible fade show mb-md-0" role="alert">
            <?php echo $error; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    </div>
<?php endif; ?>

<div id="main" class="container-fluid container-lg">
    <?php include 'template/navigation-md.php'; ?>
    <?php include "template/$template"; ?>
</div>

<?php // include 'template/navigation-sm.php'; ?>

<!-- <div id="" style="min-height:85px;"></div> -->

<?php 
    if ( $user['superAdmin'] ) {
        include 'template/new-project-modal.php'; 
        include 'template/edit-project-modal.php'; 
        
        include 'template/new-user-modal.php'; 
        include 'template/edit-user-modal.php'; 
        
        include 'template/new-client-modal.php'; 
        include 'template/edit-client-modal.php'; 
        
        include 'template/user-logs-modal.php';
        include 'template/share-logs-modal.php';

        include 'template/send-token-modal.php'; 

        include 'template/new-public-project-modal.php';
        include 'template/edit-public-project-modal.php';

        include 'template/new-public-project-share-modal.php';
        include 'template/edit-public-project-share-modal.php';

        include 'template/selection-sheet-modal.php';
    }

    include 'template/client-logs-modal.php';

    include 'layout/footer.php';
?>