<?php

// ============================================================
// MD DASHBOARD API
// File: api/md_dashboard.php
//
// POST JSON:
// {
//   "user_id": 10
// }
//
// MD Dashboard:
// - MD Profile
// - MD Own Attendance
// - MD Monthly Working Hours
// - Workforce Summary
// - Today's Attendance Summary
// - Notifications
//
// Other APIs used by Flutter:
// attendance_checkin.php
// attendance_checkout.php
// attendance_summary.php
// get_all_locations.php
// notifications.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';

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

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

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

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

$data =
    json_decode(
        $rawData,
        true
    );

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

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

if ($userId <= 0) {

    $conn->close();

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

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

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

$currentMonth =
    (int)date('n');

// ============================================================
// VALIDATE MD
// ============================================================

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

$md =
    $result->fetch_assoc();

$stmt->close();

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

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

    $conn->close();

    sendResponse(
        403,
        false,
        "Only MD can access MD dashboard."
    );
}

// ============================================================
// MD PROFILE
//
// Currently using username as display name.
// Later we can connect employee_master/profile table
// for full name and profile photo.
// ============================================================

$profile = [

    "user_id" =>
        (string)$md['id'],

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

    "name" =>
        $md['username'],

    "role" =>
        $role,

    "photo_url" =>
        ""
];

// ============================================================
// MD OWN ATTENDANCE DEFAULT
// ============================================================

$myAttendance = [

    "status" =>
        "not_checked_in",

    "attendance_status" =>
        "not_checked_in",

    "daily_report_id" =>
        null,

    "report_date" =>
        $today,

    "login_time" =>
        null,

    "logout_time" =>
        null,

    "daily_working_hours" =>
        0
];

// ============================================================
// GET MD OWN ATTENDANCE
// ============================================================

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

if ($stmt) {

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

    $stmt->execute();

    $result =
        $stmt->get_result();

    if (
        $result->num_rows > 0
    ) {

        $attendance =
            $result->fetch_assoc();

        $attendanceStatus =
            "not_checked_in";

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

            $attendanceStatus =
                "checked_in";
        }

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

            $attendanceStatus =
                "checked_out";
        }

        $myAttendance = [

            "status" =>
                $attendanceStatus,

            "attendance_status" =>
                $attendanceStatus,

            "daily_report_id" =>
                (string)$attendance['id'],

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

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

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

            "daily_working_hours" =>
                (float)(
                    $attendance[
                        'daily_working_hours'
                    ] ?? 0
                )
        ];
    }

    $stmt->close();
}

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

$monthlyWorkingHours = [

    "year" =>
        $currentYear,

    "month" =>
        $currentMonth,

    "month_name" =>
        date('F'),

    "total_working_hours" =>
        0,

    "total_working_minutes" =>
        0,

    "total_working_days" =>
        0
];

$stmt = $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 ($stmt) {

    $stmt->bind_param(
        "iii",
        $userId,
        $currentYear,
        $currentMonth
    );

    $stmt->execute();

    $result =
        $stmt->get_result();

    if (
        $result->num_rows > 0
    ) {

        $row =
            $result->fetch_assoc();

        $monthlyWorkingHours[
            'total_working_hours'
        ] =
            (float)(
                $row[
                    'total_working_hours'
                ] ?? 0
            );

        $monthlyWorkingHours[
            'total_working_minutes'
        ] =
            (int)(
                $row[
                    'total_working_minutes'
                ] ?? 0
            );

        $monthlyWorkingHours[
            'total_working_days'
        ] =
            (int)(
                $row[
                    'total_working_days'
                ] ?? 0
            );
    }

    $stmt->close();
}

// ============================================================
// WORKFORCE COUNTS
// ============================================================

$totalEmployees =
    0;

$totalManagers =
    0;

$totalHR =
    0;

$result = $conn->query("
    SELECT
        LOWER(TRIM(role)) AS normalized_role,
        COUNT(*) AS total
    FROM users
    WHERE LOWER(TRIM(role)) IN (
        'employee',
        'manager',
        'hr'
    )
    GROUP BY
        LOWER(TRIM(role))
");

if ($result) {

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

        $count =
            (int)$row['total'];

        switch (
            $row['normalized_role']
        ) {

            case 'employee':

                $totalEmployees =
                    $count;

                break;

            case 'manager':

                $totalManagers =
                    $count;

                break;

            case 'hr':

                $totalHR =
                    $count;

                break;
        }
    }
}

$totalWorkforce =
    $totalEmployees +
    $totalManagers;

// ============================================================
// TODAY ATTENDANCE SUMMARY
//
// Workforce:
// Employee + Manager
// ============================================================

$present =
    0;

$currentlyWorking =
    0;

$checkedOut =
    0;

$absent =
    0;

// ============================================================
// PRESENT COUNT
// ============================================================

$stmt = $conn->prepare("
    SELECT
        COUNT(
            DISTINCT dr.user_id
        ) AS total
    FROM daily_reports dr
    INNER JOIN users u
        ON u.id = dr.user_id
    WHERE dr.report_date = ?
      AND dr.login_time IS NOT NULL
      AND LOWER(TRIM(u.role)) IN (
          'employee',
          'manager'
      )
");

if ($stmt) {

    $stmt->bind_param(
        "s",
        $today
    );

    $stmt->execute();

    $result =
        $stmt->get_result();

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

        $present =
            (int)$row['total'];
    }

    $stmt->close();
}

// ============================================================
// CURRENTLY WORKING
// ============================================================

$stmt = $conn->prepare("
    SELECT
        COUNT(
            DISTINCT dr.user_id
        ) AS total
    FROM daily_reports dr
    INNER JOIN users u
        ON u.id = dr.user_id
    WHERE dr.report_date = ?
      AND dr.login_time IS NOT NULL
      AND dr.logout_time IS NULL
      AND LOWER(TRIM(u.role)) IN (
          'employee',
          'manager'
      )
");

if ($stmt) {

    $stmt->bind_param(
        "s",
        $today
    );

    $stmt->execute();

    $result =
        $stmt->get_result();

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

        $currentlyWorking =
            (int)$row['total'];
    }

    $stmt->close();
}

// ============================================================
// CHECKED OUT
// ============================================================

$stmt = $conn->prepare("
    SELECT
        COUNT(
            DISTINCT dr.user_id
        ) AS total
    FROM daily_reports dr
    INNER JOIN users u
        ON u.id = dr.user_id
    WHERE dr.report_date = ?
      AND dr.login_time IS NOT NULL
      AND dr.logout_time IS NOT NULL
      AND LOWER(TRIM(u.role)) IN (
          'employee',
          'manager'
      )
");

if ($stmt) {

    $stmt->bind_param(
        "s",
        $today
    );

    $stmt->execute();

    $result =
        $stmt->get_result();

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

        $checkedOut =
            (int)$row['total'];
    }

    $stmt->close();
}

// ============================================================
// ABSENT
// ============================================================

$absent =
    max(
        0,
        $totalWorkforce -
        $present
    );

// ============================================================
// LIVE LOCATION COUNT
// ============================================================

$liveLocationCount =
    0;

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

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

    $stmt = $conn->prepare("
        SELECT
            COUNT(
                DISTINCT ell.user_id
            ) AS total
        FROM employee_live_locations ell
        INNER JOIN users u
            ON u.id = ell.user_id
        INNER JOIN daily_reports dr
            ON dr.user_id = ell.user_id
        WHERE dr.report_date = ?
          AND dr.login_time IS NOT NULL
          AND dr.logout_time IS NULL
          AND LOWER(TRIM(u.role)) IN (
              'employee',
              'manager'
          )
    ");

    if ($stmt) {

        $stmt->bind_param(
            "s",
            $today
        );

        $stmt->execute();

        $result =
            $stmt->get_result();

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

            $liveLocationCount =
                (int)$row['total'];
        }

        $stmt->close();
    }
}

// ============================================================
// NOTIFICATIONS
// ============================================================

$notificationCount =
    0;

$latestNotifications =
    [];

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

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

    // ========================================================
    // Count active MD/all notifications
    // ========================================================

    $stmt = $conn->prepare("
        SELECT
            COUNT(*) AS total
        FROM notifications
        WHERE is_active = 1
          AND (
                expires_at IS NULL
                OR expires_at >= ?
              )
          AND (
                target_type = 'all'
                OR (
                    target_type = 'role'
                    AND LOWER(TRIM(target_value)) = 'md'
                )
                OR (
                    target_type = 'user'
                    AND target_value = ?
                )
              )
    ");

    if ($stmt) {

        $userIdString =
            (string)$userId;

        $stmt->bind_param(
            "ss",
            $today,
            $userIdString
        );

        $stmt->execute();

        $result =
            $stmt->get_result();

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

            $notificationCount =
                (int)$row['total'];
        }

        $stmt->close();
    }

    // ========================================================
    // Latest notifications
    // ========================================================

    $stmt = $conn->prepare("
        SELECT
            id,
            title,
            message,
            type,
            sent_by_name,
            created_at
        FROM notifications
        WHERE is_active = 1
          AND (
                expires_at IS NULL
                OR expires_at >= ?
              )
          AND (
                target_type = 'all'
                OR (
                    target_type = 'role'
                    AND LOWER(TRIM(target_value)) = 'md'
                )
                OR (
                    target_type = 'user'
                    AND target_value = ?
                )
              )
        ORDER BY
            created_at DESC
        LIMIT 5
    ");

    if ($stmt) {

        $userIdString =
            (string)$userId;

        $stmt->bind_param(
            "ss",
            $today,
            $userIdString
        );

        $stmt->execute();

        $result =
            $stmt->get_result();

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

            $latestNotifications[] = [

                "id" =>
                    (string)$row['id'],

                "title" =>
                    $row['title'],

                "message" =>
                    $row['message'],

                "type" =>
                    $row['type'],

                "sent_by_name" =>
                    $row['sent_by_name'],

                "created_at" =>
                    $row['created_at']
            ];
        }

        $stmt->close();
    }
}

// ============================================================
// CLOSE DATABASE
// ============================================================

$conn->close();

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

sendResponse(
    200,
    true,
    "MD dashboard loaded successfully.",
    [

        "date" =>
            $today,

        "profile" =>
            $profile,

        "my_attendance" =>
            $myAttendance,

        "monthly_working_hours" =>
            $monthlyWorkingHours,

        "workforce" => [

            "total_workforce" =>
                $totalWorkforce,

            "total_employees" =>
                $totalEmployees,

            "total_managers" =>
                $totalManagers,

            "total_hr" =>
                $totalHR
        ],

        "attendance_summary" => [

            "present" =>
                $present,

            "absent" =>
                $absent,

            "currently_working" =>
                $currentlyWorking,

            "checked_out" =>
                $checkedOut
        ],

        "location_summary" => [

            "live_location_count" =>
                $liveLocationCount
        ],

        "notifications" => [

            "count" =>
                $notificationCount,

            "latest" =>
                $latestNotifications
        ]
    ]
);

?>