<?php
  if (!isset($_GET['q']) || $_GET['q'] == '') {
    header('Location: /');
    die();
  }

  require_once('../helper.php');
  require_once('../config.php');

  $title = $_GET['q'].'の検索';
  $linktype = 'side';
  $q = htmlspecialchars($_GET['q']);
  $res = [];

  $mysqli = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME);

  if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
  }

  if ($pages = mysqli_prepare($mysqli, "SELECT * FROM website_page WHERE title LIKE ? OR body LIKE ?")) {
    $lq = "%$q%";
    mysqli_stmt_bind_param($pages, "ss", $lq, $lq);
    mysqli_stmt_execute($pages);
    mysqli_stmt_bind_result($pages, $wpid, $webid, $pageurl, $pagetit, $pagebody);
    mysqli_execute($pages);

    while (mysqli_stmt_fetch($pages)) {
      $cq = strtoupper($q);
      $pagetit = preg_replace('/'.$cq.'/i', '<b>'.$cq.'</b>', $pagetit);
      $pagebody = preg_replace('/'.$cq.'/i', '<b>'.$cq.'</b>', $pagebody);

      $res[] = [
        'url' => $pageurl,
        'title' => $pagetit,
        'body' => strlen($pagebody) > 100 ? substr($pagebody, 0, 100).'…' : $pagebody
      ];
    }

    mysqli_stmt_close($pages);
  }

  mysqli_close($mysqli);

  require_once('../include/header.php');
  require_once('../include/menu.php');
?>

      <hr />
      <div class="form">
        <form action="/search.php" method="get">
          <input type="text" name="q" value="<?php echo $q; ?>" />
          <input type="submit" value="送信" />
        </form>
      </div>
      <hr />

<?php foreach ($res as $r) { ?>
      <div class="result">
        <a href="<?php echo $r['url']; ?>">
          <span class="result-url"><?php echo $r['url']; ?></span>
          <div class="result-title"><?php echo $r['title']; ?></div>
          <div class="result-description"><?php echo $r['body']; ?></div>
        </a>
      </div>
<?php } ?>

<?php
  require_once('../include/footer.php');
?>
