<?php
    $prefix = Config::get('DB_PREFIX');
    $tableName = Plugin::getConfig('imgedit', 'database')['name'];
    $database = DatabaseFactory::getFactory()->getConnection();

    $searchterm = '';

    $sql = "SELECT SQL_CALC_FOUND_ROWS
                id,
                name,
                created,
                type,
                alt,
                title,
                tags,
                userid,
                filter
            FROM ".$prefix.$tableName."
            WHERE (name LIKE CONCAT('%', :search, '%')
               OR  alt LIKE CONCAT('%', :search, '%')
               OR  title LIKE CONCAT('%', :search, '%')
               OR  tags LIKE CONCAT('%', :search, '%')
                  )
            ORDER BY created DESC";

    $query = $database->prepare($sql);
    $query->bindParam(':search',    $searchterm,        PDO::PARAM_STR);
    $query->execute();

    $results = array();
    if ($query->rowCount() < 1) {
        $results['number'] = 0;
    } else {
        $results['number'] = $database->query("SELECT FOUND_ROWS()")->fetchColumn();
    }

    $i = 0;
    $results['img'] = array();
    foreach ($query->fetchAll() as $img) {
        $year = date("Y",strtotime($img->created));
        $week = date("W",strtotime($img->created));

        $results['img'][$i]             = new stdClass();
        $results['img'][$i]->id         = $img->id;
        $results['img'][$i]->name       = $img->name;
        $results['img'][$i]->created    = $img->created;
        $results['img'][$i]->year       = $year;
        $results['img'][$i]->week       = $week;
        $results['img'][$i]->created    = $img->created;
        $results['img'][$i]->type       = $img->type;
        $results['img'][$i]->alt        = $img->alt;
        $results['img'][$i]->title      = $img->title;
        $results['img'][$i]->tags       = $img->tags;
        $results['img'][$i]->userid     = $img->userid;
        $results['img'][$i]->filter     = $img->filter;
        $i++;
    }

    echo json_encode($results);
?>
