<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect(); // Connect to the database

set_time_limit(0); // Set time limit for the script execution
ob_implicit_flush(true); // Turn off output buffering
ini_set('display_errors', 1); // Show errors for debugging
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

echo 'slat_m2 계산 작업 시작 <br>';

try {
    // Fetch num and slatlist columns from the output table
    $output_sql = "SELECT num, slatlist FROM chandj.output";
    $output_stmt = $pdo->prepare($output_sql);
    $output_stmt->execute();
    $output_results = $output_stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($output_results as $output_row) {
        $output_num = $output_row['num'];
        $slatlist_data = json_decode($output_row['slatlist'], true);
        $total_slat_m2 = 0;

        // Loop through each item in slatlist to calculate the total area
        if (is_array($slatlist_data)) {
            foreach ($slatlist_data as $item) {
                $cutwidth = trim($item['cutwidth']);
                $cutheight = trim($item['cutheight']);
                $number = trim($item['number']);
                
                // Calculate the area in square meters for each item
                $item_m2 = ($cutwidth / 1000) * ($cutheight / 1000) * $number;
                $total_slat_m2 += $item_m2; // Sum up all areas
            }
        }

        // Update the output table with the calculated slat_m2
        $update_sql = "UPDATE chandj.output SET slat_m2 = :slat_m2 WHERE num = :num";
        $update_stmt = $pdo->prepare($update_sql);
        $update_stmt->bindParam(':slat_m2', $total_slat_m2, PDO::PARAM_STR);
        $update_stmt->bindParam(':num', $output_num, PDO::PARAM_INT);

        if (!$update_stmt->execute()) {
            echo "Error updating record num $output_num: " . implode(", ", $update_stmt->errorInfo()) . "<br>";
        } else {
            echo "Record num $output_num updated successfully. slat_m2: $total_slat_m2<br>";
        }
    }

    echo "All records processed.";
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>
</body>
</html>
