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

include("header.php");

if (!isset($_SESSION["adminid"])) {
    header("Location: login.php");
    exit();
}

$recres = "";

// Handle deletion of mail
if (isset($_GET["mailid"])) {
    // Sanitize the input by ensuring it is an integer
    $mailid = intval($_GET['mailid']);

    // Use prepared statement to prevent SQL injection
    $stmt_delete = mysqli_prepare($conn, "DELETE FROM mail WHERE mailid = ?");
    mysqli_stmt_bind_param($stmt_delete, "i", $mailid);
    mysqli_stmt_execute($stmt_delete);
    mysqli_stmt_close($stmt_delete);
    $recres = "Mail deleted Successfully...";
}

// Select all mails for the logged-in admin
$result = null;
if (isset($_SESSION['adminid'])) {
    $stmt_select = mysqli_prepare($conn, "SELECT * FROM mail WHERE reciverid = ?");
    mysqli_stmt_bind_param($stmt_select, "s", $_SESSION['adminid']);
    mysqli_stmt_execute($stmt_select);
    $result = mysqli_stmt_get_result($stmt_select);
}

?>
<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-inbox icon-fw icon-lg"></i>
                                        <span class="dt-module-side-nav__text">Inbox</span> </a>
                                </li>
                                <li class="dt-module-side-nav__item">
                                    <a href="sent.php" 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">
                                        <a href="#" class="dropdown-toggle text-dark" data-toggle="dropdown"
                                            aria-haspopup="true" aria-expanded="false"> Inbox </a>
                                        </div>
                                    </div>

                                <div class="dt-module__list">

                                    <?php
                                    if ($result && mysqli_num_rows($result) > 0) {
                                        while ($row = mysqli_fetch_array($result)) {
                                            $rid = $row['senderid'];
                                            $recid = "";

                                            if ($rid != 'admin') {
                                                // Securely fetch customer details using prepared statement
                                                $stmt_cust = mysqli_prepare($conn, "SELECT firstname, lastname FROM customers WHERE customerid = ?");
                                                mysqli_stmt_bind_param($stmt_cust, "i", $rid);
                                                mysqli_stmt_execute($stmt_cust);
                                                $rres = mysqli_stmt_get_result($stmt_cust);
                                                $rresarr = mysqli_fetch_array($rres);
                                                $recid = $rresarr['firstname'] . " " . $rresarr['lastname'];
                                                mysqli_stmt_close($stmt_cust);
                                            } else {
                                                $recid = $rid;
                                            }
                                    ?>
                                            <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'>
                                                </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=<?php echo $row['mailid']; ?>'>
                                                    <div class='user-detail'>
                                                        <span class='user-name'><?php echo $recid; ?></span>
                                                        <span class='dt-separator-v'>&nbsp;</span>
                                                        <span class='designation'>Subject: <?php echo $row['subject']; ?></span>
                                                    </div>
                                                    <p class='mb-0 text-light-gray text-truncate'>Message ID Number Is <?php echo $row['mailid']; ?></p>
                                                </div>
                                                <div class='dt-module__list-item-info'>
                                                    <div class='badge-group'>
                                                        <a href='readmessage.php?mailid=<?php echo $row['mailid']; ?>'>
                                                            <span class='badge bg-dark-blue text-white'>Read Message</span>
                                                        </a>
                                                        <a href='inbox.php?mailid=<?php echo $row['mailid']; ?>'>
                                                            <span class='badge badge-danger'>Delete Message</span>
                                                        </a>
                                                    </div>
                                                    <span><?php echo $row['mdatetime']; ?></span>
                                                </div>
                                                </div>
                                            <?php
                                        }
                                        mysqli_free_result($result);
                                        mysqli_stmt_close($stmt_select);
                                    }
                                    ?>
                                </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php include 'footer.php' ?>
</div>
</main>

<div class="compose-mail-box">
    <?php
    $datetime = date("Y-m-d H:i:s");
    $msgsuccess = "";
    if (isset($_POST["sendmsg"])) {
        // Determine sender ID
        $senderid = "";
        $receiverid = $_POST['sendto'];
        if (isset($_SESSION['adminid'])) {
            $senderid = $_SESSION['adminid'];
        } else if (isset($_SESSION['customerid'])) {
            $senderid = $_SESSION['customerid'];
        }

        if (!empty($senderid) && !empty($receiverid)) {
            // Use prepared statement for a secure INSERT query
            $stmt_insert = mysqli_prepare($conn, "INSERT INTO mail(subject, message, mdatetime, senderid, reciverid) VALUES (?, ?, ?, ?, ?)");
            mysqli_stmt_bind_param($stmt_insert, "sssss", $_POST['subject'], $_POST['message'], $datetime, $senderid, $receiverid);

            if (mysqli_stmt_execute($stmt_insert)) {
                $msgsuccess = "Message Sent Successfully...";
                echo "<script>swal('Success!', 'Message Sent Successfully!', 'success')</script>";
            } else {
                echo "Error: " . mysqli_error($conn);
            }
            mysqli_stmt_close($stmt_insert);
        } else {
            echo "Error: Sender or Receiver ID is missing.";
        }
    }
    ?>

    <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_cust = mysqli_query($conn, "SELECT * FROM customers");
                    if ($result_cust && mysqli_num_rows($result_cust) > 0) {
                        while ($rows = mysqli_fetch_array($result_cust)) {
                            echo "<option value='{$rows['customerid']}'>{$rows['firstname']} {$rows['lastname']}</option>";
                        }
                        mysqli_free_result($result_cust);
                    }
                    ?>
                </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-danger" 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>
<script src="../assets/js/custom/apps/app.js"></script>
<script src="../assets/js/custom/apps/mail-app.js"></script>
</body>
</html>