<?php

// ============================================================
// GET TEAM ATTENDANCE API  (FIXED — CORRECT TEAM MATCHING + PHOTO + LOCATION)
// File: api/get_team_attendance.php
//
// Method: POST
//
// JSON:
// {
//     "user_id": "EMP031",
//     "date": "2026-07-25"   // OPTIONAL. Defaults to today.
// }
//
// ------------------------------------------------------------
// FIX (team matching): matches on the TEXT column
// `reporting_manager` (manager's username), same as
// dashboard_manager.php.
// ------------------------------------------------------------
// FIX (photo not showing): buildPhotoUrl() strips a leading
// "uploads/" segment before prepending PHOTO_BASE_URL, so it
// never produces ".../uploads/uploads/xxx.jpg".
// ------------------------------------------------------------
// FIX (location missing): dr.location_address and dr.latitude /
// dr.longitude are now selected and returned per team member, so
// the app can show where each person checked in from.
// ------------------------------------------------------------
// ============================================================

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

const OFFICE_START_TIME    = '09:30:00';
const HALF_DAY_CUTOFF_TIME = '13:00:00';

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

// ============================================================
// BUILD PHOTO URL  (no more double /uploads/uploads/)
// ============================================================

function buildPhotoUrl(?string $photo): ?string {

    $photo = trim((string)$photo);

    if ($photo === '') {
        return null;
    }

    if (str_starts_with($photo, 'http://') || str_starts_with($photo, 'https://')) {
        return $photo;
    }

    $photo = ltrim($photo, '/');

    if (stripos($photo, 'uploads/') === 0) {
        $photo = substr($photo, strlen('uploads/'));
    }

    return PHOTO_BASE_URL . $photo;
}

function isValidStringId(string $id): bool {
    return $id !== ''
        && strlen($id) <= 30
        && preg_match('/^[A-Za-z0-9_\-]+$/', $id) === 1;
}

function classifyAttendance(?string $loginTime, ?string $logoutTime): array {
    $isLate = false;
    $isHalfDay = false;

    if (!empty($loginTime)) {
        $loginClock = date('H:i:s', strtotime($loginTime));
        $isLate = $loginClock > OFFICE_START_TIME;
    }

    if (!empty($logoutTime)) {
        $logoutClock = date('H:i:s', strtotime($logoutTime));
        $isHalfDay = $logoutClock <= HALF_DAY_CUTOFF_TIME;
    }

    return ['late' => $isLate, 'half_day' => $isHalfDay];
}

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  (accepts user_id OR manager_id)
// ============================================================

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

if (!isValidStringId($managerId)) {
    $conn->close();
    sendResponse(400, false, "Valid manager 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;
}

// ============================================================
// VALIDATE MANAGER  (also grabs username, needed for team match)
// ============================================================

$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 attendance.");
}

$managerUsername = trim((string)($manager['username'] ?? ''));

// ============================================================
// TEAM ATTENDANCE FOR SELECTED DATE
//
// Team match uses the same rule as dashboard_manager.php:
//   LOWER(TRIM(u.reporting_manager)) = LOWER(TRIM(<manager username>))
//
// FIX: dr.location_address, dr.latitude, dr.longitude added so
// the app can display each member's check-in location.
// ============================================================

$attStmt = $conn->prepare("
    SELECT
        u.id            AS user_id,
        u.username      AS username,
        u.role          AS role,
        u.photo         AS photo,
        u.profile_photo AS profile_photo,
        dr.login_time,
        dr.logout_time,
        dr.photo_path,
        dr.location_type,
        dr.location_address,
        dr.latitude,
        dr.longitude,
        dr.client_name,
        dr.daily_working_hours
    FROM users u
    LEFT JOIN daily_reports dr
           ON dr.user_id = u.id
          AND dr.report_date = ?
    WHERE LOWER(TRIM(u.reporting_manager)) = LOWER(TRIM(?))
      AND LOWER(TRIM(u.role)) IN ('employee', 'manager')
    ORDER BY u.username ASC
");

if (!$attStmt) {
    $conn->close();
    sendResponse(500, false, "Unable to load team attendance.");
}

$attStmt->bind_param("ss", $selectedDate, $managerUsername);
$attStmt->execute();
$attResult = $attStmt->get_result();

$teamAttendance = [];
$teamSize = 0;
$checkedIn = 0;
$checkedOut = 0;
$lateCount = 0;
$halfDayCount = 0;
$absentCount = 0;

while ($row = $attResult->fetch_assoc()) {

    $teamSize++;

    $flags = classifyAttendance($row['login_time'], $row['logout_time']);

    $hasCheckedIn  = !empty($row['login_time']);
    $hasCheckedOut = !empty($row['logout_time']);

    if ($hasCheckedIn) {
        $checkedIn++;
        if ($flags['late']) {
            $lateCount++;
        }
    } else {
        $absentCount++;
    }

    if ($hasCheckedOut) {
        $checkedOut++;
        if ($flags['half_day']) {
            $halfDayCount++;
        }
    }

    $status = 'absent';
    if ($hasCheckedIn && $hasCheckedOut) {
        $status = 'checked_out';
    } elseif ($hasCheckedIn) {
        $status = 'checked_in';
    }

    $photoUrl = buildPhotoUrl($row['profile_photo'] ?? null);
    if ($photoUrl === null) {
        $photoUrl = buildPhotoUrl($row['photo'] ?? null);
    }
    if ($photoUrl === null) {
        $photoUrl = buildPhotoUrl($row['photo_path'] ?? null);
    }

    // ----------------------------------------------------------
    // LOCATION — prefer the saved address text; fall back to
    // raw lat/lng as a display string if no address was saved.
    // ----------------------------------------------------------

    $locationLabel = trim((string)($row['location_address'] ?? ''));

    if ($locationLabel === '' &&
        $row['latitude'] !== null &&
        $row['longitude'] !== null
    ) {
        $locationLabel = number_format((float)$row['latitude'], 5) .
            ', ' . number_format((float)$row['longitude'], 5);
    }

    if ($locationLabel === '') {
        $locationLabel = null;
    }

    $teamAttendance[] = [
        "user_id"    => (string)$row['user_id'],
        "username"   => $row['username'],
        "employee_name" => $row['username'],
        "role"       => strtolower(trim($row['role'] ?? '')),

        "photo_path"    => $photoUrl,
        "profile_photo" => $photoUrl,
        "photo"         => $photoUrl,

        "login_time"  => $row['login_time'],
        "logout_time" => $row['logout_time'],

        "status"      => $status,
        "is_late"     => $flags['late'],
        "is_half_day" => $flags['half_day'],

        "location_type"    => $row['location_type'],
        "location_address" => $row['location_address'],
        "location_name"    => $locationLabel,
        "latitude"         => $row['latitude'] !== null ? (float)$row['latitude'] : null,
        "longitude"        => $row['longitude'] !== null ? (float)$row['longitude'] : null,

        "client_name"   => $row['client_name'],
        "daily_working_hours" => $row['daily_working_hours'] !== null
            ? (float)$row['daily_working_hours']
            : null,
    ];
}

$attStmt->close();
$conn->close();

sendResponse(
    200,
    true,
    "Team attendance loaded successfully.",
    [
        "date" => $selectedDate,
        "is_today" => ($selectedDate === $today),

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

        "summary" => [
            "team_size" => $teamSize,
            "checked_in" => $checkedIn,
            "checked_out" => $checkedOut,
            "late_count" => $lateCount,
            "half_day_count" => $halfDayCount,
            "absent_count" => $absentCount,
        ],

        "team_attendance" => $teamAttendance,
    ]
);

?>