<?php

// ============================================================
// DAILY RESPONSIBILITIES API
// File: api/daily_responsibilities.php
//
// Method: POST
//
// JSON:
// {
//     "user_id": "EMP001",
//     "report_date": "2026-07-23"   // optional
// }
//
// Returns:
// - Today's active responsibilities
// - Morning status
// - Evening status
// - Hits / Missed / Carry Forward
// - Employee / Manager remarks
// - Linked KRA
//
// Allowed Roles:
// employee
// manager
//
// NOTE:
// This system was migrated from INTEGER user IDs to STRING
// user IDs (VARCHAR(30) PRIMARY KEY), e.g. EMP001, BS01, HR01.
// user_id is NEVER cast to int, NEVER compared numerically,
// and is ALWAYS bound as a string ("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');

// ============================================================
// OPTIONS
// ============================================================

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

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

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

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

$data = json_decode(
    $rawData,
    true
);

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

// ============================================================
// INPUT
//
// user_id is a STRING identifier (e.g. EMP001, HR01, MD01).
// It is never cast to (int) and never treated numerically.
// ============================================================

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

$reportDate = trim(
    $data['report_date'] ?? ''
);

// ============================================================
// USER VALIDATION
//
// Must be a non-empty string. Length and charset are checked
// to match the VARCHAR(30) column, without assuming any
// numeric format.
// ============================================================

if ($userId === '') {

    $conn->close();

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

if (strlen($userId) > 30) {

    $conn->close();

    sendResponse(
        400,
        false,
        "user_id must not exceed 30 characters."
    );
}

if (!preg_match('/^[A-Za-z0-9_\-]+$/', $userId)) {

    $conn->close();

    sendResponse(
        400,
        false,
        "user_id contains invalid characters."
    );
}

// ============================================================
// REPORT DATE
// ============================================================

if ($reportDate === '') {

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

} else {

    // Validate YYYY-MM-DD

    $dateObject =
        DateTime::createFromFormat(
            'Y-m-d',
            $reportDate
        );

    if (
        !$dateObject ||
        $dateObject->format('Y-m-d')
            !== $reportDate
    ) {

        $conn->close();

        sendResponse(
            400,
            false,
            "Invalid report_date. Use YYYY-MM-DD format."
        );
    }
}

// ============================================================
// CHECK USER
//
// users.id is VARCHAR(30) PRIMARY KEY, bound as string.
// ============================================================

$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(
    "s",
    $userId
);

$stmt->execute();

$result =
    $stmt->get_result();

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

    $stmt->close();

    $conn->close();

    sendResponse(
        404,
        false,
        "User not found."
    );
}

$user =
    $result->fetch_assoc();

$stmt->close();

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

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

$allowedRoles = [
    'employee',
    'manager'
];

if (
    !in_array(
        $role,
        $allowedRoles,
        true
    )
) {

    $conn->close();

    sendResponse(
        403,
        false,
        "Daily responsibilities are available only for employees and managers."
    );
}

// ============================================================
// GET RESPONSIBILITIES
// ============================================================
//
// daily_responsibilities
//     ↓
// daily_responsibility_updates
//     ↓
// kra_master
//
// kra_master.daily_responsibility_id
// connects KRA with Responsibility.
//
// The update join is specific to report_date.
//
// dr.user_id / dru.user_id / km.user_id are all VARCHAR(30)
// and are bound as strings ("s") below.
// ============================================================

$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,

        dr.is_active,

        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 update_status,

        km.id AS kra_id,

        km.kra_name,

        km.kra_description

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

    LEFT JOIN kra_master km

        ON km.daily_responsibility_id =
            dr.id

        AND km.user_id =
            dr.user_id

        AND km.is_active = 1

    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) {

    $conn->close();

    sendResponse(
        500,
        false,
        "Unable to load daily responsibilities."
    );
}

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

$stmt->execute();

$result =
    $stmt->get_result();

// ============================================================
// BUILD RESPONSIBILITY LIST
// ============================================================

$responsibilities = [];

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

    $responsibilityId =
        (int)$row['responsibility_id'];

    // ========================================================
    // PREVENT DUPLICATE RESPONSIBILITY
    //
    // If multiple KRA rows are linked to the same
    // responsibility, collect them under same responsibility.
    // ========================================================

    if (
        !isset(
            $responsibilities[
                $responsibilityId
            ]
        )
    ) {

        $responsibilities[
            $responsibilityId
        ] = [

            "responsibility_id" =>
                (string)$responsibilityId,

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

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

            "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'],

            // ================================================
            // TODAY UPDATE
            // ================================================

            "daily_update" => [

                "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[
                        'update_status'
                    ]
            ],

            // ================================================
            // LINKED KRA
            // ================================================

            "kra" => []
        ];
    }

    // ========================================================
    // ADD KRA
    // ========================================================

    if (
        $row['kra_id']
        !== null
    ) {

        $kraId =
            (string)$row['kra_id'];

        $alreadyAdded =
            false;

        foreach (
            $responsibilities[
                $responsibilityId
            ]['kra']
            as $existingKra
        ) {

            if (
                $existingKra[
                    'kra_id'
                ] === $kraId
            ) {

                $alreadyAdded =
                    true;

                break;
            }
        }

        if (!$alreadyAdded) {

            $responsibilities[
                $responsibilityId
            ]['kra'][] = [

                "kra_id" =>
                    $kraId,

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

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

$stmt->close();

// Convert associative array to normal JSON array

$responsibilities =
    array_values(
        $responsibilities
    );

// ============================================================
// SUMMARY CALCULATION
// ============================================================

$total =
    count(
        $responsibilities
    );

$morningStarted =
    0;

$eveningCompleted =
    0;

$notStarted =
    0;

foreach (
    $responsibilities
    as $responsibility
) {

    $dailyUpdate =
        $responsibility[
            'daily_update'
        ];

    if (
        $dailyUpdate[
            'morning_checked'
        ]
    ) {

        $morningStarted++;

    } else {

        $notStarted++;
    }

    if (
        $dailyUpdate[
            'evening_completed'
        ]
    ) {

        $eveningCompleted++;
    }
}

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

$workflowStatus =
    'not_started';

if (
    $total > 0 &&
    $morningStarted > 0
) {

    $workflowStatus =
        'morning_started';
}

if (
    $total > 0 &&
    $morningStarted === $total
) {

    $workflowStatus =
        'all_morning_started';
}

if (
    $total > 0 &&
    $eveningCompleted > 0
) {

    $workflowStatus =
        'evening_in_progress';
}

if (
    $total > 0 &&
    $eveningCompleted === $total
) {

    $workflowStatus =
        'evening_completed';
}

// ============================================================
// CHECK TODAY ATTENDANCE
//
// user_id bound as string ("s").
// ============================================================

$attendance = [

    "has_checked_in" =>
        false,

    "has_checked_out" =>
        false,

    "login_time" =>
        null,

    "logout_time" =>
        null
];

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

if ($stmt) {

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

    $stmt->execute();

    $attendanceResult =
        $stmt->get_result();

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

        $attendance = [

            "has_checked_in" =>
                !empty(
                    $attendanceRow[
                        'login_time'
                    ]
                ),

            "has_checked_out" =>
                !empty(
                    $attendanceRow[
                        'logout_time'
                    ]
                ),

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

            "logout_time" =>
                $attendanceRow[
                    'logout_time'
                ]
        ];
    }

    $stmt->close();
}

// ============================================================
// MORNING ACTION AVAILABILITY
// ============================================================
//
// Morning responsibility can be started only
// after attendance check-in.
// ============================================================

$canStartMorning =
    $attendance[
        'has_checked_in'
    ] &&
    !$attendance[
        'has_checked_out'
    ];

// ============================================================
// EVENING ACTION AVAILABILITY
// ============================================================
//
// Employee must:
// - Check in
// - Not checkout
// - Start morning responsibility
// ============================================================

$canSubmitEvening =
    $attendance[
        'has_checked_in'
    ] &&
    !$attendance[
        'has_checked_out'
    ] &&
    $morningStarted > 0;

// ============================================================
// CAN CHECKOUT
// ============================================================

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

} elseif (
    $total > 0 &&
    $eveningCompleted < $total
) {

    $checkoutBlockReason =
        "Please complete all end-of-day responsibility updates.";

} else {

    $canCheckout =
        true;
}

// ============================================================
// FINAL RESPONSE
// ============================================================

$conn->close();

sendResponse(
    200,
    true,
    "Daily responsibilities loaded successfully.",
    [

        "report_date" =>
            $reportDate,

        "user" => [

            "user_id" =>
                $user['id'],

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

            "role" =>
                $role
        ],

        "attendance" =>
            $attendance,

        "summary" => [

            "total_responsibilities" =>
                $total,

            "not_started" =>
                $notStarted,

            "morning_started" =>
                $morningStarted,

            "evening_completed" =>
                $eveningCompleted,

            "workflow_status" =>
                $workflowStatus
        ],

        "actions" => [

            "can_start_morning" =>
                $canStartMorning,

            "can_submit_evening" =>
                $canSubmitEvening,

            "can_checkout" =>
                $canCheckout,

            "checkout_block_reason" =>
                $checkoutBlockReason
        ],

        "responsibilities" =>
            $responsibilities
    ]
);

?>