#!/usr/bin/env php
<?php
// Run on staging: php /tmp/sitesmith-test-entitlement.php
require_once('/docker/whp/web/configs/config.php');
require_once('/docker/whp/web/libs/mysqlmgmt.php');
require_once('/docker/whp/web/libs/Sitesmith.php');

$pdo = (new mysqlmgmt())->getMySQLConnection();
$s = new Sitesmith($pdo);
$T = 'sitesmith_test_user';
$pdo->prepare("INSERT IGNORE INTO whp.client_allowances (username) VALUES (?)")->execute([$T]);
$pdo->prepare("UPDATE whp.client_allowances SET sitesmith_enabled=0, sitesmith_monthly_cap=NULL, sitesmith_bonus_credits=0 WHERE username=?")->execute([$T]);
$pdo->prepare("DELETE FROM whp.sitesmith_usage WHERE username=?")->execute([$T]);

$pass=0;$fail=0;
function eq($w,$g,$d){global $pass,$fail; if($w===$g){$pass++;return;} $fail++; fprintf(STDERR,"FAIL %s: want=%s got=%s\n",$d,$w,$g);}

eq('DISABLED', $s->checkEntitlement($T), 'disabled');
$pdo->prepare("UPDATE whp.client_allowances SET sitesmith_bonus_credits=2 WHERE username=?")->execute([$T]);
eq('OK_BONUS', $s->checkEntitlement($T), 'bonus available');
$pdo->prepare("UPDATE whp.client_allowances SET sitesmith_enabled=1, sitesmith_bonus_credits=0 WHERE username=?")->execute([$T]);
eq('OK_MONTHLY', $s->checkEntitlement($T), 'enabled monthly');
$pdo->prepare("UPDATE whp.client_allowances SET sitesmith_monthly_cap=2 WHERE username=?")->execute([$T]);
$pdo->prepare("INSERT INTO whp.sitesmith_usage (username,site_id,thread_id,message_id,model,consumed_from,created_at) VALUES (?,1,1,1,'x','monthly',NOW()),(?,1,1,1,'x','monthly',NOW())")->execute([$T,$T]);
eq('CAP_REACHED', $s->checkEntitlement($T), 'cap reached');
$pdo->prepare("UPDATE whp.client_allowances SET sitesmith_bonus_credits=1 WHERE username=?")->execute([$T]);
eq('OK_BONUS', $s->checkEntitlement($T), 'bonus bypasses cap');

$pdo->prepare("DELETE FROM whp.sitesmith_usage WHERE username=?")->execute([$T]);
$pdo->prepare("DELETE FROM whp.client_allowances WHERE username=?")->execute([$T]);
echo "$pass passed, $fail failed\n";
exit($fail===0?0:1);
