<?php
session_start();

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once '../models/Settings.php';
require_once "../vendor/autoload.php";
require_once '../include/DatabaseConn.php';
require_once '../include/Constants.php';
require_once '../models/User.php';
require_once '../include/Helper.php';
require_once '../models/Admin.php';
require_once '../models/News.php';
require_once '../models/USettings.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['title'])) {
    $title = filter_input(INPUT_POST, 'title');
    $body = filter_input(INPUT_POST, 'body');

    if (is_null($title) || is_bool($title) || empty($title)) {
        $error = "Provide news title";
    }
    if (is_null($body) || is_bool($body) || empty($body)) {
        $error = "Provide news content";
    }
    $time = time();

    if (!isset($error)) {
        $stmt = mysqli_prepare($link, "insert INTO news(title,body,`date`) VALUES (?,?,?)");
        $stmt->bind_param("sss", $title, $body, $time);
        $stmt->execute();
        $stmt->store_result();
        if ($stmt->affected_rows > 0) {
            $users = User::getUsers($link);
            if (!is_null($users)) {
                $mail = new PHPMailer(true);
                try {
                    $mail->isSMTP();
                    $mail->SMTPDebug = 0;
                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                    $mail->Debugoutput = 'html';
                    $mail->Host = EMAIL_HOST;

                    $mail->Port = 587;
                    $mail->SMTPSecure = 'tls';
                    $mail->SMTPAuth = true;
                    $mail->Username = EMAIL_USERNAME;
                    $mail->Password = EMAIL_PASSWORD;
                    $mail->setFrom(EMAIL_NO_REPLY, APP_NAME);

                    $mail->Subject = $title;
                    $mail->isHTML(true);
                    $mail->msgHTML($body);
                    //This should be the same as the domain of your From address
                    $mail->DKIM_domain = DKIM_DOMAIN;
                    $mail->DKIM_private = 'dkim_private.pem';
                    $mail->DKIM_selector = DKIM_SELECTOR;
                    $mail->DKIM_identity = $mail->From;
                    $mail->DKIM_copyHeaderFields = false;


                    foreach ($users as $user) {
                        $settings = USettings::getSystemSettings($link, $user->getEmail());
                        if ($settings->getNews()) {
                            $mail->addAddress($user->getEmail(), $user->getName());
                        }
                    }
                    $mail->send();
                } catch (Exception $e) {
                    $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
                    fwrite($myfile, $mail->ErrorInfo);
                    fclose($myfile);
                    return null;
                }
            }

            $success = "The operation was successful";
        }
    }
}
$news = News::getNewsPage($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" />
        <link href="../css/notes.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 app-notes layout-top-spacing" id="cancel-row">
                            <div class="col-lg-12">
                                <div class="app-hamburger-container">
                                    <div class="hamburger"><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-menu chat-menu d-xl-none"><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg></div>
                                </div>

                                <div class="app-container">

                                    <div class="app-note-container">

                                        <div class="app-note-overlay"></div>

                                        <div class="tab-title">
                                            <div class="row">
                                                <div class="col-md-12 col-sm-12 col-12 text-center">
                                                    <a id="btn-add-notes" class="btn btn-primary" href="javascript:void(0);">Add</a>
                                                </div>
                                                <div class="col-md-12 col-sm-12 col-12 mt-5">
                                                    <ul class="nav nav-pills d-block" id="pills-tab3" role="tablist">
                                                        <li class="nav-item">
                                                            <a class="nav-link list-actions active" id="all-notes"><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-edit"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg> All News</a>
                                                        </li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>


                                        <div id="ct" class="note-container note-grid">
                                            <?php
                                            if (!is_null($news)) {
                                                foreach ($news as $n) {
                                                    ?>
                                                    <div class="note-item all-notes note-personal <?php
                                                    if (strcasecmp($n->getFav(), "true") == 0) {
                                                        echo "note-fav";
                                                    }
                                                    ?>">
                                                        <div class="note-inner-content">
                                                            <div class="note-content">
                                                                <p class="note-title" data-notetitle="<?php echo $n->getTitle(); ?>"><?php echo $n->getTitle(); ?></p>
                                                                <p class="meta-time"><?php echo Helper::readableTime($n->getDate()); ?></p>
                                                                <div class="note-description-content">
                                                                    <p class="note-description" data-notedescription="<?php echo $n->getBody(); ?>"><?php echo $n->getBody(); ?></p>
                                                                </div>
                                                            </div>
                                                            <div class="note-action">
                                                                <svg data-id="<?php echo $n->getId(); ?>" 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-star fav-note"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon></svg>
                                                                <svg data-id="<?php echo $n->getId(); ?>" 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-trash-2 delete-note"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <?php
                                                }
                                            }
                                            ?>
                                        </div>

                                    </div>

                                </div>

                                <!-- Modal -->
                                <div class="modal fade" id="notesMailModal" tabindex="-1" role="dialog" aria-labelledby="notesMailModalTitle" style="display: none;" aria-hidden="true">
                                    <div class="modal-dialog modal-dialog-centered" role="document">
                                        <div class="modal-content">
                                            <div class="modal-body">
                                                <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-x close" data-dismiss="modal"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
                                                <div class="notes-box">
                                                    <div class="notes-content">
                                                        <form action="news" method="POST" id="notesMailModalTitle">
                                                            <div class="row">
                                                                <div class="col-md-12">
                                                                    <div class="d-flex note-title" style="flex-direction: column">
                                                                        <input type="text" id="n-title" name="title" class="form-control" maxlength="35" placeholder="Title">
                                                                    </div>
                                                                    <span class="validation-text"></span>
                                                                </div>

                                                                <div class="col-md-12">
                                                                    <div class="d-flex note-description" style="flex-direction: column">
                                                                        <textarea id="n-description" name="body" class="form-control" maxlength="140" placeholder="Description" rows="3" spellcheck="false"></textarea>
                                                                    </div>
                                                                    <span class="validation-text"></span>
                                                                </div>
                                                            </div>

                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button class="btn" data-dismiss="modal"> <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-trash"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg> Discard</button>
                                                <button id="btn-n-add" class="btn">Add</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>

                    </div>
                    <div class="footer-wrapper">
                        <div class="footer-section f-section-2">
                            <p class="">Coded with <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-heart"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg></p>
                        </div>
                    </div>
                </div>
                <!--  END CONTENT AREA  -->
            </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 src="../js/fn.fix-padStart.js"></script>
        <script src="../js/notes.js"></script>
        <script type="text/javascript" src="../js/jquery.charactercounter.min.js"></script>
        <script>
            function showToast(msg) {
                Snackbar.show({
                    text: msg,
                    pos: 'top-right'
                });
            }
            $("#n-title").characterCounter({
                limit: '35',
                counterWrapper: 'div',
                counterFormat: '%1'
            });
            $("#n-description").characterCounter({
                limit: '140',
                counterWrapper: 'div',
                counterFormat: '%1'
            });
        </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>