<?php

require 'header.php';

if ( !isset($_REQUEST['p']) ) exit();
if ( !isset($_REQUEST['t']) ) exit();
$patternname = $_REQUEST['p'];
$targets = $_REQUEST['t'];

class PatternColor {
    public $red = 0;
    public $green = 0;
    public $blue = 0;
    public $resttime = 0;
    public function __construct($r = 0, $g = 0, $b = 0, $rest = 0) {
        $this->red = $r;
        $this->green = $g;
        $this->blue = $b;
        $this->resttime = $rest;
    }
}

$patternid = 0;
$ramptime = 0;
$query = "SELECT id, ramptime FROM patterns WHERE name=:name";
$sth = $globaldbh->prepare($query);
$sth->bindValue(":name", $patternname, PDO::PARAM_STR);
$sth->execute();

if ( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
    $patternid = $row['id'];
    $ramptime = $row['ramptime'];
}
if ( $patternid == 0 ) exit();

$query = "SELECT id, red, green, blue, resttime FROM patterncolors WHERE pattern_id=:pattern_id ORDER BY id";
$sth = $globaldbh->prepare($query);
$sth->bindValue(":pattern_id", (int) $patternid, PDO::PARAM_INT);
$sth->execute();

$colors = array();
while ( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
    $colors[] = new PatternColor($row['red'], $row['green'], $row['blue'], $row['resttime']);
}
if ( count($colors) == 0 ) exit();

$command = 0x02;

foreach ( $targets as $target ) {
    $unique = mt_rand(1, 2000000000);
    $data = pack("LLLCL", PACKETFILTER[0], PACKETFILTER[1], $unique, $command, $target);
    $data .= pack("LC", $ramptime, count($colors));
    foreach ( $colors as $color ) {
        $data .= pack("CCCL", $color->red, $color->green, $color->blue, $color->resttime);
    }
    transmitMessage($data);
}

exit();