<?php

namespace App\Services;

use App\Core\Database;

class HomepageHealthService
{

public static function score(
int $conferenceId
)
{

$db=
Database::getInstance();

$s=
$db
->prepare("

SELECT
COUNT(*)

FROM
conference_home_sections

WHERE conference_id=?

");

$s
->execute([

$conferenceId

]);

$sections=
(int)
$s
->fetchColumn();

$b=
$db
->prepare("

SELECT
COUNT(*)

FROM
conference_homepage_blocks

WHERE conference_id=?

");

$b
->execute([

$conferenceId

]);

$blocks=
(int)
$b
->fetchColumn();

$score=
40;

$score+=
min(
30,
$sections*2
);

$score+=
min(
30,
$blocks
);

return [

'score'=>
min(
100,
$score
),

'sections'=>
$sections,

'blocks'=>
$blocks

];

}

public static function dashboard(
int $conferenceId
): array
{

$db=
Database::getInstance();

$out=[];

$checks=[

'sections'=>

"

SELECT COUNT(*)

FROM conference_home_sections

WHERE conference_id=?

",

'blocks'=>

"

SELECT COUNT(*)

FROM conference_homepage_blocks

WHERE conference_id=?

",

'jobs'=>

"

SELECT COUNT(*)

FROM conference_home_jobs

WHERE conference_id=?

AND job_state='pending'

",

'deploy'=>

"

SELECT COUNT(*)

FROM conference_home_deployments

WHERE conference_id=?

"

];

foreach(
$checks
as $k=>$sql
){

$stmt=
$db
->prepare(
$sql
);

$stmt
->execute([

$conferenceId

]);

$out[
$k
]=
(int)
$stmt
->fetchColumn();

}

$out[
'status'
]=

$out[
'blocks'
]
>0

?

'healthy'

:

'warning';

return
$out;

}

public static function recover(
int $conferenceId
): bool
{

$db=
Database::getInstance();

return
$db
->prepare("

INSERT INTO
conference_home_recovery(

conference_id,

recovery_type,

recovery_result

)

VALUES(

?,

'auto',

'success'

)

")

->execute([

$conferenceId

]);

}

}
