<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");

header("Content-Type: application/json");

$num = isset($_GET['num']) ? $_GET['num'] : '';

$response = ['success' => false];

if ($num) {
    try {
        $pdo = db_connect();

        $sql = "SELECT screenlist FROM chandj.output WHERE num = ?";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $num, PDO::PARAM_INT);
        $stmh->execute();

        $row = $stmh->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            $screenlist = json_decode($row['screenlist'], true);
            if (is_array($screenlist)) {
                $totalCompleted = 0;
                $totalItems = 0;
                $checkQuantity = 0;
				
                foreach ($screenlist as $item) {
                    $totalItems += isset($item['number']) ? (float)$item['number'] : 0;
                    if (isset($item['done_check']) && $item['done_check'] == "1") {
                        $totalCompleted += isset($item['number']) ? (float)$item['number'] : 0;
                    }

					if (
						(isset($item['left_check']) && $item['left_check'] == "1") ||
						(isset($item['right_check']) && $item['right_check'] == "1") ||
						(isset($item['mid_check']) && $item['mid_check'] == "1") ||
						(isset($item['remain_check']) && $item['remain_check'] == "1") ||
						(isset($item['done_check']) && $item['done_check'] == "1")
					) {
						$checkQuantity += isset($item['number']) ? (float)$item['number'] : 0;
					}

                }
                $response['success'] = true;
                $response['totalCompleted'] = $totalCompleted;
                $response['totalItems'] = $totalItems;
                $response['checkQuantity'] = $checkQuantity;
            } else {
                $response['message'] = "Invalid screenlist format";
            }
        } else {
            $response['message'] = "No data found";
        }
    } catch (PDOException $e) {
        $response['message'] = "Error: " . $e->getMessage();
    }
}

echo json_encode($response);
?>
