<?php

// ============================================================
// GET TEAM LOCATIONS API  (UPDATED — STRING user_id SUPPORT)
// File: api/get_team_locations.php
//
// Method: POST
//
// JSON:
// {
//     "user_id": "EMP1023",
//     "date": "2026-07-20"   // OPTIONAL. Defaults to today.
// }
//
// CHANGES vs previous version:
//  1. user_id (manager id) is now handled as a STRING throughout —
//     trimmed, length-checked (<=30, matches VARCHAR(30)), charset
//     checked — NEVER cast with (int). This matches the users.id /
//     reporting_manager_id column type (VARCHAR), which is why the
//     old (int) cast was turning every id into 0 and the API kept
//     saying "Valid user_id is required" / returning no team at all
//     (and therefore no photos either).
//  2. All bind_param() calls involving user_id / employee id now use
//     "s" instead of "i".
//  3. Team query still selects `photo` and the response still sends
//     photo_path / profile_photo / photo aliases.
//  4. Date-wise lookup (from the previous update) is preserved.
// ============================================================

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

const PHOTO_BASE_URL = 'https://spica.mybelief.in/uploads/';

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();
}

function buildPhotoUrl(?string $photo): ?string {
    if (empty(trim((string)$photo))) {
        return null;
    }
    if (str_starts_with($photo, 'http://') || str_starts_with($photo, 'https://')) {
        return $photo;
    }
    return PHOTO_BASE_URL . ltrim($photo, '/');
}

// ============================================================
// VALID STRING ID CHECK
// Matches VARCHAR(30) columns: letters, digits, dash, underscore.
// Adjust the regex here if your IDs use other characters.
// ============================================================
function isValidStringId(string $id): bool {
    return $id !== ''
        && strlen($id) <= 30
        && preg_match('/^[A-Za-z0-9_\-]+$/', $id) === 1;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(405, false, "Only POST method is allowed.");
}

$rawData = file_get_contents("php://input");
$data = json_decode($rawData, true);
if (!is_array($data)) {
    $data = $_POST;
}

// ============================================================
// MANAGER USER ID — STRING, NOT INT
// ============================================================

$managerId = trim((string)($data['user_id'] ?? ''));

if (!isValidStringId($managerId)) {
    $conn->close();
    sendResponse(400, false, "Valid user_id is required.");
}

// ============================================================
// SELECTED DATE (defaults to today)
// ============================================================

$requestedDate = trim((string)($data['date'] ?? ''));
$today = date('Y-m-d');

if ($requestedDate === '') {
    $selectedDate = $today;
} else {
    $ts = strtotime($requestedDate);
    $selectedDate = $ts !== false ? date('Y-m-d', $ts) : $today;
}

$isToday = ($selectedDate === $today);

// ============================================================
// VALIDATE MANAGER  (id bound as string)
// ============================================================

$stmt = $conn->prepare("SELECT id, username, role FROM users WHERE id = ? LIMIT 1");
if (!$stmt) {
    $conn->close();
    sendResponse(500, false, "Unable to validate manager.");
}
$stmt->bind_param("s", $managerId);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) {
    $stmt->close();
    $conn->close();
    sendResponse(404, false, "Manager not found.");
}
$manager = $result->fetch_assoc();
$stmt->close();

$role = strtolower(trim($manager['role'] ?? ''));
if ($role !== 'manager') {
    $conn->close();
    sendResponse(403, false, "Only managers can access team locations.");
}

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

$liveLocationTableExists = false;
$tableCheck = $conn->query("SHOW TABLES LIKE 'employee_live_locations'");
if ($tableCheck && $tableCheck->num_rows > 0) {
    $liveLocationTableExists = true;
}

// ============================================================
// GET DIRECT TEAM  (reporting_manager_id bound as string, photo selected)
// ============================================================

$stmt = $conn->prepare("
    SELECT
        id,
        username,
        role,
        photo
    FROM users
    WHERE reporting_manager_id = ?
      AND LOWER(TRIM(role)) IN ('employee', 'manager')
    ORDER BY username ASC
");
if (!$stmt) {
    $conn->close();
    sendResponse(500, false, "Unable to load manager team.");
}
$stmt->bind_param("s", $managerId);
$stmt->execute();
$result = $stmt->get_result();

$teamLocations = [];
$totalTeamMembers = 0;
$currentlyWorking = 0;
$notCurrentlyWorking = 0;
$locationAvailable = 0;
$locationUnavailable = 0;
$liveLocationAvailable = 0;
$checkinLocationFallback = 0;

while ($employee = $result->fetch_assoc()) {

    $totalTeamMembers++;

    // STRING employee id — no (int) cast
    $employeeId = (string)$employee['id'];
    $employeeRole = strtolower(trim($employee['role'] ?? ''));
    $photoUrl = buildPhotoUrl($employee['photo'] ?? null);

    // ========================================================
    // ATTENDANCE FOR THE SELECTED DATE  (user_id bound as string)
    // ========================================================

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

    if (!$attendanceStmt) {
        $notCurrentlyWorking++;
        continue;
    }

    $attendanceStmt->bind_param("ss", $employeeId, $selectedDate);
    $attendanceStmt->execute();
    $attendanceResult = $attendanceStmt->get_result();

    if ($attendanceResult->num_rows === 0) {
        $attendanceStmt->close();
        $notCurrentlyWorking++;
        continue;
    }

    $attendance = $attendanceResult->fetch_assoc();
    $attendanceStmt->close();

    if (empty($attendance['login_time'])) {
        $notCurrentlyWorking++;
        continue;
    }

    $wasFullDayDone = !empty($attendance['logout_time']);

    if ($isToday && $wasFullDayDone) {
        $notCurrentlyWorking++;
        continue;
    }

    if ($isToday && !$wasFullDayDone) {
        $currentlyWorking++;
    }

    // ========================================================
    // DEFAULT LOCATION = check-in GPS for that date
    // ========================================================

    $currentLatitude = $attendance['latitude'];
    $currentLongitude = $attendance['longitude'];
    $currentAddress = $attendance['location_address'];
    $lastUpdated = $attendance['login_time'];
    $locationSource = 'checkin';

    // ========================================================
    // LIVE LOCATION — ONLY MEANINGFUL FOR TODAY (user_id bound as string)
    // ========================================================

    if ($isToday && $liveLocationTableExists) {

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

        if ($liveStmt) {
            $liveStmt->bind_param("s", $employeeId);
            $liveStmt->execute();
            $liveResult = $liveStmt->get_result();

            if ($liveResult->num_rows > 0) {
                $liveLocation = $liveResult->fetch_assoc();

                if ($liveLocation['latitude'] !== null && $liveLocation['longitude'] !== null) {
                    $currentLatitude = $liveLocation['latitude'];
                    $currentLongitude = $liveLocation['longitude'];

                    if (!empty(trim($liveLocation['location_address'] ?? ''))) {
                        $currentAddress = $liveLocation['location_address'];
                    }

                    $lastUpdated = $liveLocation['last_updated'];
                    $locationSource = 'live';
                }
            }
            $liveStmt->close();
        }
    }

    $hasLocation = $currentLatitude !== null && $currentLongitude !== null;

    if ($hasLocation) {
        $locationAvailable++;
        if ($locationSource === 'live') {
            $liveLocationAvailable++;
        } else {
            $checkinLocationFallback++;
        }
    } else {
        $locationUnavailable++;
    }

    $teamLocations[] = [

        "user_id" => $employeeId,
        "employee_name" => $employee['username'],
        "username" => $employee['username'],
        "role" => $employeeRole,

        // photo — under every alias the Flutter app checks for
        "photo_path" => $photoUrl,
        "profile_photo" => $photoUrl,
        "photo" => $photoUrl,

        "attendance" => [
            "daily_report_id" => (string)$attendance['id'],
            "report_date" => $attendance['report_date'],
            "status" => ($isToday && !$wasFullDayDone) ? "currently_working" : "day_completed",
            "attendance_status" => "checked_in",
            "login_time" => $attendance['login_time'],
            "logout_time" => $attendance['logout_time'],
        ],

        "location" => [
            "available" => $hasLocation,
            "latitude" => $currentLatitude !== null ? (float)$currentLatitude : null,
            "longitude" => $currentLongitude !== null ? (float)$currentLongitude : null,
            "location_type" => $attendance['location_type'],
            "location_address" => $currentAddress,
            "client_name" => $attendance['client_name'],
            "source" => $locationSource,
            "updated_at" => $lastUpdated,
        ],

        "checkin_location" => [
            "latitude" => $attendance['latitude'] !== null ? (float)$attendance['latitude'] : null,
            "longitude" => $attendance['longitude'] !== null ? (float)$attendance['longitude'] : null,
            "location_type" => $attendance['location_type'],
            "location_address" => $attendance['location_address'],
            "client_name" => $attendance['client_name'],
        ],

        "latitude" => $currentLatitude !== null ? (float)$currentLatitude : null,
        "longitude" => $currentLongitude !== null ? (float)$currentLongitude : null,
        "location_address" => $currentAddress,
        "location_type" => $attendance['location_type'],
        "client_name" => $attendance['client_name'],
        "location_source" => $locationSource,
        "last_updated" => $lastUpdated,
    ];
}

$stmt->close();

$notCurrentlyWorking = max(0, $totalTeamMembers - $currentlyWorking);

$conn->close();

sendResponse(
    200,
    true,
    "Team locations loaded successfully.",
    [
        "date" => $selectedDate,
        "is_today" => $isToday,

        "manager" => [
            "user_id" => (string)$manager['id'],
            "username" => $manager['username'],
            "role" => $role,
        ],

        "summary" => [
            "total_team_members" => $totalTeamMembers,
            "currently_working" => $currentlyWorking,
            "not_currently_working" => $notCurrentlyWorking,
            "location_available" => $locationAvailable,
            "location_unavailable" => $locationUnavailable,
            "live_location_available" => $liveLocationAvailable,
            "checkin_location_fallback" => $checkinLocationFallback,
        ],

        "team_locations" => $teamLocations,
    ]
);

?>