<?php
session_start();
ob_start(); 
require('../include/startup.php');

$curent_date = (new DateTime())->format('Y-m-d H:i:s');  
$message = "";
$shift_status = "none";

if (isset($_POST['toggle_shift'])) {
    $clock_no = trim($_POST['clock_no']);
    $sql = "SELECT * FROM admin WHERE clock_no = '$clock_no'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        $user_id = $user['id'];

        $sql = "SELECT * FROM shifts WHERE user_id = $user_id AND status = 'active'";
        $result = $conn->query($sql);

        if ($result->num_rows == 0) {
            $sql = "INSERT INTO shifts (user_id, start_time, status) VALUES ($user_id, '$curent_date', 'active')";
            if ($conn->query($sql) === TRUE) {
                $message = "Successfully clocked in!";
                $message_type = "success";
                $shift_status = "active";
            }
        } else {
            $shift = $result->fetch_assoc();
            $shift_id = $shift['id'];

            $sql = "UPDATE shifts SET end_time = '$curent_date', status = 'inactive' WHERE id = $shift_id";
            if ($conn->query($sql) === TRUE) {
                $start_time  = strtotime($shift['start_time']);
                $end_time    = strtotime($curent_date);
                $total_hours = ($end_time - $start_time) / 3600;

                $day_of_week = date('N', $start_time);
                $pay_amount  = calculatePay($total_hours, $day_of_week);

                $sql = "UPDATE shifts SET total_hours = $total_hours, pay_amount = $pay_amount WHERE id = $shift_id";
                $conn->query($sql);

                $message = "Shift ended successfully. Worked: " . round($total_hours, 2) . "h | Pay: ₹" . number_format($pay_amount, 2);
                $message_type = "success";
                $shift_status = "ended";
            }
        }
    } else {
        $message = "Incorrect Clock Code. Please try again.";
        $message_type = "error";
    }
}

function calculatePay($worked_hours, $day_of_week) {
    $standard_rate = 100;
    if ($day_of_week >= 1 && $day_of_week <= 4) {
        if ($worked_hours <= 9.75) {
            return round($worked_hours * $standard_rate, 2);
        } else {
            return round((9.75 * $standard_rate) + (($worked_hours - 9.75) * $standard_rate * 1.33), 2);
        }
    } elseif ($day_of_week == 5 || $day_of_week == 6) {
        return round($worked_hours * $standard_rate * 1.5, 2);
    } elseif ($day_of_week == 7) {
        return round($worked_hours * $standard_rate * 2, 2);
    }
    return 0;
}
?>

<style>
    * { margin: 0; padding: 0; box-sizing: border-box; }

    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background: #f0edf5;
        min-height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 24px;
    }

    .clock-card {
        background: #ffffff;
        border-radius: 24px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.04), 0 12px 48px rgba(99,45,110,0.13);
        padding: 60px 56px 52px;
        width: 100%;
        max-width: 520px;
        position: relative;
        overflow: hidden;
    }

    .clock-card::before {
        content: '';
        position: absolute;
        top: 0; left: 0; right: 0;
        height: 5px;
        background: linear-gradient(90deg, #9c4893 0%, #c97bc2 60%, #7d3876 100%);
    }

    .card-header {
        text-align: center;
        margin-bottom: 44px;
    }

    .card-icon {
        width: 72px;
        height: 72px;
        background: linear-gradient(135deg, #f5edf4, #e8d5e6);
        border-radius: 18px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 20px;
        font-size: 34px;
    }

    .card-header h2 {
        font-size: 28px;
        font-weight: 700;
        color: #1a1025;
        letter-spacing: -0.4px;
        margin-bottom: 6px;
    }

    .card-header p {
        font-size: 15px;
        color: #9b8faa;
    }

    .input-group {
        margin-bottom: 28px;
    }

    .input-group label {
        display: block;
        font-size: 13px;
        font-weight: 600;
        color: #6b5c7a;
        text-transform: uppercase;
        letter-spacing: 0.9px;
        margin-bottom: 10px;
    }

    .input-group input[type="text"] {
        width: 100%;
        padding: 20px 24px;
        font-size: 22px;
        font-family: 'Courier New', Courier, monospace;
        font-weight: 500;
        letter-spacing: 4px;
        border: 1.5px solid #e2d9ea;
        border-radius: 12px;
        color: #1a1025;
        background: #faf8fc;
        transition: border-color 0.2s, box-shadow 0.2s;
        outline: none;
        text-align: center;
    }

    .input-group input[type="text"]:focus {
        border-color: #9c4893;
        background: #fff;
        box-shadow: 0 0 0 4px rgba(156, 72, 147, 0.12);
    }

    .input-group input[type="text"]::placeholder {
        color: #c0b4cb;
        letter-spacing: 1px;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        font-weight: 400;
        font-size: 16px;
    }

    .btn-toggle {
        width: 100%;
        padding: 22px;
        font-size: 17px;
        font-weight: 700;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        border: none;
        border-radius: 14px;
        cursor: pointer;
        transition: all 0.18s ease;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12px;
        background: linear-gradient(135deg, #9c4893, #7d3876);
        color: #fff;
        letter-spacing: 0.3px;
        box-shadow: 0 4px 18px rgba(156,72,147,0.30);
    }

    .btn-toggle:hover {
        background: linear-gradient(135deg, #b356a8, #9c4893);
        transform: translateY(-2px);
        box-shadow: 0 8px 28px rgba(156,72,147,0.38);
    }

    .btn-toggle:active {
        transform: translateY(0);
        box-shadow: 0 4px 18px rgba(156,72,147,0.30);
    }

    .btn-toggle .btn-icon { font-size: 22px; }

    .divider {
        height: 1px;
        background: #f0eaf5;
        margin: 28px 0 20px;
    }

    .status-bar {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        font-size: 14px;
        color: #9b8faa;
        font-weight: 600;
    }

    .status-dot {
        width: 9px;
        height: 9px;
        border-radius: 50%;
        background: #d4c8df;
    }

    .status-dot.active { background: #22c55e; box-shadow: 0 0 0 3px rgba(34,197,94,0.2); }
    .status-dot.ended  { background: #ef4444; box-shadow: 0 0 0 3px rgba(239,68,68,0.2); }

    /* ── Toast ── */
    .toast-overlay {
        position: fixed;
        top: 0; left: 0; right: 0; bottom: 0;
        z-index: 9999;
        display: flex;
        align-items: flex-start;
        justify-content: center;
        padding-top: 32px;
        pointer-events: none;
    }

    .toast {
        background: #fff;
        border-radius: 16px;
        box-shadow: 0 8px 40px rgba(0,0,0,0.15), 0 2px 8px rgba(0,0,0,0.08);
        padding: 20px 40px 20px 20px;
        display: flex;
        align-items: flex-start;
        gap: 14px;
        min-width: 320px;
        max-width: 480px;
        pointer-events: all;
        animation: slideDown 0.35s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
        position: relative;
        overflow: hidden;
    }

    .toast.hide {
        animation: slideUp 0.3s ease-in forwards;
    }

    .toast-icon {
        width: 44px;
        height: 44px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 22px;
        flex-shrink: 0;
    }

    .toast-body {
        flex: 1;
        padding-top: 2px;
    }

    .toast-title {
        font-size: 15px;
        font-weight: 700;
        color: #1a1025;
        margin-bottom: 4px;
    }

    .toast-msg {
        font-size: 14px;
        color: #6b5c7a;
        line-height: 1.5;
    }

    .toast-close {
        position: absolute;
        top: 10px;
        right: 10px;
        background: none;
        border: none;
        cursor: pointer;
        color: #c0b4cb;
        font-size: 16px;
        line-height: 1;
        padding: 4px 6px;
        border-radius: 6px;
        transition: color 0.15s, background 0.15s;
    }

    .toast-close:hover {
        color: #1a1025;
        background: #f0edf5;
    }

    .toast-progress {
        position: absolute;
        bottom: 0; left: 0;
        height: 3px;
        border-radius: 0 0 16px 16px;
        animation: shrink 3.5s linear forwards;
    }

    /* Toast variants */
    .toast.success .toast-icon { background: #edfaf3; }
    .toast.success .toast-progress { background: #22c55e; }

    .toast.error .toast-icon { background: #fef2f2; }
    .toast.error .toast-progress { background: #ef4444; }

    .toast.warning .toast-icon { background: #fff8ec; }
    .toast.warning .toast-progress { background: #f59e0b; }

    /* Animations */
    @keyframes slideDown {
        from { opacity: 0; transform: translateY(-24px) scale(0.96); }
        to   { opacity: 1; transform: translateY(0)     scale(1);    }
    }

    @keyframes slideUp {
        from { opacity: 1; transform: translateY(0)     scale(1);    }
        to   { opacity: 0; transform: translateY(-16px) scale(0.96); }
    }

    @keyframes shrink {
        from { width: 100%; }
        to   { width: 0%;   }
    }

    @media (max-width: 560px) {
        .clock-card { padding: 40px 24px 36px; }
        .input-group input[type="text"] { font-size: 18px; padding: 18px; }
        .toast { min-width: unset; width: calc(100vw - 32px); }
    }
</style>

<section class="content">
    <div class="clock-card">
        <div class="card-header">
            <div class="card-icon">🕐</div>
            <h2>Clock In / Clock Out</h2>
            <p>Enter your clock code and tap the button</p>
        </div>

        <form method="POST" action="">
            <div class="input-group">
                <label for="clock_no">Clock Code</label>
                <input type="text" id="clock_no" name="clock_no"
                       placeholder="Enter your code" required autocomplete="off">
            </div>

            <button type="submit" name="toggle_shift" class="btn-toggle">
                <span class="btn-icon">⏱</span>
                Clock In / Clock Out
            </button>
        </form>

        <?php if ($shift_status !== "none"): ?>
            <div class="divider"></div>
            <div class="status-bar">
                <span class="status-dot <?php echo $shift_status; ?>"></span>
                <?php echo $shift_status === 'active' ? 'Shift Active' : 'Shift Ended'; ?>
            </div>
        <?php endif; ?>
    </div>
</section>

<?php if (!empty($message)): ?>
<?php
    $icons = [
        'success' => '✅',
        'error'   => '❌',
        'warning' => '⚠️',
    ];
    $titles = [
        'success' => 'Success',
        'error'   => 'Error',
        'warning' => 'Warning',
    ];
    $type  = $message_type ?? 'success';
    $icon  = $icons[$type]  ?? '✅';
    $title = $titles[$type] ?? 'Notice';
?>
<div class="toast-overlay" id="toastOverlay">
    <div class="toast <?php echo htmlspecialchars($type); ?>" id="toast">
        <div class="toast-icon"><?php echo $icon; ?></div>
        <div class="toast-body">
            <div class="toast-title"><?php echo htmlspecialchars($title); ?></div>
            <div class="toast-msg"><?php echo htmlspecialchars($message); ?></div>
        </div>
        <button class="toast-close" onclick="hideToast()" aria-label="Close">✕</button>
        <div class="toast-progress"></div>
    </div>
</div>

<script>
    const TOAST_DURATION = 3500;

    function hideToast() {
        const toast   = document.getElementById('toast');
        const overlay = document.getElementById('toastOverlay');
        if (!toast) return;
        toast.classList.add('hide');
        setTimeout(() => { if (overlay) overlay.style.display = 'none'; }, 300);
    }

    setTimeout(hideToast, TOAST_DURATION);
</script>
<?php endif; ?>