<?php

class VisitsSync extends Vn\Lib\Method {
	function run($db) {
		$result = $db->query(
			"SELECT id, agent
				FROM visitAgent
					WHERE version = '0.0'
						OR platform = 'unknown'
						OR cookies IS NULL
				ORDER BY id DESC LIMIT 1"
		);

		$stmt = $db->prepare(
			"UPDATE visitAgent
				SET platform = ?,
					browser = ?,
					version = ?,
					javascript = ?,
					cookies = ?
				WHERE id = ?"
		);

		if ($result && $stmt) {
			set_time_limit(0);

			$stmt->bind_param('sssiii'
				,$platform
				,$browser
				,$version
				,$javascript
				,$cookies
				,$id
			);

			// Update the visit info using browscap
			
			$count = 0;

			while ($row = $result->fetch_assoc()) {
				$info = get_browser($row['agent']);
				if (!$info) continue;

				$platform   = $info->platform;
				$browser    = $info->browser;
				$version    = $info->version;
				$javascript = !property_exists($info, 'javascript') || $info->javascript;
				$cookies    = !property_exists($info, 'cookies') || $info->cookies;
				$id         = $row['id'];
				$stmt->execute();
				
				$count++;
			}
			
			echo "$count records updated.\n";
		}

		if ($stmt)
			$stmt->close();
		if ($result)
			$result->free();
	}
}