<?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');


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

// ✅ Validate required fields
$missing_fields = [];
if (!isset($data['user_id'])) $missing_fields[] = 'user_id';
if (!isset($data['site_id'])) $missing_fields[] = 'site_id';
if (!isset($data['org_id'])) $missing_fields[] = 'org_id';
if (!isset($data['clock_out_tag'])) $missing_fields[] = 'clock_out_tag';

if (!empty($missing_fields)) {
    error_log("Missing required fields: " . implode(", ", $missing_fields));
    echo json_encode(["success" => false, "message" => "Missing required fields: " . implode(", ", $missing_fields)]);
    exit();
}

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

// ✅ Check if user is currently clocked in
$stmt = $conn->prepare("SELECT id FROM clock_in WHERE user_id = ? AND site_id = ? AND is_on_site = 1");
$stmt->bind_param("ii", $user_id, $site_id);
$stmt->execute();
$result = $stmt->get_result();
$clock_in_record = $result->fetch_assoc();
$stmt->close();

if (!$clock_in_record) {
    error_log("User ID: $user_id is not clocked in at Site ID: $site_id, cannot clock out");
    echo json_encode(["success" => false, "message" => "User is not clocked in, cannot clock out"]);
    exit();
}

// ✅ Insert clock-out record
$stmt = $conn->prepare("INSERT INTO clock_out (user_id, site_id, org_id, clock_out_tag) VALUES (?, ?, ?, ?)");
$stmt->bind_param("iiis", $user_id, $site_id, $org_id, $clock_out_tag);
$success = $stmt->execute();
$stmt->close();

if ($success) {
    // ✅ Update `is_on_site` status in `clock_in` table
    $stmt = $conn->prepare("UPDATE clock_in SET is_on_site = 0 WHERE user_id = ? AND site_id = ?");
    $stmt->bind_param("ii", $user_id, $site_id);
    $stmt->execute();
    $stmt->close();

    error_log("Clock Out Successful: User ID: $user_id at Site ID: $site_id");
    echo json_encode(["success" => true, "message" => "Clock out successful"]);
} else {
    error_log("Database error: " . $conn->error);
    echo json_encode(["success" => false, "message" => "Failed to clock out"]);
}

$conn->close();
?>
