<?php
/**
 * @package    Proxim
 * @author     Mike Kivu <mikepaul620@gmail.com | https://webexpert.co.ke>
 * @copyright  2019 Proxim
 * @version    1.5.0
 * @since      File available since Release 1.0.0
 * 
 ____  ____   __  _  _  __  _  _ 
(  _ \(  _ \ /  \( \/ )(  )( \/ )
 ) __/ )   /(  O ))  (  )( / \/ \
(__)  (__\_) \__/(_/\_)(__)\_)(_/
*/

require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'bootstrap.php';

// Routes which do not need protection by the authentication and the request
// @TODO: Move this to a middleware
$authRouteWhitelist = [
    'auth_register',
    'auth_login',
    'auth_logout',
    'auth_reset_password',
    'auth_reset_session',
    'theme',
    'fileDownload',
    'authorizeGhostAdmin'
];

$app->hook('slim.before.dispatch', function () use ($app, $authRouteWhitelist, $user, $smarty) {
    $routeName = $app->router()->getCurrentRoute()->getName();
    $controller = $app->container->controller;

	/** Skip routes which don't require these protections */
    if (!in_array($routeName, $authRouteWhitelist)) {
        /** Enforce required authentication. */
        if ($user->isLogged()) {

            if (!$user->is_started) {
                $controller->setTemplate('dashboard/account-started');
                $controller->display();
                return $app->stop();
            }

            if ($user->is_banned) {
                $controller->setTemplate('dashboard/account-disabled');
                $controller->display();
                return $app->stop();
            }   
        
        } else {
            $smarty->assign([
                'do' => 'in',
                'highlight' => 'You must sign in to see this page'
            ]);

            $controller->setVars([
                'page' => [
                    'title' => "Sign in",
                ],
            ]);
            $controller->setTemplate('dashboard/sign');
            $controller->display();
            return $app->stop();
        }
    }
});

/**
 * Request Payload
 */
$params = $app->request->get();
$requestPayload = $app->request->post();

$app->get('/?', '\Proxim\Dashboard\Auth:login')->name('auth_login');
$app->get('/signin?', '\Proxim\Dashboard\Auth:login')->name('auth_login');
$app->get('/login?', '\Proxim\Dashboard\Auth:login')->name('auth_login');
$app->get('/signup?', '\Proxim\Dashboard\Auth:signup')->name('auth_register');
$app->get('/forgot-password?', '\Proxim\Dashboard\Auth:forgotPassword')->name('auth_reset_password');
$app->get('/reset/:reset_key?', '\Proxim\Dashboard\Auth:resetPassword')->name('auth_reset_password');

$app->get('/authorize/:employeeId/:authKey?', '\Proxim\Dashboard\Auth:authorize')->name('authorize');
$app->get('/authorize/ghostadmin?', '\Proxim\Dashboard\Auth:authorizeGhostAdmin')->name('authorizeGhostAdmin');

# logout
$app->get('/logout', function () use ($app, $user) {
	$user->logout();
    $app->redirect('/');
})->name('auth_logout');

# notifications
$app->get('/notifications?', '\Proxim\Dashboard\Notifications:getNotifications');

#Orders
$app->get('/orders?', '\Proxim\Dashboard\Orders:getOrders');
$app->get('/orders/create?', '\Proxim\Dashboard\Orders:createOrder');
$app->get('/orders/:status?', '\Proxim\Dashboard\Orders:getOrders');
$app->get('/orders/:user_group/:user_id?', '\Proxim\Dashboard\Orders:getUserOrders');
$app->get('/order/:orderId?', '\Proxim\Dashboard\Orders:getOrder');
$app->get('/order/:orderId/edit?', '\Proxim\Dashboard\Orders:editOrder');
$app->get('/order/:orderId/:sub_view?', '\Proxim\Dashboard\Orders:getOrder');

#Profile
$app->get('/profile?', '\Proxim\Dashboard\Profile:profile');

#Feedback
$app->get('/feedback?', '\Proxim\Dashboard\Feedback:index');
$app->get('/feedback/:feedbackId?', '\Proxim\Dashboard\Feedback:viewFeedback');

#financial overview
$app->get('/financial-overview?', '\Proxim\Dashboard\Payments:financialOverview');
$app->get('/financial-overview/:sub_view?', '\Proxim\Dashboard\Payments:financialOverview');

#payments
$app->get('/payments?', '\Proxim\Dashboard\Payments:payments');
$app->get('/payments/:sub_view?', '\Proxim\Dashboard\Payments:payments');

#mailing
$app->get('/mailing?', '\Proxim\Dashboard\Mailing:mailing');
$app->get('/mailing/:sub_view?', '\Proxim\Dashboard\Mailing:mailing');
$app->get('/mailing/:sub_view/:id?', '\Proxim\Dashboard\Mailing:mailing');

#users
$app->group('/customers', function () use ($app) {
    $app->get('/?', '\Proxim\Dashboard\Admin:customers');
    $app->get('/:sub_view?', '\Proxim\Dashboard\Admin:customers');
    $app->get('/:sub_view/:customer_id?', '\Proxim\Dashboard\Admin:customers');
});

$app->group('/employees', function () use ($app) {
    $app->get('/:sub_view?', '\Proxim\Dashboard\Admin:employees');
    $app->get('/:sub_view/:employee_id?', '\Proxim\Dashboard\Admin:employees');
});

#coupons
$app->get('/coupons?', '\Proxim\Dashboard\Admin:coupons');
$app->get('/coupons/:sub_view?', '\Proxim\Dashboard\Admin:coupons');
$app->get('/coupons/:sub_view/:currency_id?', '\Proxim\Dashboard\Admin:coupons');

# sites
$app->get('/my-sites?', '\Proxim\Dashboard\MySites:viewSites');
$app->get('/my-sites/add?', '\Proxim\Dashboard\MySites:addSite');
$app->get('/my-sites/:site_id?', '\Proxim\Dashboard\MySites:site');
$app->get('/my-sites/:site_id/:sub_view?', '\Proxim\Dashboard\MySites:site');

# deadlines
$app->get('/deadlines?', '\Proxim\Dashboard\MySites:site');
$app->get('/deadlines/:sub_view?', '\Proxim\Dashboard\MySites:site');

# modules
$app->get('/modules?', '\Proxim\Dashboard\Modules:listModules');
$app->get('/modules/install?', '\Proxim\Dashboard\Modules:installModules');
$app->get('/modules/purchase/:moduleName?', '\Proxim\Dashboard\Modules:purchaseModule');

# updates
$app->get('/updates?', '\Proxim\Dashboard\Updates:index');

$app->group('/system', function () use ($app) {
    #system
    $app->get('/settings?', '\Proxim\Dashboard\Admin:settings');

     #uploads
     $app->get('/uploads?', '\Proxim\Dashboard\Admin:uploads');

    #payments 
    $app->get('/payments?', '\Proxim\Dashboard\Admin:payments');

    # currency
    $app->get('/currency?', '\Proxim\Dashboard\Admin:currency');
    $app->get('/currency/:sub_view?', '\Proxim\Dashboard\Admin:currency');
    $app->get('/currency/:sub_view/:currency_id?', '\Proxim\Dashboard\Admin:currency');

    #preferences
    $app->group('/preferences', function () use ($app) {
        $app->get('/?', '\Proxim\Dashboard\Customize:paperTypes');
        $app->get('/paper-types?', '\Proxim\Dashboard\Customize:paperTypes');
        $app->get('/disciplines?', '\Proxim\Dashboard\Customize:disciplines');
        $app->get('/paper-formats?', '\Proxim\Dashboard\Customize:paperFormats');
        $app->get('/upload-types?', '\Proxim\Dashboard\Customize:uploadTypes');
    });
});

$app->group('/api', function () use ($app) {
    # auth
    $app->post('/signin?', '\Proxim\Api\Auth:signin')->name('auth_login');
    $app->post('/signup?', '\Proxim\Api\Auth:signup')->name('auth_register');
    $app->post('/reset-password?', '\Proxim\Api\Auth:resetPassword')->name('auth_reset_password');
    $app->post('/forget-password-confirm?', '\Proxim\Api\Auth:changePassword')->name('auth_reset_password');

    $app->get('/ifs/download/:fileId?', '\Proxim\Api\Files:downloadFile')->name('fileDownload');

    # order
    $app->post('/order?', '\Proxim\Api\Orders:createOrder');

    #orders
    $app->group('/orders', function () use ($app) {
        #files
        $app->post('/:order_id/upload_files', '\Proxim\Api\Orders:uploadFiles');
        $app->get('/:order_id/download_all_attachments?', '\Proxim\Api\Files:downloadAllAttachments');

        $app->post('/:order_id?', '\Proxim\Api\Orders:order');
        $app->post('/:order_id/:do?', '\Proxim\Api\Orders:order');
    });

    #messages
    $app->group('/messages', function () use ($app) {
        $app->post('/send?', '\Proxim\Api\Orders:sendMessage');
        $app->post('/:id/reply?', '\Proxim\Api\Orders:replyMessage');
        $app->post('/:id/read?', '\Proxim\Api\Orders:readMessage');
    });

    #files
    $app->group('/files', function () use ($app) {
        $app->get('/:file_id/download?', '\Proxim\Api\Files:downloadFile');
        $app->post('/upload?', '\Proxim\Api\Files:uploadFiles');
    });

    #feedback
    $app->group('/feedback', function () use ($app) {
        $app->post('/:feedback_id/reply?', '\Proxim\Api\Orders:feedbackReply');
    });

    #profile
    $app->post('/user/settings?', '\Proxim\Api\Profile:editProfile');
    $app->get('/user/settings?', '\Proxim\Api\Profile:editProfile');
    $app->post('/user/remove-picture?', '\Proxim\Api\Profile:removePicture');
    
    #request payment
    $app->post('/user/request-payment?', '\Proxim\Api\Profile:requestPayment');
    $app->get('/user/payment-requests/:request_id?', '\Proxim\Api\Admin:getPaymentRequestOrders');
    
    #users 
    $app->post('/customers?', '\Proxim\Api\Admin:customers');
    $app->post('/employees/:do?', '\Proxim\Api\Admin:employees');

    # auth
    $app->post('/theme?', '\Proxim\Api\Profile:setTheme')->name('theme');

    $app->post('/modules/upload?', '\Proxim\Api\Modules:uploadPlugin');

    # admin
    $app->group('/admin', function () use ($app) {
        # modules
        $app->post('/modules?', '\Proxim\Api\Modules:doAction');

        # bulk actions
        $app->post('/bulk-actions?', '\Proxim\Api\Admin:bulkActions');

        #mailing
        $app->post('/mailing?', '\Proxim\Api\Admin:mailing');

        #delete
        $app->post('/delete?', '\Proxim\Api\Admin:delete');

        #settings
        $app->post('/settings?', '\Proxim\Api\Admin:settings');
        
        #sites
        $app->post('/sites?', '\Proxim\Api\MySites:updateSettings');

        #currency
        $app->post('/currency?', '\Proxim\Api\Admin:currency');
        #coupon
        $app->post('/coupon?', '\Proxim\Api\Admin:coupon');
        #test
        $app->post('/test?', '\Proxim\Api\Admin:test');

        #withdraw
        $app->post('/withdraw?', '\Proxim\Api\Admin:withdraw');

        # password reset link
        $app->post('/password-reset-link?', '\Proxim\Api\Admin:generateResetLink');
    });

    #preferences
    $app->post('/preferences?', '\Proxim\Api\Customize:index');

    #data
    $app->group('/data', function () use ($app) {
        $app->post('/live?', '\Proxim\Api\Updates:getLiveData');
        $app->post('/reset?', '\Proxim\Api\Updates:reset');
        $app->post('/load?', '\Proxim\Api\Updates:load');

        #upload
        $app->post('/upload?', '\Proxim\Api\Files:dataUpload');
    });

    $app->post('/:module_name/:controller?', '\Proxim\Dashboard\Modules:initModule');
});

$app->get('/:module_name?', '\Proxim\Dashboard\Modules:initModule');
$app->get('/:module_name/:controller?', '\Proxim\Dashboard\Modules:initModule');

$app->notFound(function () use ($app) {
    $app->response->status(404);
    if ($app->request->isAjax()) {
        $app->response()->header('Content-Type', 'application/json; charset=utf-8');
        $app->response([
            "error" => true,
            "message" => "Error 404. Resource not found"
        ]);
    } else {
        $app->response()->header('Content-Type', 'text/html; charset=utf-8');
        $html = $app->container->smarty->fetch('404.tpl');
        echo trim($html);
    }
    
    return $app->stop();
});

// Run Slim
$app->response()->header('Content-Type', 'application/json; charset=utf-8');
$app->run();