<?php
session_start();
require_once '../models/Settings.php';
require_once '../include/DatabaseConn.php';
require_once '../include/Constants.php';
require_once '../models/Investment.php';
require_once '../models/Admin.php';

$db = new DatabaseConn();
$link = $db->connect();

$admin = Admin::getCurrentAdmin();

if (is_null($admin)) {
    $url = $_SERVER['REQUEST_URI'];
    header("location: ./login?" . RETURN_URL . "=" . $url);
    die();
}

if (isset($_POST['name'])) {
    $name = filter_input(INPUT_POST, 'name');
    if (is_null($name) || is_bool($name) || empty($name) || strcmp($name, NONE) == 0) {
        $error = "Package Name is not valid";
    }
    $percentage = filter_input(INPUT_POST, 'percentage', FILTER_VALIDATE_FLOAT);
    if (is_null($percentage) || is_bool($percentage) || empty($percentage) || $percentage <= 0) {
        $error = "ROI is not valid";
    }
    $days = filter_input(INPUT_POST, 'days', FILTER_VALIDATE_INT);
    if (is_null($days) || is_bool($days) || empty($days) || $days < 0) {
        $error = "Enter a valid trading duration";
    }
    $type = filter_input(INPUT_POST, 'type');
    if (is_null($type) || is_bool($type) || empty($type) || strcmp($type, NONE) == 0) {
        $error = "Investment Type is not valid";
    }
    $min = filter_input(INPUT_POST, 'min');
    if (is_null($min) || is_bool($min) || empty($min) || $min <= 0) {
        $error = "Minimum investment is not valid";
    }
    $unlimited = filter_input(INPUT_POST, 'unlimited');
    if (is_null($unlimited)) {
        $max = filter_input(INPUT_POST, 'max');
        if (is_null($max) || is_bool($max) || empty($max) || $max <= 0 || $max <= $min) {
            $error = "Maximum investment is not valid";
        }
    } else {
        $max = -1;
    }
    $group = filter_input(INPUT_POST, 'group');
    if (is_null($group) || is_bool($group) || empty($group)) {
        $error = "Investment group is not valid";
    } else if (strcmp($group, NONE) == 0) {
        $group = null;
    }
    if (!isset($error)) {

        if (is_null($group)) {
            mysqli_query($link, "insert into investment(`name`,percentage,`type`,`min`,`max`,igroup,`days`) VALUES('$name','$percentage','$type',$min,$max,null,$days)");
        } else {
            mysqli_query($link, "insert into investment(`name`,percentage,`type`,`min`,`max`,igroup,`days`) VALUES('$name','$percentage','$type',$min,$max,'$group', $days)");
        }
        if (mysqli_affected_rows($link) > 0) {
            $success = "Investment plan has been added";
        } else {
            $error = mysqli_error($link);
        }
    }
} else if (isset($_POST['id_'])) {
    $name_ = filter_input(INPUT_POST, 'name_');
    if (is_null($name_) || is_bool($name_) || empty($name_) || strcmp($name_, NONE) == 0) {
        $error = "Package Name is not valid";
    }
    $id_ = filter_input(INPUT_POST, 'id_');
    if (is_null($id_) || is_bool($id_) || empty($id_)) {
        $error = "Token missing";
    }
    $percentage_ = filter_input(INPUT_POST, 'percentage_', FILTER_VALIDATE_FLOAT);
    if (is_null($percentage_) || is_bool($percentage_) || empty($percentage_) || $percentage_ <= 0) {
        $error = "ROI is not valid";
    }
    $days_ = filter_input(INPUT_POST, 'days_', FILTER_VALIDATE_INT);
    if (is_null($days_) || is_bool($days_) || empty($days_) || $days_ < 0) {
        $error = "Trading duration is not valid";
    }
    $type_ = filter_input(INPUT_POST, 'type_');
    if (is_null($type_) || is_bool($type_) || empty($type_) || strcmp($type_, NONE) == 0) {
        $error = "Investment Type is not valid";
    }
    $min_ = filter_input(INPUT_POST, 'min_');
    if (is_null($min_) || is_bool($min_) || empty($min_) || $min_ <= 0) {
        $error = "Minimum investment is not valid";
    }
    $unlimited_ = filter_input(INPUT_POST, 'unlimited_');
    if (is_null($unlimited_)) {
        $max_ = filter_input(INPUT_POST, 'max_');
        if (is_null($max_) || is_bool($max_) || empty($max_) || $max_ <= 0 || $max_ <= $min_) {
            $error = "Maximum investment is not valid";
        }
    } else {
        $max_ = -1;
    }
    $group_ = filter_input(INPUT_POST, 'group_');
    if (is_null($group_) || is_bool($group_) || empty($group_)) {
        $error = "Investment group is not valid";
    } else if (strcmp($group_, NONE) == 0) {
        $group_ = null;
    }
    if (!isset($error)) {
        if (is_null($group_)) {
            mysqli_query($link, "update investment set `name` = '$name_', percentage = '$percentage_', `type` = '$type_', `min` = $min_, `max` = $max_, igroup = null, `days` = $days_ where id = $id_");
        } else {
            mysqli_query($link, "update investment set `name` = '$name_', percentage = '$percentage_', `type` = '$type_', `min` = $min_, `max` = $max_, igroup = '$group_', `days` = $days_ where id = $id_");
        }

        if (mysqli_affected_rows($link) > 0) {
            $success = "Investment plan has been updated";
        } else {
            $error = "No fields were modified!";
        }
    }
} else if (isset($_POST['delete'])) {
    $emails = filter_input(INPUT_POST, 'delete');
    $emails = json_decode($emails);
    foreach ($emails as $value) {
        Investment::deleteInvestment($value, $link);
    }
    $success = "Investment plan has been deleted";
}

$settings = Settings::getSystemSettings($link);
$investments = Investment::getInvesments($link);
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <?php require_once './partials/head.php'; ?>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.1/animate.min.css" />
        <link href="../css/snackbar.min.css" rel="stylesheet" type="text/css" />
        <style>
            ul{margin:0;padding:0;list-style:none}::-webkit-scrollbar{background:0 0;width:3px;height:6px}::-webkit-scrollbar-thumb{background:rgba(0,0,0,.07);border:solid rgba(88,88,88,.12) 2px;border-radius:5px}thead tr th{padding:8px 15px!important}thead th{color:#758696;font-size:13px;font-weight:600;border:0!important}tbody tr{color:#4a4a4a}tbody tr:hover{background:#f6f8f9}.form-control{border-radius:5px}.table td,.table th{border-top:1px solid #f0f3fa}.form-control::-webkit-input-placeholder{color:#18214d59}.form-control::-moz-placeholder{color:#18214d59}.form-control:-ms-input-placeholder{color:#18214d59}.form-control:-moz-placeholder{color:#18214d59}.custom-control-input:focus~.custom-control-label::before{box-shadow:none}.table{margin-bottom:0}.table td{font-size:13px;padding:10px 18px}.settings-profile .col-md-6{margin-bottom:20px}.settings-profile input{border:1px solid #e0e3eb;border-radius:5px;font-size:14px;height:45px}.settings-profile input[type=submit]{background:#007bff;color:#fff;font-weight:600;padding:10px 25px;height:inherit;font-size:16px;margin-top:10px}.settings-notification li{display:flex;justify-content:space-between;padding:15px 0;border-bottom:1px solid #f0f3fa;align-items:center}.settings-notification li:first-child{padding-top:0}.settings-notification li:last-child{padding-bottom:0;border-bottom:0}.settings-notification li span{color:#18214d59}.settings-notification li p{margin-bottom:0}.wallet-history .ion-md-trash{font-size:16px;cursor:pointer}.wallet-history{overflow-x:auto}
        </style>
        <link href="../css/form.css" rel="stylesheet" type="text/css" />
    </head>
    <body id="dark">

        <div id="app">
            <?php require_once './partials/top-header.php'; ?>
            <!--  BEGIN MAIN CONTAINER  -->
            <div class="main-container" id="container">
                <div class="overlay"></div>
                <div class="search-overlay"></div>
                <?php require_once './partials/side-bar.php'; ?>
                <!--  BEGIN CONTENT AREA  -->
                <div id="content" class="main-content">
                    <div class="layout-px-spacing">
                        <div class="row layout-top-spacing layout-spacing">
                            <div class="col-lg-12">
                                <div class="statbox widget box box-shadow">
                                    <div class="widget-content widget-content-area">
                                        <div class="table-responsive mb-4 style-1">
                                            <table id="style-1" class="table style-1 table-hover non-hover">
                                                <thead>
                                                    <tr>
                                                        <th>Name</th>
                                                        <th>Percentage</th>
                                                        <th>Investment Type</th>
                                                        <th>Minimum Amount</th>
                                                        <th>Maximum Amount</th>
                                                        <th>Trading Days</th>
                                                        <th>Investment Group</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    if (!is_null($investments)) {
                                                        foreach ($investments as $investment) {
                                                            ?>
                                                            <tr data-investment="<?php echo "{$investment->getId()}"; ?>">
                                                                <td class="wallet-name"> <?php echo "{$investment->getName()}"; ?></td>
                                                                <td class="wallet-name"> <?php echo "{$investment->getPercentage()}"; ?></td>
                                                                <td class="wallet-name"> <?php echo "{$investment->getType()}"; ?></td>
                                                                <td class="wallet-name"><?php echo "{$investment->getMin()}"; ?></td>
                                                                <td class="wallet-name"><?php echo $investment->getMax(); ?></td>
                                                                <td class="wallet-name"><?php echo $investment->getDays(); ?></td>                                                                <td class="wallet-name"><?php
                                                                    if (is_null($investment->getIgroup())) {
                                                                        echo "Not set";
                                                                    } else {
                                                                        echo "{$investment->getIgroup()}";
                                                                    }
                                                                    ?></td>
                                                                <td class="text-center">
                                                                    <div class="dropdown custom-dropdown">
                                                                        <a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                                                                            <svg
                                                                                xmlns="http://www.w3.org/2000/svg"
                                                                                width="24"
                                                                                height="24"
                                                                                viewBox="0 0 24 24"
                                                                                fill="none"
                                                                                stroke="currentColor"
                                                                                stroke-width="2"
                                                                                stroke-linecap="round"
                                                                                stroke-linejoin="round"
                                                                                class="feather feather-more-horizontal"
                                                                                >
                                                                            <circle cx="12" cy="12" r="1"></circle>
                                                                            <circle cx="19" cy="12" r="1"></circle>
                                                                            <circle cx="5" cy="12" r="1"></circle>
                                                                            </svg>
                                                                        </a>

                                                                        <div class="dropdown-menu" aria-labelledby="dropdownMenuLink1">
                                                                            <a class="dropdown-item edit-investment cursor" data-id="<?php echo $investment->getId(); ?>"
                                                                               data-package="<?php echo $investment->getName(); ?>" data-percentage="<?php echo $investment->getPercentage(); ?>"
                                                                               data-type="<?php echo $investment->getType(); ?>" data-min="<?php echo $investment->getMin(); ?>"
                                                                               data-max="<?php echo $investment->getMax(); ?>" data-days="<?php echo $investment->getDays(); ?>" data-group="<?php echo $investment->getIgroup(); ?>">Edit</a>
                                                                            <a class="dropdown-item cursor" onclick="delete_({emails: '<?php echo "{$investment->getId()}"; ?>'})">Delete</a>
                                                                        </div>

                                                                    </div>
                                                                </td>
                                                            </tr>
                                                            <?php
                                                        }
                                                    }
                                                    ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>

                                </div>
                                <div class="statbox widget box box-shadow" style="margin-top: 20px">
                                    <div class="card settings-profile" >
                                        <div class="card-body">
                                            <h5 class="card-title">Add Investment Option</h5>
                                            <form method="post" action="investment">
                                                <div class="form-row">
                                                    <div class="col-md-6">
                                                        <label for="generateKey">Package Name</label>
                                                        <input id="generateKey" name="name" type="text" class="form-control" placeholder="Package Name">
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label for="rewritePassword">Percentage</label>
                                                        <input id="rewritePassword" name="percentage" type="text" class="form-control" placeholder="Percentage (ROI)">
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label for="rewritePassword">Trade duration</label>
                                                        <input id="generateKey" name="days" type="text" class="form-control" placeholder="Enter the number of days for this trade">
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label for="rewritePassword">Investment Type</label>
                                                        <select class='placeholder js-states form-control' required id="list"
                                                                name="type">
                                                            <option selected value="<?php echo DAILY; ?>">Daily</option>
                                                            <option value="<?php echo WEEKLY; ?>">Weekly</option>
                                                            <option value="<?php echo BI_WEEKLY; ?>">Bi-Weekly</option>
                                                            <option value="<?php echo MONTHLY; ?>">Monthly</option>
                                                        </select>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label for="rewritePassword">Minimum Amount</label>
                                                        <input id="generateKey" name="min" type="text" class="form-control" placeholder="Minimum Amount">
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label for="rewritePassword">Maximum Amount</label>
                                                        <input id="max" name="max" type="text" class="form-control" placeholder="Maxmium Amount">
                                                        <input type="checkbox" value="on" style="vertical-align: middle" name="unlimited" class="new-control-input child-chk select-customers-info" id="u">
                                                        <label style="vertical-align: middle" class="new-control new-checkbox checkbox-outline-primary  m-auto">
                                                            Unlimited
                                                        </label>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label for="rewritePassword">Investment Groups</label>
                                                        <select class='placeholder js-states form-control' required id="list"
                                                                name="group">
                                                            <option selected value="<?php echo NONE; ?>"><?php echo NONE; ?></option>
                                                            <?php
                                                            $groups = Investment::getInvesmentGroup($link);
                                                            if (!is_null($groups)) {
                                                                foreach ($groups as $group) {
                                                                    ?>
                                                                    <option value="<?php echo $group->getName(); ?>"><?php echo $group->getName(); ?></option>
                                                                    <?php
                                                                }
                                                            }
                                                            ?>
                                                        </select>
                                                    </div>

                                                    <div class="col-md-12" >
                                                        <input type="submit" value="Save">
                                                    </div>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php require_once './partials/footer.php'; ?>
                </div>
                <!--  END CONTENT AREA  -->
            </div>
        </div>
        <!-- END MAIN CONTAINER -->
        <div class="modal fade login-modal" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel"  aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header" id="loginModalLabel">
                        <h4 class="modal-title">Edit Investment</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                            <svg
                                aria-hidden="true"
                                xmlns="http://www.w3.org/2000/svg"
                                width="24"
                                height="24"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                stroke-width="2"
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                class="feather feather-x"
                                >
                            <line x1="18" y1="6" x2="6" y2="18"></line>
                            <line x1="6" y1="6" x2="18" y2="18"></line>
                            </svg>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form method="post" action="investment">
                            <div class="form-row">
                                <div class="col-md-6">
                                    <input type="hidden" name="id_"  />
                                    <label for="generateKey">Package Name</label>
                                    <input id="generateKey" name="name_" type="text" class="form-control" placeholder="Package Name">
                                </div>
                                <div class="col-md-6">
                                    <label for="rewritePassword">Percentage</label>
                                    <input id="rewritePassword" name="percentage_" type="text" class="form-control" placeholder="Percentage (ROI)">
                                </div>
                                <div class="col-md-6">
                                    <label for="rewritePassword">Investment Type</label>
                                    <select class='placeholder js-states form-control' required id="list"
                                            name="type_">
                                        <option value="<?php echo DAILY; ?>">Daily</option>
                                        <option value="<?php echo WEEKLY; ?>">Weekly</option>
                                        <option value="<?php echo BI_WEEKLY; ?>">Bi-Weekly</option>
                                        <option value="<?php echo MONTHLY; ?>">Monthly</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label for="rewritePassword">Trade duration</label>
                                    <input id="generateKey" name="days_" type="text" class="form-control" placeholder="Enter the number of days for this trade">
                                </div>
                                <div class="col-md-6">
                                    <label for="rewritePassword">Minimum Amount</label>
                                    <input id="generateKey" name="min_" type="text" class="form-control" placeholder="Minimum Amount">
                                </div>
                                <div class="col-md-6">
                                    <label for="rewritePassword">Maximum Amount</label>
                                    <input id="max" name="max_" type="text" class="form-control" placeholder="Maxmium Amount">
                                    <input type="checkbox" value="on" style="vertical-align: middle" name="unlimited_" class="new-control-input child-chk select-customers-info" id="u">
                                    <label style="vertical-align: middle" class="new-control new-checkbox checkbox-outline-primary  m-auto">
                                        Unlimited
                                    </label>
                                </div>
                                <div class="col-md-6">
                                    <label for="rewritePassword">Investment Groups</label>
                                    <select class='placeholder js-states form-control' required id="list"
                                            name="group_">
                                        <option value="<?php echo NONE; ?>"><?php echo NONE; ?></option>
                                        <?php
                                        $groups = Investment::getInvesmentGroup($link);
                                        if (!is_null($groups)) {
                                            foreach ($groups as $group) {
                                                ?>
                                                <option value="<?php echo $group->getName(); ?>"><?php echo $group->getName(); ?></option>
                                                <?php
                                            }
                                        }
                                        ?>
                                    </select>
                                </div>
                                <div class="col-md-12 settings-profile">
                                    <input type="submit" value="Save">
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <?php require_once './partials/scripts.php'; ?>
        <script src="../js/snackbar.min.js" type="text/javascript"></script>
        <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
        <script>
                                                                        $("#u").change(function () {
                                                                            $('#max').val("");
                                                                            $("#max").toggle(function () {
                                                                                $(this).attr("disabled", "true");
                                                                            }, function () {
                                                                                $(this).removeAttr("disabled");
                                                                            });
                                                                        });
                                                                        function delete_(emails) {
                                                                            var form = document.createElement("form");
                                                                            form.setAttribute('method', "post");
                                                                            form.setAttribute('action', "investment");

                                                                            var i = document.createElement("input"); //input element, text
                                                                            i.setAttribute('type', "hidden");
                                                                            i.setAttribute('name', "delete");
                                                                            i.setAttribute('value', JSON.stringify(emails));

                                                                            form.appendChild(i);
                                                                            document.getElementsByTagName('body')[0].appendChild(form);

                                                                            $(form).trigger("submit");
                                                                        }
                                                                        $('.edit-investment').click(function () {

                                                                            $("input[name='name_']").val($(this).attr("data-package"));
                                                                            $("input[name='name_a']").val($(this).attr("data-package"));
                                                                            $("input[name='percentage_']").val($(this).attr("data-percentage"));
                                                                            $("input[name='days_']").val($(this).attr("data-days"));

                                                                            let query = "select[name='type_'] option[value='" + $(this).attr("data-type") + "']";
                                                                            $(query).prop('selected', true);

                                                                            let query2 = "select[name='group_'] option[value='" + $(this).attr("data-group") + "']";
                                                                            (!$(this).attr("data-group")) ? $("select[name='group_'] option:first-child").prop('selected', true) : $(query2).prop('selected', true);

                                                                            $("input[name='min_']").val($(this).attr("data-min").replace(/\,/g, ''));

                                                                            if ($(this).attr("data-max") == "unlimited") {
                                                                                $("input[name='unlimited_']").prop("checked", true);
                                                                                $("input[name='max_']").val("");
                                                                            } else {
                                                                                $("input[name='max_']").val($(this).attr("data-max").replace(/\,/g, ''));
                                                                                $("input[name='unlimited_']").prop("checked", false);
                                                                            }
                                                                            $("input[name='max_']").keydown(function () {
                                                                                $("input[name='unlimited_']").prop("checked", false);
                                                                            });

                                                                            $("input[name='id_']").val($(this).attr("data-id"));
                                                                            $('#loginModal').modal();

                                                                            return;
                                                                        });
        </script>
        <?php if (isset($error)) { ?>
            <script>Snackbar.show({
                    text: '<?php echo "$error"; ?>',
                    pos: 'top-right'
                });</script>
        <?php } else if (isset($success)) { ?>
            <script> Snackbar.show({
                    text: '<?php echo "$success"; ?>',
                    pos: 'top-right'
                });</script>
        <?php } ?>

    </body>
</html>