<?php
ob_start();
include("../../../include/startup.php");
ob_clean();
header('Content-Type: application/json');
error_reporting(0);

if (!isset($conn) || !$conn) {
    echo json_encode(['success' => false, 'error' => 'DB connection failed']);
    exit;
}

// Only allow POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Invalid request method']);
    exit;
}

try {
    // ── Input validation ──────────────────────────────────────────────
    $shift_id   = isset($_POST['shift_id'])   ? (int)$_POST['shift_id']          : 0;
    $start_time = isset($_POST['start_time']) ? trim($_POST['start_time'])        : '';
    $end_time   = isset($_POST['end_time'])   ? trim($_POST['end_time'])          : '';
    $status     = isset($_POST['status'])     ? trim($_POST['status'])            : 'completed';

    if ($shift_id <= 0) {
        echo json_encode(['success' => false, 'error' => 'Invajjjlid shift ID']);
        exit;
    }

    if (empty($start_time)) {
        echo json_encode(['success' => false, 'error' => 'Clock In time is required']);
        exit;
    }

    // Validate status
    $allowed_statuses = ['active', 'completed'];
    if (!in_array($status, $allowed_statuses)) {
        $status = 'completed';
    }

    // Convert datetime-local format (YYYY-MM-DDTHH:MM) → MySQL (YYYY-MM-DD HH:MM:SS)
    $start_time_mysql = str_replace('T', ' ', $start_time) . ':00';
    $end_time_mysql   = !empty($end_time) ? str_replace('T', ' ', $end_time) . ':00' : null;

    // Validate that end_time is after start_time (if provided)
    if ($end_time_mysql && strtotime($end_time_mysql) <= strtotime($start_time_mysql)) {
        echo json_encode(['success' => false, 'error' => 'Clock Out time must be after Clock In time']);
        exit;
    }

    // ── Recalculate total_hours ───────────────────────────────────────
    $total_hours = null;
    if ($end_time_mysql) {
        $diff        = strtotime($end_time_mysql) - strtotime($start_time_mysql);
        $total_hours = round($diff / 3600, 2);  // hours with 2 decimal places
    }

    // ── Check shift exists ────────────────────────────────────────────
    $check = $conn->query("SELECT id FROM shifts WHERE id = $shift_id");
    if (!$check || $check->num_rows === 0) {
        echo json_encode(['success' => false, 'error' => 'Shift record not found']);
        exit;
    }

    // ── Build UPDATE query ────────────────────────────────────────────
    $start_time_escaped = $conn->real_escape_string($start_time_mysql);
    $status_escaped     = $conn->real_escape_string($status);

    if ($end_time_mysql) {
        $end_time_escaped = $conn->real_escape_string($end_time_mysql);
        $sql = "
            UPDATE shifts SET
                start_time  = '$start_time_escaped',
                end_time    = '$end_time_escaped',
                total_hours = $total_hours,
                status      = '$status_escaped'
            WHERE id = $shift_id
        ";
    } else {
        // No end time — clear it and set status to active
        $sql = "
            UPDATE shifts SET
                start_time  = '$start_time_escaped',
                end_time    = NULL,
                total_hours = NULL,
                status      = 'active'
            WHERE id = $shift_id
        ";
    }

    if (!$conn->query($sql)) {
        throw new Exception('Update failed: ' . $conn->error);
    }

    if ($conn->affected_rows === 0) {
        // No rows changed — might mean same data was submitted, still success
        echo json_encode(['success' => true, 'message' => 'No changes detected']);
        exit;
    }

    ob_clean();
    echo json_encode([
        'success' => true,
        'message' => 'Shift record updated successfully',
        'data'    => [
            'shift_id'    => $shift_id,
            'start_time'  => $start_time_mysql,
            'end_time'    => $end_time_mysql,
            'total_hours' => $total_hours,
            'status'      => $end_time_mysql ? $status : 'active'
        ]
    ]);

} catch (Exception $e) {
    ob_clean();
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}

ob_end_flush();
?>