<?php

// ============================================================
// MANAGER DASHBOARD API
// File: api/manager_dashboard.php
//
// users.id                 = VARCHAR e.g. EMP031
// users.reporting_manager  = VARCHAR e.g. matches the manager's
//                            username (NOT reporting_manager_id)
// daily_reports.user_id     = VARCHAR e.g. EMP031 / BS05
//
// FIX (aligned with myteam.php / manager_team.php):
// The team query used to filter by u.reporting_manager_id, an
// int/FK column that isn't reliably populated for every
// employee — that's why some managers saw 0 or the wrong team.
// It now matches on u.reporting_manager (varchar) against the
// manager's own username, case-insensitive, exactly like
// myteam.php / manager_team.php already do.
// ============================================================

error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');

// ============================================================
// HEADERS
// ============================================================

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

// ============================================================
// CORS
// ============================================================

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

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

// ============================================================
// FATAL ERROR HANDLER
// ============================================================

register_shutdown_function(
    function () {

        $error = error_get_last();

        if (
            $error !== null &&
            in_array(
                $error['type'],
                [
                    E_ERROR,
                    E_PARSE,
                    E_CORE_ERROR,
                    E_COMPILE_ERROR
                ],
                true
            )
        ) {

            if (!headers_sent()) {
                header(
                    'Content-Type: application/json; charset=UTF-8'
                );

                http_response_code(500);
            }

            echo json_encode(
                [
                    'success' => false,
                    'message' => 'PHP Fatal Error',
                    'error' => $error['message'],
                    'file' => basename($error['file']),
                    'line' => $error['line']
                ],
                JSON_UNESCAPED_UNICODE |
                JSON_UNESCAPED_SLASHES
            );
        }
    }
);

// ============================================================
// DATABASE
// ============================================================

require_once '../config.php';

// ============================================================
// UPLOADS BASE URL
// ============================================================

$base_url = 'https://spica.mybelief.in/uploads';

// ============================================================
// BUILD FULL PHOTO URL
// ============================================================

function buildPhotoUrl(
    string $photoPath,
    string $baseUrl
): string {

    $photoPath = trim($photoPath);

    if ($photoPath === '') {
        return '';
    }

    if (
        stripos($photoPath, 'http://') === 0 ||
        stripos($photoPath, 'https://') === 0
    ) {
        return $photoPath;
    }

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

    return rtrim($baseUrl, '/') . '/' . $photoPath;
}

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

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

// ============================================================
// READ REQUEST
// ============================================================

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

$data = [];

if ($rawData !== false && trim($rawData) !== '') {

    $decodedData = json_decode($rawData, true);

    if (
        json_last_error() === JSON_ERROR_NONE &&
        is_array($decodedData)
    ) {
        $data = $decodedData;
    }
}

if (!empty($_POST)) {
    $data = array_merge($data, $_POST);
}

// ============================================================
// GET MANAGER ID
// ============================================================

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

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

// ============================================================
// DATE
// ============================================================

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

// ============================================================
// GET MANAGER
//
// We now also fetch `username` so we can match employees by
// reporting_manager (varchar) against it, and `reporting_manager`
// is NOT selected here since managers themselves don't need it.
// ============================================================

$stmt = $conn->prepare("
    SELECT
        id,
        username,
        role,
        first_name,
        last_name,
        designation,
        photo,
        profile_photo,
        work_location,
        Company
    FROM users
    WHERE id = ?
    LIMIT 1
");

if (!$stmt) {

    $error = $conn->error;
    $conn->close();

    sendResponse(500, false, 'Unable to prepare manager query.', [
        'error' => $error
    ]);
}

$stmt->bind_param('s', $managerId);

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

    $error = $stmt->error;
    $stmt->close();
    $conn->close();

    sendResponse(500, false, 'Unable to execute manager query.', [
        'error' => $error
    ]);
}

$result = $stmt->get_result();

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

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

    sendResponse(404, false, 'Manager not found.', [
        'debug' => ['received_user_id' => $managerId]
    ]);
}

$manager = $result->fetch_assoc();

$stmt->close();

// ============================================================
// CHECK ROLE
// ============================================================

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

if ($role !== 'manager') {

    $conn->close();

    sendResponse(403, false, 'This dashboard is available only for managers.', [
        'debug' => [
            'user_id' => $managerId,
            'role' => $role
        ]
    ]);
}

// ============================================================
// MANAGER USERNAME
//
// This is what employees' reporting_manager column is matched
// against, exactly like myteam.php / manager_team.php.
// ============================================================

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

// ============================================================
// MANAGER NAME
// ============================================================

$managerName = trim(
    ($manager['first_name'] ?? '') . ' ' . ($manager['last_name'] ?? '')
);

if ($managerName === '') {
    $managerName = $manager['username'] ?? $managerId;
}

// ============================================================
// MANAGER PHOTO
// ============================================================

$managerPhoto = '';

if (!empty(trim((string)($manager['profile_photo'] ?? '')))) {
    $managerPhoto = trim((string)$manager['profile_photo']);
} elseif (!empty(trim((string)($manager['photo'] ?? '')))) {
    $managerPhoto = trim((string)$manager['photo']);
}

$managerPhoto = buildPhotoUrl($managerPhoto, $base_url);

// ============================================================
// MANAGER OWN ATTENDANCE DEFAULT
// ============================================================

$managerAttendance = [
    'daily_report_id' => null,
    'has_checked_in' => false,
    'has_checked_out' => false,
    'status' => 'not_checked_in',
    'login_time' => null,
    'logout_time' => null,
    'daily_working_hours' => 0,
    'latitude' => null,
    'longitude' => null,
    'location_type' => null,
    'location_address' => null
];

// ============================================================
// MANAGER OWN ATTENDANCE
// ============================================================

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

if ($attendanceStmt) {

    $attendanceStmt->bind_param('ss', $managerId, $today);

    if ($attendanceStmt->execute()) {

        $attendanceResult = $attendanceStmt->get_result();

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

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

            $attendanceStatus = 'not_checked_in';

            if ($hasCheckedIn) {
                $attendanceStatus = 'checked_in';
            }

            if ($hasCheckedOut) {
                $attendanceStatus = 'checked_out';
            }

            $managerAttendance = [
                'daily_report_id' => (string)($attendanceRow['id'] ?? ''),
                'has_checked_in' => $hasCheckedIn,
                'has_checked_out' => $hasCheckedOut,
                'status' => $attendanceStatus,
                'login_time' => $attendanceRow['login_time'],
                'logout_time' => $attendanceRow['logout_time'],
                'daily_working_hours' => (float)($attendanceRow['daily_working_hours'] ?? 0),
                'latitude' => $attendanceRow['latitude'] !== null ? (float)$attendanceRow['latitude'] : null,
                'longitude' => $attendanceRow['longitude'] !== null ? (float)$attendanceRow['longitude'] : null,
                'location_type' => $attendanceRow['location_type'],
                'location_address' => $attendanceRow['location_address']
            ];
        }
    }

    $attendanceStmt->close();
}

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

$teamMembers = [];

$teamStmt = $conn->prepare("
    SELECT
        id,
        username,
        role,
        first_name,
        last_name,
        designation,
        photo,
        profile_photo,
        work_location
    FROM users
    WHERE LOWER(reporting_manager) = LOWER(?)
      AND LOWER(status) = 'active'
      AND LOWER(role) IN ('employee', 'manager')
    ORDER BY username ASC
");

if (!$teamStmt) {

    $error = $conn->error;
    $conn->close();

    sendResponse(500, false, 'Unable to prepare manager team query.', [
        'error' => $error
    ]);
}

$teamStmt->bind_param('s', $managerUsername);

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

    $error = $teamStmt->error;
    $teamStmt->close();
    $conn->close();

    sendResponse(500, false, 'Unable to execute manager team query.', [
        'error' => $error
    ]);
}

$teamResult = $teamStmt->get_result();

// ============================================================
// PROCESS TEAM
// ============================================================

while ($teamUser = $teamResult->fetch_assoc()) {

    $employeeId = trim((string)($teamUser['id'] ?? ''));

    if ($employeeId === '') {
        continue;
    }

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

    if ($employeeName === '') {
        $employeeName = $teamUser['username'] ?? $employeeId;
    }

    // ========================================================
    // PHOTO
    // ========================================================

    $employeePhoto = '';

    if (!empty(trim((string)($teamUser['profile_photo'] ?? '')))) {
        $employeePhoto = trim((string)$teamUser['profile_photo']);
    } elseif (!empty(trim((string)($teamUser['photo'] ?? '')))) {
        $employeePhoto = trim((string)$teamUser['photo']);
    }

    $employeePhoto = buildPhotoUrl($employeePhoto, $base_url);

    // ========================================================
    // ATTENDANCE DEFAULT
    // ========================================================

    $attendanceData = [
        'status' => 'not_checked_in',
        'login_time' => null,
        'logout_time' => null,
        'daily_working_hours' => 0,
        'latitude' => null,
        'longitude' => null,
        'location_type' => null,
        'location_address' => null
    ];

    // ========================================================
    // EMPLOYEE ATTENDANCE
    // ========================================================

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

    if ($employeeAttendanceStmt) {

        $employeeAttendanceStmt->bind_param('ss', $employeeId, $today);

        if ($employeeAttendanceStmt->execute()) {

            $employeeAttendanceResult = $employeeAttendanceStmt->get_result();

            if ($row = $employeeAttendanceResult->fetch_assoc()) {

                $attendanceStatus = 'not_checked_in';

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

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

                $attendanceData = [
                    'status' => $attendanceStatus,
                    'login_time' => $row['login_time'],
                    'logout_time' => $row['logout_time'],
                    'daily_working_hours' => (float)($row['daily_working_hours'] ?? 0),
                    'latitude' => $row['latitude'] !== null ? (float)$row['latitude'] : null,
                    'longitude' => $row['longitude'] !== null ? (float)$row['longitude'] : null,
                    'location_type' => $row['location_type'],
                    'location_address' => $row['location_address']
                ];
            }
        }

        $employeeAttendanceStmt->close();
    }

    // ========================================================
    // RESPONSIBILITY SUMMARY (KRA daily updates)
    // ========================================================

    $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
    // ========================================================

    $pendingKpiCount = 0;

    $kpiStmt = $conn->prepare("
        SELECT
            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()) {
            $pendingKpiCount = (int)$kpiRow['pending_count'];
        }

        $kpiStmt->close();
    }

    // ========================================================
    // ADD TEAM MEMBER
    // ========================================================

    $teamMembers[] = [

        'user_id' => $employeeId,
        'username' => $teamUser['username'],
        'name' => $employeeName,
        'designation' => $teamUser['designation'] ?? '',
        'role' => strtolower(trim((string)($teamUser['role'] ?? ''))),
        'photo' => $employeePhoto,
        'profile_photo' => $employeePhoto,
        'work_location' => $teamUser['work_location'] ?? '',

        'attendance' => $attendanceData,

        'responsibilities' => $responsibilitySummary,

        'pending_kpi_approvals' => $pendingKpiCount
    ];
}

$teamStmt->close();

// ============================================================
// SUMMARY
// ============================================================

$totalTeam = count($teamMembers);
$presentTodayCount = 0;
$checkedOutCount = 0;
$notCheckedInCount = 0;
$currentlyWorkingCount = 0;
$pendingResponsibilityReviews = 0;
$pendingKpiApprovals = 0;

foreach ($teamMembers as $member) {

    $status = $member['attendance']['status'] ?? 'not_checked_in';

    if ($status === 'not_checked_in') {
        $notCheckedInCount++;
    } elseif ($status === 'checked_in') {
        $presentTodayCount++;
        $currentlyWorkingCount++;
    } elseif ($status === 'checked_out') {
        $presentTodayCount++;
        $checkedOutCount++;
    }

    $pendingResponsibilityReviews += (int)($member['responsibilities']['pending_review'] ?? 0);
    $pendingKpiApprovals += (int)($member['pending_kpi_approvals'] ?? 0);
}

// ============================================================
// TEAM LOCATIONS
// ============================================================

$teamLocations = [];

foreach ($teamMembers as $member) {

    $attendance = $member['attendance'];

    if ($attendance['latitude'] !== null && $attendance['longitude'] !== null) {

        $teamLocations[] = [
            'user_id' => $member['user_id'],
            'username' => $member['username'],
            'name' => $member['name'],
            'attendance_status' => $attendance['status'],
            'latitude' => (float)$attendance['latitude'],
            'longitude' => (float)$attendance['longitude'],
            'location_type' => $attendance['location_type'],
            'location_address' => $attendance['location_address']
        ];
    }
}

// ============================================================
// SUMMARY FOR FLUTTER
// ============================================================

$summary = [
    'total_team' => $totalTeam,
    'present_today' => $presentTodayCount,
    'absent_today' => $notCheckedInCount,
    'checked_out_today' => $checkedOutCount,
    'currently_working' => $currentlyWorkingCount,
    'pending_responsibility_reviews' => $pendingResponsibilityReviews,
    'pending_kpi_approvals' => $pendingKpiApprovals
];

$teamSummary = [
    'total_team_members' => $totalTeam,
    'today_attendance_count' => $presentTodayCount,
    'currently_working' => $currentlyWorkingCount,
    'checked_out' => $checkedOutCount,
    'not_checked_in' => $notCheckedInCount,
    'pending_responsibility_reviews' => $pendingResponsibilityReviews,
    'pending_kpi_approvals' => $pendingKpiApprovals
];

// ============================================================
// RESPONSE
// ============================================================

$responseData = [

    'date' => $today,

    'manager' => [
        'user_id' => (string)$manager['id'],
        'username' => $manager['username'],
        'name' => $managerName,
        'first_name' => $manager['first_name'] ?? '',
        'last_name' => $manager['last_name'] ?? '',
        'designation' => $manager['designation'] ?? 'Manager',
        'role' => $role,
        'photo' => $managerPhoto,
        'profile_photo' => $managerPhoto,
        'work_location' => $manager['work_location'] ?? '',
        'company' => $manager['Company'] ?? ''
    ],

    'own_attendance' => $managerAttendance,

    'summary' => $summary,

    'team_summary' => $teamSummary,

    'team_members' => $teamMembers,

    'team_locations' => $teamLocations,

    'unread_notifications' => 0
];

// ============================================================
// CLOSE DB
// ============================================================

$conn->close();

// ============================================================
// SUCCESS
// ============================================================

sendResponse(200, true, 'Manager dashboard loaded successfully.', $responseData);
?>