<?php

// ============================================================
// MANAGER TEAM API
// File: api/manager_team.php
//
// Method: POST
//
// JSON:
// {
//     "user_id": "MGR001"
// }
//
// FIX (aligned with myteam.php / dashboard_manager.php):
// The old version filtered by u.reporting_manager_id (an int/FK
// column) which isn't reliably populated for every employee.
// That's why the app was showing 0 / wrong team members.
//
// This version matches on the `reporting_manager` VARCHAR column
// against the manager's `username`, case-insensitive — exactly
// like myteam.php does. So we first look up the manager's own
// username from users.id, then filter the team by that username.
//
// Returns manager's direct team with:
// - Employee details (flattened for the Flutter app)
// - Today's attendance
// - Working status
// - Daily working hours
// - Responsibility progress
// - Pending KPI approvals
//
// NOTE:
// user_id / manager id are STRING (VARCHAR(30)), e.g. EMP001,
// BS01, HR01. Never cast to int, never compared numerically,
// always bound as "s" in prepared statements.
// ============================================================

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

// ============================================================
// RESPONSE FUNCTION
// ============================================================

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

// ============================================================
// ONLY POST
// ============================================================

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

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

// ============================================================
// READ INPUT
// ============================================================

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

$data = json_decode($rawData, true);

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

// ============================================================
// MANAGER ID (string, e.g. EMP001, HR01, MD01)
// ============================================================

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

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

if (strlen($managerId) > 30) {
    $conn->close();
    sendResponse(400, false, "user_id must not exceed 30 characters.");
}

if (!preg_match('/^[A-Za-z0-9_\-]+$/', $managerId)) {
    $conn->close();
    sendResponse(400, false, "user_id contains invalid characters.");
}

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

// ============================================================
// PHOTO URL HELPER
// ============================================================

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

    return 'https://spica.mybelief.in/' . $photo;
}

try {

    // ============================================================
    // VALIDATE MANAGER
    //
    // We need BOTH:
    //  - id            (to keep responding with the same user_id)
    //  - username       (to match against users.reporting_manager,
    //                    exactly like myteam.php / dashboard_manager.php)
    //  - role           (must be 'manager')
    // ============================================================

    $stmt = $conn->prepare("
        SELECT
            id,
            username,
            role,
            CONCAT(COALESCE(first_name,''),' ',COALESCE(last_name,'')) AS full_name
        FROM users
        WHERE id = ?
        LIMIT 1
    ");

    if (!$stmt) {
        throw new Exception("Unable to prepare manager validation.");
    }

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

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

    // ============================================================
    // GET DIRECT TEAM
    //
    // FIX: match on reporting_manager (varchar) = manager's
    // username, case-insensitive — same as myteam.php — instead
    // of the unreliable reporting_manager_id FK column.
    // ============================================================

    $stmt = $conn->prepare("
        SELECT
            u.id,
            u.username,
            u.role,
            u.first_name,
            u.last_name,
            u.email,
            u.mobileno,
            d.division_name,
            des.designation_name
        FROM users u
        LEFT JOIN divisions d ON u.division_id = d.id
        LEFT JOIN designations des ON u.designation_id = des.id
        WHERE LOWER(u.reporting_manager) = LOWER(?)
          AND u.status = 'active'
          AND LOWER(u.role) IN ('employee', 'manager')
        ORDER BY u.first_name ASC
    ");

    if (!$stmt) {
        throw new Exception("Unable to load team. Please verify the reporting_manager column.");
    }

    $stmt->bind_param("s", $managerUsername);
    $stmt->execute();
    $result = $stmt->get_result();

    $team = [];

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

        $employeeId = trim($employee['id']);

        $employeeName = trim(
            ($employee['first_name'] ?? '') . ' ' . ($employee['last_name'] ?? '')
        );

        // ========================================================
        // DEFAULT ATTENDANCE (flattened)
        // ========================================================

        $attendanceStatus       = "not_checked_in";
        $loginTime               = null;
        $logoutTime              = null;
        $dailyWorkingHours        = 0;
        $currentLatitude          = null;
        $currentLongitude         = null;
        $locationType             = null;
        $locationAddress          = null;
        $clientName               = null;

        $attendanceStmt = $conn->prepare("
            SELECT
                id,
                login_time,
                logout_time,
                daily_working_hours,
                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) {

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

            if ($attendanceRow = $attendanceResult->fetch_assoc()) {

                if (!empty($attendanceRow['login_time'])) {
                    $attendanceStatus = "checked_in";
                }

                if (!empty($attendanceRow['logout_time'])) {
                    $attendanceStatus = "checked_out";
                }

                if ($attendanceStatus === 'checked_out') {
                    $currentLatitude  = $attendanceRow['logout_latitude'];
                    $currentLongitude = $attendanceRow['logout_longitude'];
                } else {
                    $currentLatitude  = $attendanceRow['latitude'];
                    $currentLongitude = $attendanceRow['longitude'];
                }

                $loginTime         = $attendanceRow['login_time'];
                $logoutTime        = $attendanceRow['logout_time'];
                $dailyWorkingHours = (float)($attendanceRow['daily_working_hours'] ?? 0);
                $locationType      = $attendanceRow['location_type'];
                $locationAddress   = $attendanceRow['location_address'];
                $clientName        = $attendanceRow['client_name'];
            }

            $attendanceStmt->close();
        }

        // ========================================================
        // RESPONSIBILITY SUMMARY
        // ========================================================

        $responsibilitySummary = [
            "total"             => 0,
            "morning_started"   => 0,
            "evening_completed" => 0,
            "pending_review"    => 0
        ];

        $responsibilityStmt = $conn->prepare("
            SELECT
                COUNT(DISTINCT dr.id) AS total_count,
                COUNT(DISTINCT CASE WHEN dru.morning_checked = 1 THEN dr.id END) AS morning_count,
                COUNT(DISTINCT CASE WHEN dru.evening_completed = 1 THEN dr.id END) AS evening_count,
                COUNT(DISTINCT CASE WHEN dru.status = 'evening_submitted' THEN dr.id END) AS pending_review_count
            FROM daily_responsibilities dr
            LEFT JOIN daily_responsibility_updates dru
                ON dru.responsibility_id = dr.id
               AND dru.user_id = dr.user_id
               AND dru.report_date = ?
            WHERE dr.user_id = ?
              AND dr.is_active = 1
              AND (dr.start_date IS NULL OR dr.start_date <= ?)
              AND (dr.end_date IS NULL OR dr.end_date >= ?)
        ");

        if ($responsibilityStmt) {

            $responsibilityStmt->bind_param("ssss", $today, $employeeId, $today, $today);
            $responsibilityStmt->execute();
            $responsibilityResult = $responsibilityStmt->get_result();

            if ($responsibilityRow = $responsibilityResult->fetch_assoc()) {
                $responsibilitySummary = [
                    "total"             => (int)$responsibilityRow['total_count'],
                    "morning_started"   => (int)$responsibilityRow['morning_count'],
                    "evening_completed" => (int)$responsibilityRow['evening_count'],
                    "pending_review"    => (int)$responsibilityRow['pending_review_count']
                ];
            }

            $responsibilityStmt->close();
        }

        // ========================================================
        // KPI SUMMARY
        // ========================================================

        $kpiSummary = [
            "submitted"        => 0,
            "manager_approved" => 0,
            "pending_approval" => 0
        ];

        $kpiStmt = $conn->prepare("
            SELECT
                COUNT(CASE WHEN status = 'submitted' THEN 1 END) AS submitted_count,
                COUNT(CASE WHEN status = 'manager_approved' OR manager_approved = 1 THEN 1 END) AS approved_count,
                COUNT(CASE WHEN status = 'submitted' AND manager_approved = 0 THEN 1 END) AS pending_count
            FROM kpi_actuals
            WHERE user_id = ?
        ");

        if ($kpiStmt) {

            $kpiStmt->bind_param("s", $employeeId);
            $kpiStmt->execute();
            $kpiResult = $kpiStmt->get_result();

            if ($kpiRow = $kpiResult->fetch_assoc()) {
                $kpiSummary = [
                    "submitted"        => (int)$kpiRow['submitted_count'],
                    "manager_approved" => (int)$kpiRow['approved_count'],
                    "pending_approval" => (int)$kpiRow['pending_count']
                ];
            }

            $kpiStmt->close();
        }

        // ========================================================
        // MONTHLY WORKING HOURS
        // ========================================================

        $monthlyHours = [
            "total_working_hours"   => 0,
            "total_working_minutes" => 0,
            "total_working_days"    => 0
        ];

        $currentYear  = (int)date('Y');
        $currentMonth = (int)date('m');

        $monthlyStmt = $conn->prepare("
            SELECT
                total_working_hours,
                total_working_minutes,
                total_working_days
            FROM monthly_working_hours
            WHERE user_id = ?
              AND year = ?
              AND month = ?
            LIMIT 1
        ");

        if ($monthlyStmt) {

            $monthlyStmt->bind_param("sii", $employeeId, $currentYear, $currentMonth);
            $monthlyStmt->execute();
            $monthlyResult = $monthlyStmt->get_result();

            if ($monthlyRow = $monthlyResult->fetch_assoc()) {
                $monthlyHours = [
                    "total_working_hours"   => (float)$monthlyRow['total_working_hours'],
                    "total_working_minutes" => (int)$monthlyRow['total_working_minutes'],
                    "total_working_days"    => (int)$monthlyRow['total_working_days']
                ];
            }

            $monthlyStmt->close();
        }

        // ========================================================
        // ADD EMPLOYEE
        //
        // IMPORTANT: fields below are FLATTENED (top-level) to
        // match what ManagerTeamScreen (Flutter) reads directly,
        // e.g. employee['employee_name'], employee['attendance_status'],
        // employee['latitude'], employee['location_name'], etc.
        // Nested summaries are still included for future use.
        // ========================================================

        $team[] = [

            // --- flat fields the Flutter screen reads directly ---
            "user_id"             => $employeeId,
            "username"            => $employee['username'],
            "employee_name"       => $employeeName !== '' ? $employeeName : $employee['username'],
            "name"                => $employeeName !== '' ? $employeeName : $employee['username'],
            "designation"         => $employee['designation_name'] ?: 'Employee',
            "division"            => $employee['division_name'] ?: null,
            "email"               => $employee['email'],
            "mobileno"            => $employee['mobileno'],
            // NOTE: users table has no photo_path column currently.
            // If/when one is added (or stored in another table),
            // wire it up here with buildPhotoUrl($value).
            "photo_path"          => null,

            "role"                => strtolower($employee['role']),

            "attendance_status"   => $attendanceStatus,
            "status"              => $attendanceStatus,
            "login_time"          => $loginTime,
            "check_in"            => $loginTime,
            "logout_time"         => $logoutTime,
            "check_out"           => $logoutTime,
            "daily_working_hours" => $dailyWorkingHours,

            "latitude"            => $currentLatitude,
            "longitude"           => $currentLongitude,
            "location_type"       => $locationType,
            "location_name"       => $locationAddress,
            "current_location"    => $locationAddress,
            "location_address"    => $locationAddress,
            "client_name"         => $clientName,

            // --- nested summaries (kept for future screens) ---
            "attendance" => [
                "status"               => $attendanceStatus,
                "login_time"           => $loginTime,
                "logout_time"          => $logoutTime,
                "daily_working_hours"  => $dailyWorkingHours,
                "latitude"             => $currentLatitude,
                "longitude"            => $currentLongitude,
                "location_type"        => $locationType,
                "location_address"     => $locationAddress,
                "client_name"          => $clientName
            ],

            "responsibility_summary" => $responsibilitySummary,
            "kpi_summary"             => $kpiSummary,
            "monthly_working_hours"   => $monthlyHours
        ];
    }

    $stmt->close();

    // ============================================================
    // TEAM SUMMARY
    // ============================================================

    $totalTeam        = count($team);
    $presentToday     = 0;
    $currentlyWorking = 0;
    $checkedOut       = 0;
    $notCheckedIn     = 0;
    $pendingReviews   = 0;
    $pendingKpis      = 0;

    foreach ($team as $member) {

        $status = $member['attendance_status'];

        if ($status === 'checked_in') {
            $presentToday++;
            $currentlyWorking++;
        } elseif ($status === 'checked_out') {
            $presentToday++;
            $checkedOut++;
        } else {
            $notCheckedIn++;
        }

        $pendingReviews += $member['responsibility_summary']['pending_review'];
        $pendingKpis    += $member['kpi_summary']['pending_approval'];
    }

    $conn->close();

    sendResponse(
        200,
        true,
        "Manager team loaded successfully.",
        [
            "date" => $today,

            "manager" => [
                "user_id"  => $managerId,
                "username" => $manager['username'],
                "name"     => trim($manager['full_name']) ?: $manager['username']
            ],

            "summary" => [
                "total_team_members"            => $totalTeam,
                "present_today"                  => $presentToday,
                "currently_working"               => $currentlyWorking,
                "checked_out"                     => $checkedOut,
                "not_checked_in"                  => $notCheckedIn,
                "pending_responsibility_reviews"  => $pendingReviews,
                "pending_kpi_approvals"           => $pendingKpis
            ],

            // "team" is the key ManagerTeamScreen looks for first
            "team"      => $team,
            "employees" => $team,
            "data"      => $team
        ]
    );

} catch (Throwable $e) {

    $conn->close();

    sendResponse(
        500,
        false,
        "Unable to load manager team. " . $e->getMessage()
    );
}