<?php
header("Content-Type: application/json; charset=UTF-8");
// ============================================================
// EMPLOYEE DASHBOARD API
// File: api/employee_dashboard.php
//
// IMPORTANT:
// users.id is VARCHAR
// Examples:
// EMP031
// BS05
//
// Flutter sends:
// {
//     "user_id": "EMP031"
// }
// ============================================================

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

// ============================================================
// OPTIONS / CORS
// ============================================================

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

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

require_once '../config.php';

// ============================================================
// UPLOADS BASE URL
//
// All employee photos are stored under this path on the
// server. Any relative photo path returned from the database
// (e.g. "EMP031.jpg" or "photos/EMP031.jpg") gets this base
// URL prepended so Flutter always receives a full, ready to
// use image URL.
// ============================================================

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

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

// ============================================================
// BUILD FULL PHOTO URL
//
// Prepends $base_url to a relative photo path.
// If the value is already a full http(s) URL, or empty,
// it is returned unchanged.
// ============================================================

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

    $photoPath = trim($photoPath);

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

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

    // Strip any leading slashes from the stored path
    $photoPath = ltrim($photoPath, '/');

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

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

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

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

// ============================================================
// READ INPUT
//
// Supports:
// - JSON
// - form-data
// - x-www-form-urlencoded
// ============================================================

$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;
    }
}

// Merge normal POST
if (
    !empty($_POST) &&
    is_array($_POST)
) {

    $data = array_merge(
        $data,
        $_POST
    );
}

// ============================================================
// GET USER ID
//
// IMPORTANT:
// DO NOT CONVERT TO INTEGER.
//
// Example:
// EMP031
// BS05
// ============================================================

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

// ============================================================
// VALIDATE USER ID
// ============================================================

if ($userId === '') {

    if (isset($conn)) {
        $conn->close();
    }

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

// ============================================================
// DATE SETTINGS
// ============================================================

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

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

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

$monthKey = date('Y-m');

// ============================================================
// CURRENT WEEK
// Monday -> Sunday
// ============================================================

$currentDayNumber = (int)date('N');

$weekStart = date(
    'Y-m-d',
    strtotime(
        '-' .
        ($currentDayNumber - 1) .
        ' days'
    )
);

$weekEnd = date(
    'Y-m-d',
    strtotime(
        '+' .
        (7 - $currentDayNumber) .
        ' days'
    )
);

// ============================================================
// DEFAULT RESPONSE VARIABLES
// ============================================================

$employee = null;

$attendance = [

    "status" =>
        "not_checked_in",

    "has_checked_in" =>
        false,

    "has_checked_out" =>
        false,

    "attendance_id" =>
        null,

    "daily_report_id" =>
        null,

    "report_date" =>
        $today,

    "login_time" =>
        null,

    "logout_time" =>
        null,

    "daily_working_hours" =>
        0,

    "latitude" =>
        null,

    "longitude" =>
        null,

    "logout_latitude" =>
        null,

    "logout_longitude" =>
        null,

    "location_type" =>
        null,

    "location_address" =>
        null,

    "client_name" =>
        null,

    "photo_path" =>
        null,

    "logout_photo_path" =>
        null
];

$monthlyWorkingHours = [

    "year" =>
        $currentYear,

    "month" =>
        $currentMonth,

    "total_working_hours" =>
        0,

    "total_working_minutes" =>
        0,

    "total_working_days" =>
        0
];

$responsibilities = [];

$kras = [];

$kpiActuals = [];

$leaveBalance = [];

// ============================================================
// 1. GET EMPLOYEE / USER DETAILS
//
// users.id is VARCHAR
// ============================================================

$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 fetch employee information.",
        [
            "error" => $error
        ]
    );
}

// IMPORTANT: string ID
$stmt->bind_param(
    "s",
    $userId
);

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

    $error = $stmt->error;

    $stmt->close();

    $conn->close();

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

$result = $stmt->get_result();

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

    $stmt->close();

    $conn->close();

    sendResponse(
        404,
        false,
        "Employee not found.",
        [
            "debug" => [
                "received_user_id" =>
                    $userId
            ]
        ]
    );
}

$user = $result->fetch_assoc();

$stmt->close();

// ============================================================
// VALIDATE ROLE
// ============================================================

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

// Employee and Manager can access own dashboard data
if (
    $role !== 'employee' &&
    $role !== 'manager'
) {

    $conn->close();

    sendResponse(
        403,
        false,
        "This dashboard is available only for employees and managers.",
        [
            "debug" => [
                "user_id" =>
                    $userId,

                "role" =>
                    $role
            ]
        ]
    );
}

// ============================================================
// EMPLOYEE DISPLAY NAME
// ============================================================

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

if ($employeeName === '') {

    $employeeName =
        $user['username']
        ?? $userId;
}

// ============================================================
// PROFILE PHOTO
// ============================================================

$profilePhoto = '';

if (
    !empty(
        $user['profile_photo']
    )
) {

    $profilePhoto =
        trim(
            (string)$user[
                'profile_photo'
            ]
        );

} elseif (
    !empty(
        $user['photo']
    )
) {

    $profilePhoto =
        trim(
            (string)$user[
                'photo'
            ]
        );
}

// Convert whatever is stored in the database (a bare filename
// or a relative path) into a full, directly loadable URL using
// the uploads base URL declared above.
$profilePhoto = buildPhotoUrl(
    $profilePhoto,
    $base_url
);

// ============================================================
// EMPLOYEE DATA
//
// Flutter EmployeeDashboard currently reads:
// _dashboardData['user']
//
// We return this object as BOTH:
// "user"
// "employee"
// ============================================================

$employee = [

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

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

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

    "name" =>
        $employeeName,

    "employee_name" =>
        $employeeName,

    "first_name" =>
        $user['first_name'],

    "last_name" =>
        $user['last_name'],

    "designation" =>
        $user['designation']
        ?? 'Employee',

    "role" =>
        $role,

    "photo" =>
        $profilePhoto,

    "profile_photo" =>
        $profilePhoto,

    "photo_path" =>
        $profilePhoto,

    "work_location" =>
        $user['work_location'],

    "company" =>
        $user['Company']
];

// ============================================================
// 2. GET TODAY'S ATTENDANCE
//
// daily_reports.user_id is VARCHAR
// ============================================================

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

if ($stmt) {

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

    if ($stmt->execute()) {

        $result =
            $stmt->get_result();

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

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

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

            $attendanceStatus =
                "not_checked_in";

            if ($hasCheckedIn) {

                $attendanceStatus =
                    "checked_in";
            }

            if ($hasCheckedOut) {

                $attendanceStatus =
                    "checked_out";
            }

            $attendance = [

                "status" =>
                    $attendanceStatus,

                "has_checked_in" =>
                    $hasCheckedIn,

                "has_checked_out" =>
                    $hasCheckedOut,

                "attendance_id" =>
                    $row[
                        'attendance_id'
                    ] !== null
                        ? (string)$row[
                            'attendance_id'
                        ]
                        : null,

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

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

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

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

                "daily_working_hours" =>
                    (float)(
                        $row[
                            'daily_working_hours'
                        ]
                        ?? 0
                    ),

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

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

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

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

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

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

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

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

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

    $stmt->close();
}

// ============================================================
// 3. GET MONTHLY WORKING HOURS
//
// user_id changed to STRING
// ============================================================

$stmt = $conn->prepare("
    SELECT
        year,
        month,
        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(
        "sii",
        $userId,
        $currentYear,
        $currentMonth
    );

    if ($stmt->execute()) {

        $result =
            $stmt->get_result();

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

            $monthlyWorkingHours = [

                "year" =>
                    (int)$row['year'],

                "month" =>
                    (int)$row['month'],

                "total_working_hours" =>
                    (float)(
                        $row[
                            'total_working_hours'
                        ]
                        ?? 0
                    ),

                "total_working_minutes" =>
                    (int)(
                        $row[
                            'total_working_minutes'
                        ]
                        ?? 0
                    ),

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

    $stmt->close();
}

// ============================================================
// 4. GET TODAY'S DAILY RESPONSIBILITIES
//
// IMPORTANT:
// Your previous database check showed:
// daily_responsibilities.user_id = INT
//
// But users.id = VARCHAR.
//
// This is a database schema mismatch.
//
// To prevent this API from crashing, this query is only useful
// if daily_responsibilities.user_id has already been converted
// to VARCHAR.
//
// Recommended database fix:
// ALTER TABLE daily_responsibilities
// MODIFY user_id VARCHAR(11) NOT NULL;
//
// ALTER TABLE daily_responsibility_updates
// MODIFY user_id VARCHAR(11) NOT NULL;
// ============================================================

$stmt = $conn->prepare("
    SELECT

        dr.id AS responsibility_id,

        dr.user_id,

        dr.assigned_by,

        dr.responsibility_title,

        dr.responsibility_description,

        dr.priority,

        dr.start_date,

        dr.end_date,

        dr.is_daily,

        dru.id AS update_id,

        COALESCE(
            dru.morning_checked,
            0
        ) AS morning_checked,

        dru.morning_started_at,

        COALESCE(
            dru.evening_completed,
            0
        ) AS evening_completed,

        dru.hits,

        dru.missed,

        dru.carry_forward,

        dru.employee_remarks,

        dru.manager_remarks,

        COALESCE(
            dru.status,
            'not_started'
        ) AS daily_status

    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 >= ?
      )

    ORDER BY

        FIELD(
            dr.priority,
            'Urgent',
            'High',
            'Medium',
            'Low'
        ),

        dr.id ASC
");

if ($stmt) {

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

    if ($stmt->execute()) {

        $result =
            $stmt->get_result();

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

            $responsibilities[] = [

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

                "assigned_by" =>
                    $row['assigned_by'] !== null
                        ? (string)$row[
                            'assigned_by'
                        ]
                        : null,

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

                "description" =>
                    $row[
                        'responsibility_description'
                    ],

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

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

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

                "is_daily" =>
                    (bool)$row['is_daily'],

                "update_id" =>
                    $row['update_id'] !== null
                        ? (string)$row[
                            'update_id'
                        ]
                        : null,

                "morning_checked" =>
                    (bool)$row[
                        'morning_checked'
                    ],

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

                "evening_completed" =>
                    (bool)$row[
                        'evening_completed'
                    ],

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

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

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

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

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

                "status" =>
                    $row['daily_status']
            ];
        }
    }

    $stmt->close();
}

// ============================================================
// 5. GET EMPLOYEE KRA
//
// Assuming kra_master.user_id stores VARCHAR employee ID.
// ============================================================

$stmt = $conn->prepare("
    SELECT
        km.id,
        km.user_id,
        km.company_id,
        km.kra_name,
        km.kra_description,
        km.daily_responsibility_id
    FROM kra_master km
    WHERE km.user_id = ?
      AND km.is_active = 1
    ORDER BY km.id ASC
");

if ($stmt) {

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

    if ($stmt->execute()) {

        $result =
            $stmt->get_result();

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

            $kras[] = [

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

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

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

                "company_id" =>
                    $row[
                        'company_id'
                    ] !== null
                        ? (string)$row[
                            'company_id'
                        ]
                        : null,

                "daily_responsibility_id" =>
                    $row[
                        'daily_responsibility_id'
                    ] !== null
                        ? (string)$row[
                            'daily_responsibility_id'
                        ]
                        : null
            ];
        }
    }

    $stmt->close();
}

// ============================================================
// 6. GET CURRENT WEEK KPI ACTUALS
//
// Assuming kpi_actuals.user_id stores VARCHAR employee ID.
// ============================================================

$stmt = $conn->prepare("
    SELECT

        id,

        kpi_id,

        month_key,

        week_start,

        week_end,

        actual_value,

        status,

        employee_comment,

        attachment,

        attachment_original_name,

        manager_comment,

        hr_comment,

        submitted_at,

        approved_at,

        verified_at,

        manager_approved

    FROM kpi_actuals

    WHERE user_id = ?

      AND week_start <= ?

      AND week_end >= ?

    ORDER BY kpi_id ASC
");

if ($stmt) {

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

    if ($stmt->execute()) {

        $result =
            $stmt->get_result();

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

            $kpiActuals[] = [

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

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

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

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

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

                "actual_value" =>
                    (float)(
                        $row[
                            'actual_value'
                        ]
                        ?? 0
                    ),

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

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

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

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

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

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

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

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

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

                "manager_approved" =>
                    (bool)$row[
                        'manager_approved'
                    ]
            ];
        }
    }

    $stmt->close();
}

// ============================================================
// 7. GET LEAVE BALANCE
//
// Assuming leave_balance.user_id stores VARCHAR employee ID.
// ============================================================

$stmt = $conn->prepare("
    SELECT
        leave_type,
        year,
        balance,
        entitled_days,
        last_updated
    FROM leave_balance
    WHERE user_id = ?
      AND year = ?
    ORDER BY leave_type ASC
");

if ($stmt) {

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

    if ($stmt->execute()) {

        $result =
            $stmt->get_result();

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

            $leaveBalance[] = [

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

                "year" =>
                    (int)$row['year'],

                "balance" =>
                    (float)(
                        $row['balance']
                        ?? 0
                    ),

                "entitled_days" =>
                    (float)(
                        $row[
                            'entitled_days'
                        ]
                        ?? 0
                    ),

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

    $stmt->close();
}

// ============================================================
// 8. RESPONSIBILITY SUMMARY
// ============================================================

$totalResponsibilities =
    count(
        $responsibilities
    );

$morningStartedCount = 0;

$eveningCompletedCount = 0;

foreach (
    $responsibilities as $item
) {

    if (
        $item[
            'morning_checked'
        ] === true
    ) {

        $morningStartedCount++;
    }

    if (
        $item[
            'evening_completed'
        ] === true
    ) {

        $eveningCompletedCount++;
    }
}

// ============================================================
// WORKFLOW STATUS
// ============================================================

$workflowStatus =
    'not_started';

if (
    $totalResponsibilities > 0 &&
    $morningStartedCount > 0
) {

    $workflowStatus =
        'morning_started';
}

if (
    $totalResponsibilities > 0 &&
    $eveningCompletedCount ===
        $totalResponsibilities
) {

    $workflowStatus =
        'evening_completed';
}

// ============================================================
// 9. CHECKOUT ELIGIBILITY
// ============================================================

$canCheckout = false;

$checkoutBlockReason = null;

if (
    !$attendance[
        'has_checked_in'
    ]
) {

    $checkoutBlockReason =
        'Please check in first.';

} elseif (
    $attendance[
        'has_checked_out'
    ]
) {

    $checkoutBlockReason =
        'You have already checked out today.';

} elseif (
    $totalResponsibilities > 0 &&
    $eveningCompletedCount <
        $totalResponsibilities
) {

    $checkoutBlockReason =
        'Please complete your end-of-day responsibility updates before checkout.';

} else {

    $canCheckout = true;
}

// ============================================================
// FINAL RESPONSE
//
// IMPORTANT:
//
// Flutter EmployeeDashboard uses:
// _dashboardData['user']
// _dashboardData['attendance']
// _dashboardData['monthly_working_hours']
//
// So "user" is included.
//
// "employee" is also included for compatibility.
// ============================================================

$responseData = [

    "server_time" =>
        date(
            'Y-m-d H:i:s'
        ),

    "date" =>
        $today,

    // Flutter dashboard uses this
    "user" =>
        $employee,

    // Other APIs/screens can use this
    "employee" =>
        $employee,

    "attendance" =>
        $attendance,

    "monthly_working_hours" =>
        $monthlyWorkingHours,

    "daily_responsibility_summary" => [

        "total" =>
            $totalResponsibilities,

        "morning_started" =>
            $morningStartedCount,

        "evening_completed" =>
            $eveningCompletedCount,

        "workflow_status" =>
            $workflowStatus
    ],

    "daily_responsibilities" =>
        $responsibilities,

    "kra" =>
        $kras,

    "current_week" => [

        "month_key" =>
            $monthKey,

        "week_start" =>
            $weekStart,

        "week_end" =>
            $weekEnd
    ],

    "kpi_actuals" =>
        $kpiActuals,

    "leave_balance" =>
        $leaveBalance,

    "checkout" => [

        "can_checkout" =>
            $canCheckout,

        "block_reason" =>
            $checkoutBlockReason
    ],

    "unread_notifications" =>
        0
];

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

$conn->close();

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

sendResponse(
    200,
    true,
    "Employee dashboard loaded successfully.",
    $responseData
);

?>