<?php
ob_start();
session_start();
error_reporting(0);
include("../config/theconfig.php");
include("header.php");

// Check for admin session
if (!isset($_SESSION["adminid"])) {
    header("Location: login.php");
    exit(); // Always add exit() after a header redirect
}

// Handle mail deletion
if (isset($_GET["mailid"])) {
    // Sanitize input to prevent SQL injection
    $mailid = mysqli_real_escape_string($conn, $_GET['mailid']);
    // The query is now more secure
    mysqli_query($conn, "DELETE FROM mail WHERE mailid='$mailid'");
    $recres = "Mail deleted Successfully...";
}

// Fetch sent mails
// Sanitize session variable to prevent SQL injection
$senderid = mysqli_real_escape_string($conn, $_SESSION['adminid']);
$result = mysqli_query($conn, "SELECT * FROM mail WHERE senderid='$senderid'");

?>
<div class="dt-content-wrapper">

    <div class="dt-content">

        <div class="row">

            <div class="col-xl-12">

                <div class="dt-module">

                    <div class="dt-module__sidebar">

                        <div class="dt-module__sidebar-header border-bottom">
                            <div class="d-none d-md-flex align-items-center">
                                <i class="icon icon-open-mail icon-1x mr-3 text-dark"></i>
                                <span class="h3 mb-0">Messages</span>
                            </div>

                            <div class="quick-menu-list d-md-none">

                                <form class="search-box d-md-none">
                                    <input class="form-control" type="search" id="address" name="address"
                                           placeholder="Search in app...">
                                    <button type="submit" class="search-icon"><i
                                            class="icon icon-search icon-lg"></i></button>
                                </form>
                                <a href="javascript:void(0)" class="quick-menu d-none d-md-block"
                                   data-toggle="mdrawer" data-target="#drawer-search-bar"><i
                                        class="icon icon-search"></i></a>
                                <a href="javascript:void(0)" class="quick-menu" data-open="compose"><i
                                        class="icon icon-editors"></i></a>
                                <a href="javascript:void(0)" class="quick-menu" data-toggle="mdrawer"
                                   data-target="#drawer-notifications"><i
                                        class="icon icon-notification2"></i></a>
                                <a href="javascript:void(0)" class="quick-menu d-md-none"
                                   data-toggle="msidebar-content"><i class="icon icon-menu"></i></a>
                            </div>
                            </div>
                        <div class="dt-module__sidebar-content ps-custom-scrollbar">

                            <div class="action-area mt-5 mb-7 d-none d-md-block">
                                <a href="javascript:void(0)"
                                   class="btn btn-shadow btn-default compose-btn btn-rounded"
                                   data-open="compose">
                                    <i class="icon icon-editors icon-fw mr-2"></i>Compose</a>
                            </div>
                            <ul class="dt-module-side-nav">

                                <li class="dt-module-side-nav__header">
                                    <span class="dt-module-side-nav__text">main</span>
                                </li>
                                <li class="dt-module-side-nav__item active">
                                    <a href="javascript:void(0)" class="dt-module-side-nav__link">
                                        <i class="icon icon-send icon-fw icon-lg"></i>
                                        <span class="dt-module-side-nav__text">Sent</span> </a>
                                </li>
                                </ul>
                            </div>
                        </div>
                    <div class="dt-module__container">

                        <div class="dt-module__header d-none d-md-flex">

                            <form class="search-box ml--15">
                                <input class="form-control border-0 shadow-none bg-focus form-control-sm"
                                       placeholder="Search in app..." value=""
                                       type="search"> <span class="search-icon"><i
                                    class="icon icon-search icon-lg"></i></span>
                            </form>
                            </div>
                        <div class="dt-module__content ps-custom-scrollbar">

                            <div class="dt-module__content-inner">

                                <div class="px-1 pb-4 border-bottom border-width-2 mb-1 mt--5">
                                    <div class="dropdown">

                                        <div class="dt-checkbox dt-checkbox-icon dt-checkbox-only mr-1">
                                            <input id="option-checkbox" type="checkbox">
                                            <label class="font-weight-light dt-checkbox-content"
                                                   for="option-checkbox">
                                                <span class="unchecked"><i
                                                        class="icon icon-box-o icon-fw icon-xl"></i></span>
                                                <span class="checked"><i
                                                        class="icon icon-box-check-o icon-fw icon-xl text-primary"></i></span>
                                            </label>
                                        </div>
                                        <a href="#" class="dropdown-toggle text-dark" data-toggle="dropdown"
                                           aria-haspopup="true" aria-expanded="false">Sent Messages </a>
                                        </div>
                                    </div>

                                <div class="dt-module__list">

                                    <?php
                                    while ($row = mysqli_fetch_array($result)) {
                                        $rid = htmlspecialchars($row['reciverid']);
                                        if (!($rid == 'admin')) {
                                            $rres = mysqli_query($conn, "SELECT * FROM customers WHERE customerid='" . mysqli_real_escape_string($conn, $rid) . "'");
                                            $rresarr = mysqli_fetch_array($rres);
                                            $recid = htmlspecialchars($rresarr['firstname'] . " " . $rresarr['lastname']);
                                        } else {
                                            $recid = $rid;
                                        }
                                        echo "<div class='dt-module__list-item'>
                                                <div class='dt-checkbox dt-checkbox-icon dt-checkbox-only mr-5'>
                                                    <input id='icon-checkbox-1' type='checkbox'>
                                                    <label class='font-weight-light dt-checkbox-content'
                                                           for='icon-checkbox-1'>
                                                        <span class='unchecked'><i
                                                                class='icon icon-box-o icon-fw icon-xl'></i></span>
                                                        <span class='checked'><i
                                                                class='icon icon-box-check-o icon-fw icon-xl text-primary'></i></span>
                                                    </label>
                                                </div>
                                                <div class='dt-checkbox dt-checkbox-icon dt-checkbox-only mr-5'>
                                                    <input id='icon-checkbox-2' type='checkbox''>
                                                    <label class='font-weight-light dt-checkbox-content'
                                                           for='icon-checkbox-2'>
                                                        <span class='unchecked'><i
                                                                class='icon icon-star-o icon-fw icon-xl'></i></span>
                                                        <span class='checked'><i
                                                                class='icon icon-star-fill icon-fw icon-xl text-warning'></i></span>
                                                    </label>
                                                </div>
                                                <img class='dt-avatar mr-4' src='../assets/images/icon-account.png'
                                                     alt='Reece Jacklin''>
                                                <div class='dt-module__list-item-content'
                                                     data-location='readmessage.php?mailid=".htmlspecialchars($row['mailid'])."'>
                                                    <div class='user-detail'>
                                                        <span class='user-name'>Receiver: $recid</span>
                                                        <span class='dt-separator-v'>&nbsp;</span>
                                                        <span class='designation'>Subject: ".htmlspecialchars($row['subject'])."</span>
                                                    </div>
                                                    <p class='mb-0 text-light-gray text-truncate'>Message ID Number Is ".htmlspecialchars($row['mailid'])."</p>
                                                </div>
                                                <div class='dt-module__list-item-info'>
                                                    <div class='badge-group'>
                                                        <a href='readmessage.php?mailid=".htmlspecialchars($row['mailid'])."'> <span class='badge bg-dark-blue text-white'>View</span></a>
                                                        <a href='sent.php?mailid=".htmlspecialchars($row['mailid'])."'> <span class='badge badge-danger'>Delete</span></a>
                                                    </div>
                                                    <span>".htmlspecialchars($row['mdatetime'])."</span>
                                                </div>
                                                </div>
                                            ";
                                    }
                                    ?>
                                </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php include 'footer.php' ?>
</div>
<div class="compose-mail-box">
    <?php
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;

    require 'PHPMailer/src/Exception.php';
    require 'PHPMailer/src/PHPMailer.php';
    require 'PHPMailer/src/SMTP.php';

    $datetime = date("Y-m-d h:i:s");

    if (isset($_POST["sendmsg"])) {
        // Sanitize input
        $sendtoId = mysqli_real_escape_string($conn, $_POST['sendto']);

        // Fetch the email of the recipient
        $emailQuery = mysqli_query($conn, "SELECT email FROM customers WHERE customerid='$sendtoId'");
        $emailRow = mysqli_fetch_array($emailQuery);
        $recipientEmail = htmlspecialchars($emailRow['email']);

        // Sanitize other post variables
        $subject = mysqli_real_escape_string($conn, $_POST['subject']);
        $message = mysqli_real_escape_string($conn, $_POST['message']);

        // Determine sender ID
        if (isset($_SESSION['customerid'])) {
            $sender = mysqli_real_escape_string($conn, $_SESSION['customerid']);
            $sql = "INSERT INTO mail(subject, message, mdatetime, senderid, reciverid) VALUES('$subject', '$message', '$datetime', '$sender', '$sendtoId')";
        } else if (isset($_SESSION['adminid'])) {
            $sender = mysqli_real_escape_string($conn, $_SESSION['adminid']);
            $sql = "INSERT INTO mail(subject, message, mdatetime, senderid, reciverid) VALUES('$subject', '$message', '$datetime', '$sender', '$sendtoId')";
        }

        // Execute the mail insert
        if (!mysqli_query($conn, $sql)) {
            die('Error: ' . mysqli_error($conn));
        }

        // Create a new PHPMailer instance
        $mail = new PHPMailer(true);

        try {
            // Server settings
            $mail->isSMTP();
            $mail->Host = 'mail.noblecityfinance.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'support@noblecityfinance.com';
            // Note: Hardcoding the password is a security risk. Consider using environment variables or a secure configuration file.
            $mail->Password = 'ashley123412J<>';
            $mail->SMTPSecure = 'tls';
            $mail->Port = 465;

            // Recipients
            $mail->setFrom('support@noblecityfinance.com', 'Mailer');
            $mail->addAddress($recipientEmail);

            // Content
            $mail->isHTML(true);
            $mail->Subject = htmlspecialchars($_POST['subject']);
            $mail->Body = htmlspecialchars($_POST['message']);

            // Send the email
            $mail->send();
            echo "<script>swal('Success!', 'Message Sent Successfully!', 'success')</script>";
        } catch (Exception $e) {
            echo "<script>swal('Error!', 'Message could not be sent. Mailer Error: {$mail->ErrorInfo}', 'error')</script>";
        }
    }
    ?>

    <div class="compose-mail-box__header" data-toggle="minimize">
        <div class="title">
            <i class="icon icon-editors icon-fw icon-xl mr-2"></i>Compose New Message
        </div>

        <div class="action-area ml-auto">
            <a class="text-white mr-3" href="javascript:void(0)"> <i class="icon icon-chevrolet-down icon-xl"></i> </a>
            <a class="text-white" href="javascript:void(0)" data-dismiss="compose"> <i
                    class="icon icon-remove icon-xl"></i>
            </a>
        </div>
    </div>
    <div class="compose-mail-box__body">
        <form method="post" action="">

            <div class="form-group mb-1">
                <label class="sr-only" for="emails">Email address</label>
                <select name="sendto" id="sendto" class="custom-select custom-select-sm">
                    <?php
                    $result = mysqli_query($conn, "SELECT * FROM customers");

                    while ($rows = mysqli_fetch_array($result)) {
                        echo "<option value='".htmlspecialchars($rows['customerid'])."'>".htmlspecialchars($rows['firstname'])." ".htmlspecialchars($rows['lastname'])." (".htmlspecialchars($rows['email']).")</option>";
                    }

                    ?>
                </select>
            </div>
            <div class="form-group">
                <label class="sr-only" for="subject">Subject</label>
                <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject">
            </div>
            <div class="form-group">
                <label class="sr-only" for="textarea">Example textarea</label>
                <textarea name="message" id="MESSAGE" class="form-control" id="textarea">
Hi ,
Type Your Message Content Here.

Cheers!
</textarea>
            </div>
            <div class="d-flex align-items-center">
                <input type="submit" name="sendmsg" id="sendmsg" class="btn btn-primary btn-sm" value="Send Message">

                <div class="action-area ml-auto">
                    <a class="text-dark" href="javascript:void(0)" data-dismiss="compose">
                        <i class="icon icon-trash-filled mr-1"></i> <span class="f-12 text-uppercase align-middle">discard</span>
                    </a>
                </div>
            </div>
            </form>
        </div>
    </div>
</div>
</div>
<div class="card user-info-card">
    <div class="p-4">
        <div class="dt-avatar-wrapper mb-3">
            <img style="display: none" class="dt-avatar size-50 profile-pic"
                 src="assets/images/user-avatar/domnic-harris.jpg" alt="Domnic Harris"> <span style="display: none"
                                                                                              class="dt-avatar size-50 bg-orange text-white text-uppercase profile-placeholder">pp</span>

            <div class="dt-avatar-info">
                <span class="dt-avatar-name h4 mb-1">Domnic Harris</span>
                <span class="dt-avatar-desc f-12">dom.harris@gmail.com</span>
            </div>
        </div>

        <div class="mb-1">
            <i class="icon icon-maps icon-fw mr-1"></i> <span class="f-12">Palo Alto, CA, United States</span>
        </div>

        <div>
            <i class="icon icon-contacts icon-fw mr-1"></i> <span class="f-12">20+ Mutual Connections</span>
        </div>
    </div>

    <div class="px-4 py-2 border-top d-flex justify-content-between">
        <a href="javascript:void(0)" class="card-link">Add to Contacts</a>
        <div class="ml-2 ml-sm-10">
            <a class="mr-1" href="javascript:void(0)"><i class="icon icon-mail icon-fw icon-xl"></i></a>
            <a class="mr-1" href="javascript:void(0)"><i class="icon icon-tag-o icon-fw icon-xl"></i></a>
            <a href="javascript:void(0)"><i class="icon icon-chat-app icon-fw icon-xl"></i></a>
        </div>
    </div>
</div>
<script src="../assets/js/custom/apps/app.js"></script>
<script src="../assets/js/custom/apps/mail-app.js"></script>
</body>
</html>