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

$conn = getDbConnection();

// ✅ Enable error logging (for debugging, uncomment when needed)
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', 'clock_in_errors.log'); // Ensure logs are recorded

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

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

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

$user_id = intval($data['user_id']);
$site_id = intval($data['site_id']);
$org_id = intval($data['org_id']);
$clock_in_tag = trim($data['clock_in_tag']);

// ✅ Check if the user is already on-site (latest clock-in record)
$stmt = $conn->prepare("SELECT is_on_site FROM clock_in WHERE user_id = ? ORDER BY clock_in_time DESC LIMIT 1");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$stmt->close();

if ($row && $row['is_on_site'] == 1) {
    echo json_encode(["success" => false, "message" => "Already Booked On! Please Clock Out first."]);
    exit();
}

// ✅ Insert new Book On record
$stmt = $conn->prepare("INSERT INTO clock_in (user_id, site_id, org_id, clock_in_tag, is_on_site, clock_in_time) VALUES (?, ?, ?, ?, 1, NOW())");
$stmt->bind_param("iiis", $user_id, $site_id, $org_id, $clock_in_tag);
$success = $stmt->execute();
$stmt->close();

if ($success) {
    echo json_encode(["success" => true, "message" => "Book On Successful"]);
} else {
    echo json_encode(["success" => false, "message" => "Failed to Book On", "error" => $conn->error]);
}

$conn->close();
?>
