<?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']);
  $limit = 10;
  $offset = (isset($_GET['page']) ? (int)$_GET['page']-1 : 0) * $limit;
  $totalpages = 0;
  $res = [];

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

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

  $q = mysqli_real_escape_string($mysqli, $q);
  $tq = explode(' ', $q);
  $lq = '';
  foreach ($tq as $k => $v) {
    $lq .= "title LIKE '%$v%' OR body LIKE '%$v%'";
    if ($k != array_key_last($tq)) $lq .= " OR ";
  }

  $tp = mysqli_query($mysqli, "SELECT COUNT(1) FROM website_page WHERE $lq;");
  $totalpages = (int)mysqli_fetch_row($tp)[0];
  unset($tp);

  if ($pages = mysqli_prepare($mysqli, "SELECT * FROM website_page WHERE $lq LIMIT ? OFFSET ?")) {
    mysqli_stmt_bind_param($pages, "ii", $limit, $offset);
    mysqli_stmt_execute($pages);
    mysqli_stmt_bind_result($pages, $wpid, $webid, $pageurl, $pagetit, $pagebody);
    mysqli_execute($pages);

    while (mysqli_stmt_fetch($pages)) {
      $cq = preg_split('/(\ |\+)/i', $q);
      $cpreg = '(';
      foreach ($cq as $k => $v) {
        $cpreg .= $v;
        if ($k != array_key_last($cq)) $cpreg .= '|';
      }
      $cpreg .= ')';
      $tmpbody = '';

      foreach ($cq as $k => $v) {
        $tmpbody .= '…'.mb_substr(mb_stristr($pagebody, $v, true), -120);
        $tmpbody .= mb_substr($pagebody, mb_stripos($pagebody, $v), 120).'… ';
      }

      $pagebody = preg_replace('/'.$cpreg.'/i', '<span class="result-mark">$1</span>', $tmpbody);
      $pagetit = preg_replace('/'.$cpreg.'/i', '<span class="result-mark">$1</span>', $pagetit);

      $res[] = [
        'url' => $pageurl,
        'title' => $pagetit,
        'body' => $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 } ?>

      <hr />
<?php for ($i = 1; $i <= ceil($totalpages/$limit); $i++) { ?>
      <a class="pagination" href="/search.php?q=<?php echo $q; ?>&page=<?php echo $i; ?>"><?php echo $i; ?></a>
<?php } ?>

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