<?php

// ============================================================
// EVENING RESPONSIBILITY API
// File: api/evening_responsibility.php
//
// Method: POST
//
// Single:
// {
//   "user_id": 227,
//   "responsibility_id": 10,
//   "hits": "5 client follow-ups completed",
//   "missed": "1 client not reachable",
//   "carry_forward": "Follow up tomorrow",
//   "employee_remarks": "Quotation sent"
// }
//
// Multiple:
// {
//   "user_id": 227,
//   "updates": [
//     {
//       "responsibility_id": 10,
//       "hits": "Completed",
//       "missed": "",
//       "carry_forward": "",
//       "employee_remarks": "Done"
//     },
//     {
//       "responsibility_id": 11,
//       "hits": "Report prepared",
//       "missed": "",
//       "carry_forward": "Final review tomorrow",
//       "employee_remarks": ""
//     }
//   ]
// }
//
// Rules:
// - Employee / Manager only
// - Must check in first
// - Cannot submit after checkout
// - Responsibility must belong to user
// - Morning responsibility must already be started
// ============================================================

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

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

$data = json_decode(
    $rawData,
    true
);

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

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

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

$updates = [];

// ============================================================
// SUPPORT SINGLE RESPONSIBILITY
// ============================================================

if (
    isset($data['responsibility_id']) &&
    (int)$data['responsibility_id'] > 0
) {

    $updates[] = [

        "responsibility_id" =>
            (int)$data['responsibility_id'],

        "hits" =>
            trim(
                $data['hits'] ?? ''
            ),

        "missed" =>
            trim(
                $data['missed'] ?? ''
            ),

        "carry_forward" =>
            trim(
                $data['carry_forward'] ?? ''
            ),

        "employee_remarks" =>
            trim(
                $data['employee_remarks'] ?? ''
            )
    ];
}

// ============================================================
// SUPPORT MULTIPLE RESPONSIBILITIES
// ============================================================

if (
    isset($data['updates']) &&
    is_array($data['updates'])
) {

    $updates = [];

    foreach (
        $data['updates']
        as $item
    ) {

        if (
            !is_array($item)
        ) {
            continue;
        }

        $responsibilityId =
            (int)(
                $item[
                    'responsibility_id'
                ] ?? 0
            );

        if (
            $responsibilityId <= 0
        ) {
            continue;
        }

        $updates[] = [

            "responsibility_id" =>
                $responsibilityId,

            "hits" =>
                trim(
                    $item['hits']
                    ?? ''
                ),

            "missed" =>
                trim(
                    $item['missed']
                    ?? ''
                ),

            "carry_forward" =>
                trim(
                    $item[
                        'carry_forward'
                    ] ?? ''
                ),

            "employee_remarks" =>
                trim(
                    $item[
                        'employee_remarks'
                    ] ?? ''
                )
        ];
    }
}

// ============================================================
// VALIDATION
// ============================================================

if (
    $userId <= 0
) {

    $conn->close();

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

if (
    count($updates) === 0
) {

    $conn->close();

    sendResponse(
        400,
        false,
        "At least one responsibility update is required."
    );
}

// ============================================================
// CURRENT DATE
// ============================================================

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

$currentDateTime =
    date('Y-m-d H:i:s');

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

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

$user =
    $result->fetch_assoc();

$stmt->close();

// ============================================================
// ROLE VALIDATION
// ============================================================

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

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

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

    $conn->close();

    sendResponse(
        403,
        false,
        "Only employees and managers can submit daily responsibility updates."
    );
}

// ============================================================
// CHECK TODAY ATTENDANCE
// ============================================================

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

if (!$stmt) {

    $conn->close();

    sendResponse(
        500,
        false,
        "Unable to verify attendance."
    );
}

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

$stmt->execute();

$result =
    $stmt->get_result();

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

    $stmt->close();

    $conn->close();

    sendResponse(
        403,
        false,
        "Please check in before submitting your end-of-day update."
    );
}

$attendance =
    $result->fetch_assoc();

$stmt->close();

// ============================================================
// MUST BE CHECKED IN
// ============================================================

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

    $conn->close();

    sendResponse(
        403,
        false,
        "Please check in before submitting your end-of-day update."
    );
}

// ============================================================
// CANNOT UPDATE AFTER CHECKOUT
// ============================================================

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

    $conn->close();

    sendResponse(
        403,
        false,
        "You have already checked out today."
    );
}

// ============================================================
// START TRANSACTION
// ============================================================

$conn->begin_transaction();

try {

    $submittedUpdates = [];

    // ========================================================
    // PROCESS EACH RESPONSIBILITY
    // ========================================================

    foreach (
        $updates
        as $item
    ) {

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

        $hits =
            $item['hits'];

        $missed =
            $item['missed'];

        $carryForward =
            $item[
                'carry_forward'
            ];

        $employeeRemarks =
            $item[
                'employee_remarks'
            ];

        // ====================================================
        // VERIFY RESPONSIBILITY BELONGS TO USER
        // ====================================================

        $stmt = $conn->prepare("
            SELECT
                id,
                responsibility_title,
                priority
            FROM daily_responsibilities
            WHERE id = ?
              AND user_id = ?
              AND is_active = 1
              AND (
                    start_date IS NULL
                    OR start_date <= ?
              )
              AND (
                    end_date IS NULL
                    OR end_date >= ?
              )
            LIMIT 1
        ");

        if (!$stmt) {

            throw new Exception(
                "Unable to validate responsibility."
            );
        }

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

        $stmt->execute();

        $result =
            $stmt->get_result();

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

            $stmt->close();

            throw new Exception(
                "Responsibility ID {$responsibilityId} is not assigned to this user or is not active today."
            );
        }

        $responsibility =
            $result->fetch_assoc();

        $stmt->close();

        // ====================================================
        // GET MORNING UPDATE
        // ====================================================

        $stmt = $conn->prepare("
            SELECT
                id,
                morning_checked,
                morning_started_at,
                evening_completed,
                status
            FROM daily_responsibility_updates
            WHERE user_id = ?
              AND responsibility_id = ?
              AND report_date = ?
            LIMIT 1
        ");

        if (!$stmt) {

            throw new Exception(
                "Unable to check daily responsibility update."
            );
        }

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

        $stmt->execute();

        $result =
            $stmt->get_result();

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

            $stmt->close();

            throw new Exception(
                "Please start responsibility ID {$responsibilityId} in the morning before submitting the evening update."
            );
        }

        $dailyUpdate =
            $result->fetch_assoc();

        $stmt->close();

        // ====================================================
        // MORNING MUST BE CHECKED
        // ====================================================

        if (
            (int)$dailyUpdate[
                'morning_checked'
            ] !== 1
        ) {

            throw new Exception(
                "Responsibility ID {$responsibilityId} was not started in the morning."
            );
        }

        $updateId =
            (int)$dailyUpdate['id'];

        // ====================================================
        // UPDATE EVENING DATA
        // ====================================================

        $stmt = $conn->prepare("
            UPDATE daily_responsibility_updates
            SET
                evening_completed = 1,
                hits = ?,
                missed = ?,
                carry_forward = ?,
                employee_remarks = ?,
                status = 'evening_submitted'
            WHERE id = ?
              AND user_id = ?
              AND responsibility_id = ?
              AND report_date = ?
        ");

        if (!$stmt) {

            throw new Exception(
                "Unable to prepare evening responsibility update."
            );
        }

        $stmt->bind_param(
            "ssssiiis",
            $hits,
            $missed,
            $carryForward,
            $employeeRemarks,
            $updateId,
            $userId,
            $responsibilityId,
            $today
        );

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

            $stmt->close();

            throw new Exception(
                "Unable to save evening responsibility update."
            );
        }

        $stmt->close();

        // ====================================================
        // ADD RESPONSE DATA
        // ====================================================

        $submittedUpdates[] = [

            "update_id" =>
                (string)$updateId,

            "responsibility_id" =>
                (string)$responsibilityId,

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

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

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

            "evening_completed" =>
                true,

            "hits" =>
                $hits,

            "missed" =>
                $missed,

            "carry_forward" =>
                $carryForward,

            "employee_remarks" =>
                $employeeRemarks,

            "status" =>
                "evening_submitted"
        ];
    }

    // ========================================================
    // COMMIT EVENING UPDATES
    // ========================================================

    $conn->commit();

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

    $totalResponsibilities =
        0;

    $morningStarted =
        0;

    $eveningCompleted =
        0;

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

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

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

        $stmt->execute();

        $result =
            $stmt->get_result();

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

            $totalResponsibilities =
                (int)$summary[
                    'total_count'
                ];

            $morningStarted =
                (int)$summary[
                    'morning_count'
                ];

            $eveningCompleted =
                (int)$summary[
                    'evening_count'
                ];
        }

        $stmt->close();
    }

    // ========================================================
    // CHECK IF ALL RESPONSIBILITIES COMPLETED
    // ========================================================

    $allCompleted = false;

    if (
        $totalResponsibilities === 0
    ) {

        $allCompleted = true;

    } elseif (
        $eveningCompleted ===
        $totalResponsibilities
    ) {

        $allCompleted = true;
    }

    // ========================================================
    // CHECKOUT ELIGIBILITY
    // ========================================================

    $canCheckout =
        $allCompleted;

    $checkoutBlockReason =
        null;

    if (!$canCheckout) {

        $remaining =
            $totalResponsibilities -
            $eveningCompleted;

        $checkoutBlockReason =
            "Please complete {$remaining} remaining responsibility update(s) before checkout.";
    }

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

    $linkedKras = [];

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

    if ($stmt) {

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

        $stmt->execute();

        $result =
            $stmt->get_result();

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

            $linkedKras[] = [

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

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

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

                "responsibility_id" =>
                    (string)$kra[
                        'daily_responsibility_id'
                    ]
            ];
        }

        $stmt->close();
    }

    $conn->close();

    // ========================================================
    // SUCCESS RESPONSE
    // ========================================================

    sendResponse(
        200,
        true,
        "End-of-day responsibility update submitted successfully.",
        [

            "report_date" =>
                $today,

            "submitted_at" =>
                $currentDateTime,

            "user" => [

                "user_id" =>
                    (string)$userId,

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

                "role" =>
                    $role
            ],

            "summary" => [

                "total_responsibilities" =>
                    $totalResponsibilities,

                "morning_started" =>
                    $morningStarted,

                "evening_completed" =>
                    $eveningCompleted,

                "all_completed" =>
                    $allCompleted
            ],

            "checkout" => [

                "can_checkout" =>
                    $canCheckout,

                "block_reason" =>
                    $checkoutBlockReason
            ],

            "submitted_updates" =>
                $submittedUpdates,

            "linked_kras" =>
                $linkedKras
        ]
    );

} catch (Throwable $e) {

    // ========================================================
    // ROLLBACK
    // ========================================================

    $conn->rollback();

    $conn->close();

    sendResponse(
        500,
        false,
        $e->getMessage()
    );
}

?>