<?php
namespace Passport\Lib;

use Dever;

class Code
{
    private $width;

    private $height;

    public $code;

    public $mcode;

    public $string;

    private $image;

    public function __construct($width = '160', $height = '30')
    {
        $this->width = $width;
        $this->height = $height;
    }

    public function create()
    {
        header("Content-type: image/png");
        $this->createCode();
        $this->createImage();
        $this->createPix();
        $this->write();
        imagepng($this->image);
        imagedestroy($this->image);
    }

    public function createM()
    {
        $len = isset(Dever::config('base', 'project')->mobileCode['length']) ? Dever::config('base', 'project')->mobileCode['length'] : 4;
        $this->createRand($len);
    }

    private function createImage()
    {
        $this->image = @imagecreate($this->width, $this->height);
        $back = imagecolorallocate($this->image, 255, 255, 255);
        $border = imagecolorallocate($this->image, 0, 0, 0);
        imagefilledrectangle($this->image, 0, 0, $this->width - 1, $this->height - 1, $back);
        imagerectangle($this->image, 0, 0, $this->width - 1, $this->height - 1, $border);
    }

    private function createPix()
    {
        for ($i = 0; $i <= 200; $i++) {
            imagesetpixel($this->image, rand(2, $this->width), rand(2, $this->height), imagecolorallocate($this->image, rand(0, 255), rand(0, 255), rand(0, 255)));
        }
    }

    public function createRand($length)
    {
        $this->mcode = null;
        $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $str = '0123456789';
        $max = strlen($str) - 1;

        for ($i = 0; $i < $length; $i++) {
            $this->mcode .= $str[rand(0, $max)]; //rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }
    }

    private function createCode()
    {
        $cal = array
            (
            array('+', '+'),
            array('-', '-'),
            //array('*', '乘以'),
            //array('/', '除以'),
        );
        $index = array_rand($cal);

        $m1 = rand(1, 100);
        $m2 = rand(1, 100);

        $this->string = $m1 . $cal[$index][1] . $m2 . '';

        $this->code = '$this->code = ' . $m1 . $cal[$index][0] . $m2 . ';';

        eval($this->code);
    }

    private function write()
    {
        $length = strlen($this->string);
        for ($i = 0; $i < $length; $i++) {
            $bg_color = imagecolorallocate($this->image, rand(0, 255), rand(0, 128), rand(0, 255));
            $x = floor($this->width / $length) * $i;
            $y = rand(0, $this->height - 15);
            imagechar($this->image, rand(5, 5), $x + 5, $y, $this->string[$i], $bg_color);
        }
    }

    public function __destruct()
    {
        unset($this->width, $this->height, $this->image);
    }
}