<?php

header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

date_default_timezone_set('Asia/Kolkata');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once '../config.php';

function sendResponse(
    int $statusCode,
    bool $success,
    string $message,
    array $extra = []
): void {

    http_response_code($statusCode);

    echo json_encode(
        array_merge(
            [
                "success" => $success,
                "message" => $message
            ],
            $extra
        ),
        JSON_UNESCAPED_UNICODE |
        JSON_UNESCAPED_SLASHES
    );

    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {

    sendResponse(
        405,
        false,
        "Only POST method is allowed."
    );
}

// ============================================================
// READ JSON / FORM DATA
// ============================================================

$rawData = file_get_contents("php://input");

$data = json_decode(
    $rawData,
    true
);

if (!is_array($data)) {
    $data = $_POST;
}

// ============================================================
// INPUT
// ============================================================

$userId = (int)(
    $data['user_id'] ?? 0
);

$latitude =
    $data['latitude'] ?? null;

$longitude =
    $data['longitude'] ?? null;

$locationAddress = trim(
    $data['location_address'] ?? ''
);

// ============================================================
// VALIDATE USER ID
// ============================================================

if ($userId <= 0) {

    $conn->close();

    sendResponse(
        400,
        false,
        "Valid user_id is required."
    );
}

// ============================================================
// VALIDATE LOCATION
// ============================================================

if (
    $latitude === null ||
    $longitude === null
) {

    $conn->close();

    sendResponse(
        400,
        false,
        "Latitude and longitude are required."
    );
}

if (
    !is_numeric($latitude) ||
    !is_numeric($longitude)
) {

    $conn->close();

    sendResponse(
        400,
        false,
        "Invalid latitude or longitude."
    );
}

$latitude =
    (float)$latitude;

$longitude =
    (float)$longitude;

if (
    $latitude < -90 ||
    $latitude > 90
) {

    $conn->close();

    sendResponse(
        400,
        false,
        "Invalid latitude range."
    );
}

if (
    $longitude < -180 ||
    $longitude > 180
) {

    $conn->close();

    sendResponse(
        400,
        false,
        "Invalid longitude range."
    );
}

$today =
    date('Y-m-d');

$updatedAt =
    date('Y-m-d H:i:s');

// ============================================================
// VALIDATE USER
// ============================================================

$stmt = $conn->prepare("
    SELECT
        id,
        username,
        role
    FROM users
    WHERE id = ?
    LIMIT 1
");

if (!$stmt) {

    $conn->close();

    sendResponse(
        500,
        false,
        "Unable to validate user."
    );
}

$stmt->bind_param(
    "i",
    $userId
);

$stmt->execute();

$result =
    $stmt->get_result();

if (
    $result->num_rows === 0
) {

    $stmt->close();

    $conn->close();

    sendResponse(
        404,
        false,
        "User not found."
    );
}

$user =
    $result->fetch_assoc();

$stmt->close();

// ============================================================
// NORMALIZE ROLE
// ============================================================

$role = strtolower(
    trim(
        $user['role'] ?? ''
    )
);

// ============================================================
// ALLOWED ROLES
// ============================================================

$allowedRoles = [
    'employee',
    'manager',
    'hr',
    'md',
    'superadmin'
];

if (
    !in_array(
        $role,
        $allowedRoles,
        true
    )
) {

    $conn->close();

    sendResponse(
        403,
        false,
        "Your account is not allowed to use live location tracking."
    );
}

// ============================================================
// GET TODAY ATTENDANCE
// ============================================================

$stmt = $conn->prepare("
    SELECT
        id,
        report_date,
        login_time,
        logout_time,
        latitude,
        longitude,
        location_address
    FROM daily_reports
    WHERE user_id = ?
      AND report_date = ?
    ORDER BY id DESC
    LIMIT 1
");

if (!$stmt) {

    $conn->close();

    sendResponse(
        500,
        false,
        "Unable to check attendance."
    );
}

$stmt->bind_param(
    "is",
    $userId,
    $today
);

$stmt->execute();

$result =
    $stmt->get_result();

if (
    $result->num_rows === 0
) {

    $stmt->close();

    $conn->close();

    sendResponse(
        403,
        false,
        "You must check in before live location can be updated."
    );
}

$attendance =
    $result->fetch_assoc();

$stmt->close();

$dailyReportId =
    (int)$attendance['id'];

// ============================================================
// MUST BE CHECKED IN
// ============================================================

if (
    empty(
        $attendance['login_time']
    )
) {

    $conn->close();

    sendResponse(
        403,
        false,
        "Attendance check-in is required before updating live location."
    );
}

// ============================================================
// STOP AFTER CHECKOUT
// ============================================================

if (
    !empty(
        $attendance['logout_time']
    )
) {

    $conn->close();

    sendResponse(
        403,
        false,
        "Attendance already checked out. Live location tracking has stopped."
    );
}

// ============================================================
// CHECK LIVE LOCATION TABLE
// ============================================================

$tableExists = false;

$tableCheck =
    $conn->query("
        SHOW TABLES
        LIKE 'employee_live_locations'
    ");

if (
    $tableCheck &&
    $tableCheck->num_rows > 0
) {

    $tableExists = true;
}

// ============================================================
// LIVE LOCATION TABLE NOT FOUND
//
// We intentionally do NOT overwrite:
//
// daily_reports.latitude
// daily_reports.longitude
//
// because these are original check-in coordinates.
// ============================================================

if (!$tableExists) {

    $conn->close();

    sendResponse(
        500,
        false,
        "Live location table is not configured. Please create employee_live_locations table."
    );
}

// ============================================================
// START TRANSACTION
// ============================================================

$conn->begin_transaction();

try {

    // ========================================================
    // UPDATE / INSERT LIVE LOCATION
    //
    // employee_live_locations.user_id should be UNIQUE.
    // ========================================================

    $stmt = $conn->prepare("
        INSERT INTO employee_live_locations
        (
            user_id,
            latitude,
            longitude,
            location_address,
            last_updated
        )
        VALUES
        (
            ?,
            ?,
            ?,
            ?,
            NOW()
        )

        ON DUPLICATE KEY UPDATE

            latitude =
                VALUES(latitude),

            longitude =
                VALUES(longitude),

            location_address =
                CASE

                    WHEN
                        VALUES(location_address) <> ''

                    THEN
                        VALUES(location_address)

                    ELSE
                        location_address

                END,

            last_updated =
                NOW()
    ");

    if (!$stmt) {

        throw new Exception(
            "Unable to prepare live location update."
        );
    }

    $stmt->bind_param(
        "idds",
        $userId,
        $latitude,
        $longitude,
        $locationAddress
    );

    if (
        !$stmt->execute()
    ) {

        $error =
            $stmt->error;

        $stmt->close();

        throw new Exception(
            "Unable to update live location. " .
            $error
        );
    }

    $stmt->close();

    // ========================================================
    // READ SAVED LIVE LOCATION
    // ========================================================

    $stmt = $conn->prepare("
        SELECT
            user_id,
            latitude,
            longitude,
            location_address,
            last_updated
        FROM employee_live_locations
        WHERE user_id = ?
        LIMIT 1
    ");

    if (!$stmt) {

        throw new Exception(
            "Unable to retrieve updated live location."
        );
    }

    $stmt->bind_param(
        "i",
        $userId
    );

    $stmt->execute();

    $result =
        $stmt->get_result();

    $liveLocation =
        null;

    if (
        $result->num_rows > 0
    ) {

        $liveLocation =
            $result->fetch_assoc();
    }

    $stmt->close();

    // ========================================================
    // COMMIT
    // ========================================================

    $conn->commit();

    // ========================================================
    // BUILD RESPONSE
    // ========================================================

    $responseData = [

        "user" => [

            "user_id" =>
                (string)$userId,

            "username" =>
                $user['username'],

            "role" =>
                $role
        ],

        "attendance" => [

            "daily_report_id" =>
                (string)$dailyReportId,

            "report_date" =>
                $today,

            "login_time" =>
                $attendance[
                    'login_time'
                ],

            "logout_time" =>
                null,

            "status" =>
                "checked_in",

            "attendance_status" =>
                "checked_in"
        ],

        // ====================================================
        // ORIGINAL CHECK-IN LOCATION
        //
        // This is preserved in daily_reports.
        // ====================================================

        "checkin_location" => [

            "latitude" =>
                $attendance[
                    'latitude'
                ],

            "longitude" =>
                $attendance[
                    'longitude'
                ],

            "location_address" =>
                $attendance[
                    'location_address'
                ]
        ],

        // ====================================================
        // CURRENT LIVE LOCATION
        // ====================================================

        "location" => [

            "latitude" =>
                $liveLocation !== null
                    ? (float)$liveLocation[
                        'latitude'
                    ]
                    : $latitude,

            "longitude" =>
                $liveLocation !== null
                    ? (float)$liveLocation[
                        'longitude'
                    ]
                    : $longitude,

            "location_address" =>
                $liveLocation !== null
                    ? $liveLocation[
                        'location_address'
                    ]
                    : $locationAddress,

            "updated_at" =>
                $liveLocation !== null
                    ? $liveLocation[
                        'last_updated'
                    ]
                    : $updatedAt
        ],

        "tracking" => [

            "is_active" =>
                true,

            "checked_in" =>
                true,

            "checked_out" =>
                false
        ]
    ];

    $conn->close();

    sendResponse(
        200,
        true,
        "Live location updated successfully.",
        $responseData
    );

} catch (
    Throwable $e
) {

    $conn->rollback();

    $conn->close();

    sendResponse(
        500,
        false,
        $e->getMessage()
    );
}

?>