<?php
session_start();
require("../../mainconfig.php");
$msg_type = "nothing";

if (isset($_SESSION['user'])) {
	$sess_username = $_SESSION['user']['username'];
	$check_user = mysqli_query($db, "SELECT * FROM users WHERE username = '$sess_username'");
	$data_user = mysqli_fetch_assoc($check_user);
	if (mysqli_num_rows($check_user) == 0) {
		header("Location: ".$cfg_baseurl."logout.php");
	} else if ($data_user['status'] == "Suspended") {
		header("Location: ".$cfg_baseurl."logout.php");
	} else if ($data_user['level'] != "Developers") {
		header("Location: ".$cfg_baseurl);
	} else {
		if (isset($_GET['id'])) {
			$post_target = $_GET['id'];
			$check_ticket = mysqli_query($db, "SELECT * FROM tickets WHERE id = '$post_target'");
			$data_ticket = mysqli_fetch_array($check_ticket);
			if (mysqli_num_rows($check_ticket) == 0) {
				header("Location: ".$cfg_baseurl."admin/tickets.php");
			} else {
				mysqli_query($db, "UPDATE tickets SET seen_admin = '1' WHERE id = '$post_target'");
				if (isset($_POST['submit'])) {
					$post_message = $_POST['message'];
					if ($data_ticket['status'] == "Closed") {
						$msg_type = "error";
						$msg_content = "<b>Gagal:</b> Ticket closed.";
					} else if (empty($post_message)) {
						$msg_type = "error";
						$msg_content = "<b>Gagal:</b> Please fill all input.";
					} else if (strlen($post_message) > 500) {
						$msg_type = "error";
						$msg_content = "<b>Gagal:</b> Maximum message is 500 characters.";
					} else {
						$last_update = "$date $time";
						$insert_ticket = mysqli_query($db, "INSERT INTO tickets_message (ticket_id, sender, user, message, datetime) VALUES ('$post_target', 'Admin', '$data_ticket[user]', '$post_message', '$last_update')");
						$update_ticket = mysqli_query($db, "UPDATE tickets SET last_update = '$last_update', seen_user = '0', status = 'Responded' WHERE id = '$post_target'");
						if ($insert_ticket == TRUE) {
							$msg_type = "success";
							$msg_content = "<b>Berhasil:</b> Message sent.";
						} else {
							$msg_type = "error";
							$msg_content = "<b>Gagal:</b> System error.";
						}
					}
				} else if (isset($_POST['closed'])) {
					if ($data_ticket['status'] == "Closed") {
						$msg_type = "error";
						$msg_content = "<b>Gagal:</b> Ticket already closed.";
					} else {
						$update_ticket = mysqli_query($db, "UPDATE tickets SET status = 'Closed' WHERE id = '$post_target'");
						if ($update_ticket == TRUE) {
							$msg_type = "success";
							$msg_content = "<b>Berhasil:</b> Ticket closed.";
							?> <meta http-equiv="refresh" content="0;URL=<?= $cfg_baseurl ?>pages/admin/ticket" /> <?
						} else {
							$msg_type = "error";
							$msg_content = "<b>Gagal:</b> System error.";
						}
					}
				}
				$check_ticket = mysqli_query($db, "SELECT * FROM tickets WHERE id = '$post_target'");
				$data_ticket = mysqli_fetch_array($check_ticket);
				include("../../lib/header.php");
?>
						<div class="page-body checkout">
    <div class="container-fluid">        
    <div class="page-title">
        <div class="row">
            <div class="col-6">
                <h3><?php echo str_replace(['_'], [' '], ucfirst(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME))); ?></h3>
            </div>
            <div class="col-6">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="<?= $cfg_baseurl ?>index"><svg class="stroke-icon">
                      <use href="<?= $cfg_baseurl ?>assets/svg/icon-sprite.svg#stroke-home"></use>
                    </svg></a></li>
                    <li class="breadcrumb-item"><?php echo $items[sizeof($items) - 2]; ?></li>
                    <li class="breadcrumb-item active"><?php echo str_replace(['_'], [' '], ucfirst(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME))); ?></li>
                </ol>
            </div>
        </div>
    </div>
</div>
          <!-- Container-fluid starts-->
          <div class="container-fluid">
            <div class="row">
                <?php 
											if ($msg_type == "success") {
											?>
											<div class="alert alert-success dark" role="alert">
                      <p><?php echo $msg_content; ?></p>
                    </div>
											<?php
											} else if ($msg_type == "error") {
											?>
											<div class="alert alert-secondary dark" role="alert">
                          <p><?php echo $msg_content; ?></p>
                        </div>
											<?php
											}
											?>
              <div class="col call-chat-body">
                <div class="card">
                  <div class="card-body p-0">
                    <div class="row chat-box">
                      <!-- Chat right side start-->
                      <div class="col pe-0 chat-right-aside">
                        <!-- chat start-->
                        <div class="chat">
                          <!-- chat-header start-->
                          <div class="chat-header clearfix"><img class="rounded-circle" src="<?= $cfg_baseurl ?>assets/images/dashboard/user/6.jpg" alt="">
                            <div class="about">
                              <div class="name">Admin <span class="font-primary f-12"> Borneo</span></div>
                              <div class="status"><?= $date; ?></div>
                            </div>
                            <ul class="list-inline float-start float-sm-end chat-menu-icons">
                                <li><a href="/pages/admin/ticket"><i class="fa fa-arrow-left"></i></a></li>
                            </ul>
                          </div>
                          <!-- chat-header end-->
                          <div class="chat-history chat-msg-box custom-scrollbar">
                            <ul>
                                <li class="clearfix">
                                <div class="message other-message pull-right"><img class="rounded-circle float-end chat-user-img img-30" src="<?= $cfg_baseurl ?>assets/images/dashboard/profile-user.png" alt="">
                                  <?php echo nl2br($data_ticket['message']); ?>
                                  <br /><i class="text-muted" style="font-size: 10px;"><?php echo $data_ticket['datetime']; ?></i>
                                </div>
                              </li>
                              <?php
                                $check_message = mysqli_query($db, "SELECT * FROM tickets_message WHERE ticket_id = '$post_target'");
                                while ($data_message = mysqli_fetch_array($check_message)) {
                                	if ($data_message['sender'] == "Admin") {
                                	    echo "<li>
                                <div class='message my-message'><img class='rounded-circle float-start chat-user-img img-30' src='".$cfg_baseurl."assets/images/dashboard/user/6.jpg' alt=''>
                                  ".nl2br($data_message['message'])."
                                  <br /><i class='text-muted' style='font-size: 10px;'>$".$data_message['datetime']."</i>
                                </div>
                              </li>";
                                	} else {
                                	    echo "<li class='clearfix'>
                                <div class='message other-message pull-right'><img class='rounded-circle float-end chat-user-img img-30' src='".$cfg_baseurl."assets/images/dashboard/profile-user.png' alt=''>
                                  ".nl2br($data_message['message'])."
                                  <br /><i class='text-muted' style='font-size: 10px;'>$".$data_message['datetime']."</i>
                                </div>
                              </li>";
                                	    $poto_propil = $cfg_baseurl.'assets/images/dashboard/profile-user.png';
                                		$msg_text = 'class="clearfix"';
                                		$pull_right = "pull-right";
                                	}
                                ?>										
                                <?php
                                }
                                ?>
                            </ul>
                          </div>
                          <!-- end chat-history-->
                          <div class="chat-message clearfix">
                            <div class="row">
                              <div class="col-xl-12 d-flex">
                                <div class="card-body custom-input"> 
                                <form class="input-group text-box" method="POST">
                                  <textarea class="form-control btn-square" placeholder="Masukkan Pesan Anda" name="message" rows="1"></textarea>
                                  <button class="input-group-text btn btn-primary" type="submit" name="submit">SEND</button>
                                </form>
                                </div>
                              </div>
                            </div>
                          </div>
                          <!-- end chat-message-->
                          <!-- chat end-->
                          <!-- Chat right side ends-->
                        </div>
                      </div>
                      <div class="col ps-0 chat-menu">
                        <ul class="nav nav-tabs border-tab nav-primary" id="info-tab" role="tablist">
                          <li class="nav-item"><a class="nav-link active" id="info-home-tab" data-bs-toggle="tab" href="#info-home" role="tab" aria-selected="true">INFO</a>
                            <div class="material-border"></div>
                          </li>
                        </ul>
                          <div class="tab-content" id="info-tabContent">
                            <div class="tab-pane fade show active" id="info-home" role="tabpanel" aria-labelledby="info-home-tab">
                              <div class="people-list">
                                <div class="card" bis_skin_checked="1">
                                  <div class="card-header d-flex justify-content-between align-items-center" bis_skin_checked="1">
                                  <h4 class="card-title m-0"><i class="mdi mdi-information-variant me-1"></i> Informasi Tiket</h4>
                                </div>
                                <div class="card-body" bis_skin_checked="1">
                                  <div class="border-bottom pb-3" bis_skin_checked="1">
                                  <h6 class="fw-medium">ID Tiket</h6><?= $data_ticket['id']; ?>
                                </div>
                                <div class="border-bottom py-3" bis_skin_checked="1">
                                  <h6 class="fw-medium">Subjek</h6><?= $data_ticket['subject']; ?>
                                </div>
                                <?
                                    if($data_ticket['subject'] == "Pesanan"){
                                        echo '<div class="border-bottom py-3" bis_skin_checked="1">
                                    <h6 class="fw-medium">Order ID</h6>'.$data_ticket['idnya'].'
                                  </div>';
                                    } elseif ($data_ticket['subject'] == "Deposit"){
                                        echo '<div class="border-bottom py-3" bis_skin_checked="1">
                                    <h6 class="fw-medium">Deposit ID</h6>'.$data_ticket['idnya'].'
                                  </div>';
                                    }
                                ?>
                                  <div class="border-bottom py-3" bis_skin_checked="1">
                                  <h6 class="fw-medium">Status</h6>
                                      <? 
                                      if($data_ticket['status'] == "Pending"){
                                          echo "<span class='badge badge-warning'>Pending</span>";
                                      } else if($data_ticket['status'] == "Responded"){
                                          echo "<span class='badge badge-primary'>Responded</span>";
                                      } else if($data_ticket['status'] == "Waiting"){
                                          echo "<span class='badge badge-warning'>Waiting</span>";
                                      } else if($data_ticket['status'] == "Opened"){
                                          echo "<span class='badge badge-primary'>Opened</span>";
                                      } else if($data_ticket['status'] == "Closed"){
                                          echo "<span class='badge badge-success'>Closed</span>";
                                      }
                                      ?>
                                  </div>
                                  <br />
                                  <form method="POST">
                                  <button class="btn btn-secondary btn-lg" type="submit" name="closed">Close Ticket</button>
                                  </form>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- Container-fluid Ends-->
        </div>
<?php
				include("../../lib/footer.php");
			}
		} else {
			header("Location: ".$cfg_baseurl."admin/tickets.php");
		}
	}
} else {
	header("Location: ".$cfg_baseurl);
}
?>