<?php
require 'config.php';
header("Content-Type: application/json");

$conn = getDbConnection();

// ✅ Enable error logging for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', 'hourly_check_error.log');

// ✅ Read JSON input
$data = json_decode(file_get_contents("php://input"), true);

// ✅ Validate required fields
if (!isset($data['token'], $data['site_id'], $data['org_id'], $data['real_name'])) {
    echo json_encode(["success" => false, "message" => "Missing required fields"]);
    exit();
}

$token = $data['token'];
$site_id = intval($data['site_id']);
$org_id = intval($data['org_id']); // ✅ Added organization ID
$real_name = trim($data['real_name']);
$personal_safety = isset($data['personal_safety']) ? (int)$data['personal_safety'] : 0;
$site_secure = isset($data['site_secure']) ? (int)$data['site_secure'] : 0;
$equipment_functional = isset($data['equipment_functional']) ? (int)$data['equipment_functional'] : 0;
$comments = isset($data['comments']) ? trim($data['comments']) : NULL;

// ✅ Validate token and get user ID
$stmt = $conn->prepare("SELECT user_id FROM users WHERE token = ?");
$stmt->bind_param("s", $token);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if (!$user) {
    echo json_encode(["success" => false, "message" => "Invalid token"]);
    exit();
}

$user_id = $user['user_id'];

// ✅ Insert into database
$stmt = $conn->prepare("
    INSERT INTO hourly_check 
    (user_id, site_id, org_id, real_name, personal_safety, site_secure, equipment_functional, comments, check_time) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");

$stmt->bind_param("iiisiiis", $user_id, $site_id, $org_id, $real_name, $personal_safety, $site_secure, $equipment_functional, $comments);
$success = $stmt->execute();

if ($success) {
    echo json_encode(["success" => true, "message" => "Hourly check submitted successfully"]);
} else {
    echo json_encode(["success" => false, "message" => "Failed to submit hourly check"]);
}

$conn->close();
?>
