<?php
/**
 * Seo Redirect class
 *
 * The Seo Redirect class contains method which redirects to a new URL.
 *
 * @author Aivars Francis | mtc.
 * @version 2014-01-12
 */

use Illuminate\Database\Eloquent\Model;

class SeoRedirect extends Model {

    /**
     * Table name
     * @var string
     */
    protected $table = 'seo_redirects';

   /**
     * Disable eloquent default timestamp columns
     * @var bool
     */
    public $timestamps = false;

    /**
     * Mass-assignable table attributes
     * @var array
     */
    protected $fillable = [
        'old_url',  
        'new_url',  
        'hits', 
        'code'
    ];

    /**
     * List with redirect codes
     * @var array
     */
    public static $redirect_codes = [
        '301' => 'Moved Permanently',
        '302' => 'Found',
        '303' => 'See Other',
        '307' => 'Moved Temporarily'

    ];

    /**
     * Redirects page to new url
     * @param string $path
     */
    public static function redirectToPage($path) {
        $redirect = SeoRedirect::where('old_url', '=', $path);
        //match with some rule
        if ($redirect->count() > 0) {
            //get rule
            $redirect = $redirect->first();
            $redirect->hits += 1;
            $redirect->update();
            header("Location: " . $redirect->new_url, true, $redirect->code);
            exit();
        }
    }
}
