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

$conn = getDbConnection();

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

// ✅ Read JSON input
$data = json_decode(file_get_contents("php://input"), true);
file_put_contents('patrol_log_debug.log', "Received Data:\n" . print_r($data, true), FILE_APPEND);

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

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

// ✅ Insert into Patrol Logs Table
$stmt = $conn->prepare("INSERT INTO patrols (user_id, site_id, org_id, tag_name) VALUES (?, ?, ?, ?)");
$stmt->bind_param("iiis", $user_id, $site_id, $org_id, $tag_name);
$success = $stmt->execute();

if ($success) {
    echo json_encode(["success" => true, "message" => "Patrol Log Saved"]);
} else {
    echo json_encode(["success" => false, "message" => "Failed to Save Patrol Log"]);
}

$conn->close();
?>
