<?php
    session_start();
    if( !isset($_SESSION['chap']) ){
        header("Location:../index.html#login-area");
        exit();
    }
    else{
        $chap = $_SESSION['chap'];
        include "../connect/db.php";
        $sql = mysqli_query($mysqli,"SELECT * FROM users WHERE email = '$chap' ");
        $row = mysqli_fetch_assoc($sql);
        if( $row['status'] == "suspended" ){
            header("Location:account.php");
            exit();
        }
        else if( $row['status'] == "terminated" ){
            header("Location:terminate.php");
            exit();
        }
    }




       if($row['kyc_status'] == "pending" || $row['kyc_status'] == "review" )


{
   header("Location:kyc.php");
   exit();


}
    if($row['code_level'] != "nothing"){

if($row['lock_status'] == "active" )


{
   header("Location:auth.php");
   exit();


}
else{

}



}
else{
    
}
    




    $name = $row['firstname'] .$row['middlename'] .$row['lastname'];
?>

<!DOCTYPE html>
<html lang="en-US" class="js">

<head>
    <meta charset="utf-8">
    <meta name="author" content="Smart">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description"
        content="Aspire Securities is a trademark of Aspire Financial Corporation. Aspire Securities is a trade name for the corporate and investment banking services of Aspire Financial Corporation and its subsidiaries. All rights reserved. Securities and strategic advisory services are provided by Aspire Securities, Inc., member FINRA, link opens in new tab and SIPC, link opens in new tab. Lending, financial risk management, and treasury management and payment services are offered by Aspire Bank. Deposit products are offered by Aspire Bank.">
    <!-- Fav Icon  -->
    <link rel="shortcut icon" href="../images/favicon.png">
    <!-- Page Title  -->
    <title><?=$row['firstname']?> <?=$row['middlename']?> <?=$row['lastname']?> | <?= htmlspecialchars(getSetting('site_name', 'Deutsche Bank Holdings Delaware')) ?> Online banking</title>
    <!-- StyleSheets  -->
    <link rel="stylesheet" href="../scss/sweetalert.css">
    <link rel="stylesheet" href="assets/css/dashlite.css?ver=2.4.0">
    <link id="skin-default" rel="stylesheet" href="assets/css/theme.css?ver=2.4.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">

    <link href="../css/toastr.css" rel="stylesheet" />
</head>
<link rel="stylesheet"
    href="https://www.jqueryscript.net/demo/jQuery-International-Telephone-Input-With-Flags-Dial-Codes/build/css/intlTelInput.css">
<script type="text/javascript">
    function googleTranslateElementInit() {
        new google.translate.TranslateElement({ pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE }, 'google_translate_element');
    }
</script>
<script type="text/javascript"
    src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<style>
    .goog-te-gadget-simple {
        border: none;
    }

    .goog-te-gadget-simple a {
        color: #000;
    }
</style>
<style type="text/css">
    .btn-primary {
        background-color: #033d75;
    }

    .btn-secondary {
        background-color: #d13636;
    }

    .btn-secondary:hover {
        opacity: 0.6;
    }

    .btn-primary:hover {
        opacity: 0.6;
    }
</style>

<body class="nk-body npc-crypto bg-white has-sidebar ">
    <div class="nk-app-root">
        <!-- main @s -->
        <div class="nk-main ">
            <!-- sidebar @s -->
            <div class="nk-sidebar nk-sidebar-fixed " data-content="sidebarMenu">
                <div class="nk-sidebar-element nk-sidebar-head" style="border-bottom: solid #fe473a;">
                    <div class="nk-sidebar-brand">
                        <a href="dashboard" class="logo-link nk-sidebar-logo">
                            <img class="logo-light logo-img" src="../logo.png" srcset="../logo.png 2x" alt="logo">
                            <img class="logo-dark logo-img" src="../logo.png" srcset="../logo.png 2x" alt="logo-dark">

                        </a>
                    </div>
                    <div class="nk-menu-trigger mr-n2">
                        <a href="#" class="nk-nav-toggle nk-quick-nav-icon d-xl-none" data-target="sidebarMenu"><em
                                class="icon ni ni-arrow-left"></em></a>
                    </div>
                </div><!-- .nk-sidebar-element -->
                <?php include 'includes/sidebar.php'?>

                <!-- main header @e -->
                <div class="nk-content nk-content-fluid">
                    <div class="container-xl wide-lg">
                        <div class="nk-content-body">
                            <div class="nk-block-head">
                                <div class="nk-block-head-sub">
                                </div>
                                <div class="nk-block-between-md g-4 card-bordered">
                                    <div class="nk-block-head-content">
                                        <h4 class="nk-block-title fw-normal">Customer care Desk.</h4>
                                        <div class="nk-block-des">
                                            <p>Our customer Care representatives are always committed in giving you the
                                                best banking experience.</p>
                                        </div>
                                    </div><!-- .nk-block-head-content -->
                                    <div class="nk-block-head-content">
                                        <ul class="nk-block-tools gx-3">
                                            <li><a href="transfer"
                                                    class="btn btn-secondary btn-light text-light"><span>Transfer
                                                        Fund</span><em class="icon ni ni-wallet-out"></em></a></li>
                                        </ul>
                                    </div><!-- .nk-block-head-content -->
                                </div><!-- .nk-block-between -->
                            </div><!-- .nk-block-head -->
                        </div>
                    </div>
                    <div class="card card-bordered card-preview">
                        <div class="card-header font-weight-bold text-light" style="background-color:#033d75;">
                            <h5 class="text-white"> <em class="icon ni ni-question"></em> Create a support ticket </h5>
                        </div>
                        <div class="card-body">
                            <form action="" method="post"><?= csrf_field() ?>
                                <div class="row">
                                    <div class="form-group col-lg-12">

                                        <select class="form-control form-control-xl" name="department" id="department">
                                            <option value="" selected="" disabled="">Please Select Customer Service
                                                Department</option>
                                            <option value="Customer Services Department">Customer Services Department
                                            </option>
                                            <option value="Account Department">Account Department</option>
                                            <option value="Transfer Department">Transfer Department</option>
                                            <option value="Card Services Department">Card Services Department</option>
                                            <option value="Loan Department">Loan Department</option>
                                            <option value="Bank Deposit Department">Bank Deposit Department</option>
                                        </select>
                                    </div>
                                    <div class="form-group col-lg-12">
                                        <textarea class="form-control form-control-xl" name="message" id="message"
                                            placeholder="Type your complaints"></textarea>
                                    </div>
                                    <div class="createResult"></div>
                                    <div class="form-group col-lg-12">
                                        <button class="btn btn-primary ticketBtn" type="submit" id="btn">Submit</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    <!-------Previous tickets---->
                    <div class="card card-bordered card-preview">
                        <div class="card-header font-weight-bold text-light" style="background-color:#033d75;">
                            <h5 class="text-white"> <em class="icon ni ni-question-alt"></em> Previous support tickets
                            </h5>
                        </div>
                        <div class="card-body">
                           

































                        <?php
// Fetch only one support ticket per unique ticket_id where the user matches $chap
$query = "
    SELECT * FROM support_tickets st
    WHERE st.user = ? 
    AND st.created_at = (
        SELECT MAX(created_at) 
        FROM support_tickets 
        WHERE ticket_id = st.ticket_id 
        AND user = ?
    )
";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('ss', $chap, $chap);
$stmt->execute();
$result = $stmt->get_result();
?>


<div style="overflow-x:auto;">
<table class="datatable-init table" style="width:100%;min-width:700px;">
    <thead>
        <tr>
            <th>Department</th>
            <th>Ticket ID</th>
            <th>Date</th>
            <th>Comments</th>
            <th>Status</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <?php while ($row = mysqli_fetch_assoc($result)) { ?>
            <tr>
                <td><?php echo htmlspecialchars($row['department']); ?></td>
                <td><?php echo htmlspecialchars($row['ticket_id']); ?></td>
                <td><?php echo date('d M Y h:i a', strtotime($row['created_at'])); ?></td>
                <td>(<?php echo htmlspecialchars($row['comments']); ?>)</td>
                <td><strong class='text-success'><?php echo htmlspecialchars($row['status']); ?></strong></td>
                <td>
                    <button class="btn btn-primary btn-sm view-btn" data-ticket-id="<?php echo htmlspecialchars($row['ticket_id']); ?>" data-toggle="modal" data-target="#replyModal">View</button>
                </td>
            </tr>
        <?php } ?>
    </tbody>
</table>

<?php mysqli_close($mysqli); ?>

<script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
<script>
function htmlspecialchars(text) {
    var map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}

function fetchguy(ticketId) {
    var csrfToken = $('input[name="csrf_token"]').val();
    $.ajax({
        type: "POST",
        url: "../apps/user/fetch_ticket_details.php",
        data: { ticket_id: ticketId, csrf_token: csrfToken },
        dataType: "json",
        success: function(data) {
            // Update the modal content
            $('#modalTicketId').text(data.ticket_id);
            $('#modalMessage').text(data.message);
            // Update the hidden input with the ticket_id
            $('input[name="ticketidx"]').val(data.ticket_id);

            // Clear the chat section
            var chatSection = $('#chatSection');
            chatSection.empty();

            // Append chat messages to the chat section
            $.each(data.messages, function(index, message) {
                var sender = message.name === 'admin' ? 'Support' : htmlspecialchars(message.name);
                chatSection.append(
                    '<div class="alert alert-pro w-100 p-1">' +
                    htmlspecialchars(message.message) + '<br>' +
                    '<small class="text-muted">' + new Date(message.created_at).toLocaleString() + '</small><br>' +
                    '<small class="text-muted">' + sender + '</small>' +
                    '</div>'
                );
            });
        },
        error: function(xhr, status, error) {
            $('#modalTicketId').text('Error');
            $('#modalMessage').text('Failed to load ticket details. Please try again.');
            $('#chatSection').empty();
        }
    });
}

$(document).ready(function() {
    $('.view-btn').click(function() {
        var ticketId = $(this).data('ticket-id');
        fetchguy(ticketId);
    });
});

</script>




<script>
    function toastAlert(bool1, pos, bool2, time, kind, msg) {
        const Toast = Swal.mixin({
            toast: bool1,
            position: pos,
            showConfirmButton: bool2,
            timer: time
        });
        Toast.fire({
            type: kind,
            title: msg
        });
    }

    function submitReply() {
    let replyMessage = $("textarea[name=replyMessage]").val();
    let ticketidx = $("input[name=ticketidx]").val();
    var csrfToken = $('input[name="csrf_token"]').val();

    // Validation
    if (replyMessage == "" || replyMessage == null) {
        toastAlert(true, "center", false, 3000, "info", "Please type your message");
        return;
    }

    if (ticketidx == "" || ticketidx == null) {
        toastAlert(true, "center", false, 3000, "info", "Ticket ID is missing");
        return;
    }

    Swal.showLoading();
    $.ajax({
        url: "../apps/user/reply_ticket.php",
        type: "POST",
        data: {
            replyMessage: replyMessage,
            ticketidx: ticketidx,
            csrf_token: csrfToken
        },
        success: function(data){
            let info = $.trim(data);
            if (info == "success") {
                Swal.fire({
                    icon: 'success',
                    title: 'Reply Submitted',
                    text: 'Your reply has been sent',
                    showConfirmButton: false,
                    timer: 2000
                });
                setTimeout(function() {
                    location.reload();
                }, 2200);
            } else if (info == "error") {
                toastAlert(true, "center", false, 3000, "error", "Something went wrong");
            } else {
                toastAlert(true, "center", false, 5000, "error", info);
            }
        },
        error: function (xhr, status, error) {
            toastAlert(true, "center", false, 5000, "error", "Request failed. Please try again.");
        }
    });
}

// Attach event listener to the send button (use delegation since modal is at bottom of page)
$(document).on('click', '.sendMsg16', function(e) {
    e.preventDefault();
    submitReply();
});

    </script>




























































































                        </div>
                    </div>

                </div>
                <script src="../js/jquery.min.js"></script>
                <script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
                <script type="text/javascript">
                    $(document).ready(function () {
                        $('.ticketBtn').click(function (e) {
                            e.preventDefault();
                            var $btn = $(this);
                            var originalHtml = $btn.html();
                            $btn.html('<i class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></i>&nbsp;Processing...');
                            $btn.prop('disabled', true);

                            var department = $('#department').val();
                            var message = $('#message').val();
                            var csrfToken = $('input[name="csrf_token"]').val();

                            $.ajax({
                                type: "POST",
                                url: "../apps/user/create_support_ticket.php",
                                data: {
                                    "department": department,
                                    "message": message,
                                    "csrf_token": csrfToken
                                },
                                success: function (data) {
                                    if ($.trim(data) == "success") {
                                        Swal.fire({
                                            icon: 'success',
                                            title: 'Request Submitted',
                                            text: 'Your request has been submitted',
                                            showConfirmButton: false,
                                            timer: 2000
                                        });
                                        setTimeout(function() {
                                            location.reload();
                                        }, 2200);
                                    } else if ($.trim(data) == "error") {
                                        toastAlert(true, "center", false, 3000, "error", "Something went wrong");
                                        $btn.html(originalHtml);
                                        $btn.prop('disabled', false);
                                    } else {
                                        toastAlert(true, "center", false, 5000, "error", data);
                                        $btn.html(originalHtml);
                                        $btn.prop('disabled', false);
                                    }
                                },
                                error: function (xhr, status, error) {
                                    toastAlert(true, "center", false, 5000, "error", "Request failed. Please try again.");
                                    $btn.html(originalHtml);
                                    $btn.prop('disabled', false);
                                }
                            });
                        });
                    });
                </script>
                <div class="nk-footer nk-footer-fluid">
                    <div class="container-fluid">
                        <div class="nk-footer-wrap">
                            <div class="nk-footer-copyright"> &copy; <?php
echo date("Y");
?>  <?= htmlspecialchars(getSetting('site_name', 'Deutsche Bank Holdings Delaware')) ?>   <a href="#">All rights
                                    reserved.</a>
                            </div>
                            <div class="nk-footer-links">
                                <ul class="nav nav-sm">
                                    <li class="nav-item"><a class="nav-link" href="#">Terms</a></li>
                                    <li class="nav-item"><a class="nav-link" href="privacy">Privacy</a></li>
                                    <li class="nav-item"><a class="nav-link" href="contact">Help</a></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- footer @e -->
            </div>
            <!-- wrap @e -->
        </div>
        <!-- main @e -->
    </div>
    <!-- app-root @e -->
    <!-- JavaScript -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="../js/country.js"></script>
    <script src="assets/js/bundle.js?ver=2.4.0"></script>
    <script src="assets/js/scripts.js?ver=2.4.0"></script>
    <script src="assets/js/charts/chart-crypto.js?ver=2.4.0"></script>
    <script src="../plugins/sweetalert2/sweetalert2.all.min.js"></script>
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/custom.js"></script>
    <script src="../js/toastr.js"></script>

<!-- Reply Modal -->
<div class="modal fade" tabindex="-1" id="replyModal">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <a href="#" class="close text-white" data-dismiss="modal" aria-label="Close">
                <em class="icon ni ni-cross"></em>
            </a>
            <div class="modal-header text-white" style="background-color:#033d75; color: white;">
                <h5 class="modal-title" id="modalTicketId"></h5>
            </div>
            <div class="modal-body bg-light">
                <p class="card-bordered rounded-sm p-1 bg-white" id="modalMessage"></p>
                <hr style="height:3px; background-color: #033d75; border-radius:3px;">
                <strong class="text-center" style="align-center text-align: center;">Discussion</strong>
                <div id="chatSection">
            </div>
            <br>
            <div class="nk-chat-editor" style="border-color:black;">
                   <div class="nk-chat-editor-upload  ml-n1">
                    <a href="#" class="btn btn-round btn-primary btn-icon"><em class="icon ni ni-plus-circle-fill"></em></a>
                     </div>
                     <div class="chatResult"></div>
                        <div class="nk-chat-editor-form">
                          <div class="form-control-wrap">
                            <input type="hidden" name="ticketidx" id="" value="">
                          <textarea name="replyMessage" class="form-control form-control-simple no-resize" rows="1" id="replyMessage" placeholder="Type your message..."></textarea>
                          </div>
                            </div>
                            <ul class="nk-chat-editor-tools g-2">
                             <li>
                                <div class="sendResult16"></div>
                              <button class="btn btn-round btn-primary btn-icon sendMsg16" id="btn16"><em class="icon ni ni-send-alt"></em></button>
                           </li>
                        </ul>
                     </div>

            </div>
            <div class="modal-footer bg-light">
                <span class="sub-text btn btn-danger btn-sm text-white" data-dismiss="modal">Close</span>
            </div>
        </div>
    </div>
</div>

</body>

</html>