<?php
session_start();
include 'config.php';

date_default_timezone_set('Asia/Kolkata');
mysqli_query($conn, "SET time_zone = '+05:30'");

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");

if (!isset($_SESSION['employee_id'])) {
    header("Location: login.php");
    exit();
}

$employee_id = $_SESSION['employee_id'];

$result = mysqli_query($conn, "SELECT * FROM register WHERE employee_id='$employee_id'");
$employee = mysqli_fetch_assoc($result);
$name = $employee['fname'] . ' ' . $employee['lname'];

$dateToday = date("Y-m-d");
$msg = "";
$attendanceRow = null;

// ✅ Handle In Time
if (isset($_POST['in_time'])) {
    $login_time = date("Y-m-d H:i:s");
    $check_sql = "SELECT * FROM attendance 
                  WHERE employee_id = '$employee_id' 
                    AND logout_time IS NULL
                  LIMIT 1";
    $result = mysqli_query($conn, $check_sql);

    if (mysqli_num_rows($result) > 0) {
        $msg = "⚠️ You already have an active session. Please record Out Time first.";
    } else {
        $insert_sql = "INSERT INTO attendance (employee_id, name, login_time) 
                       VALUES ('$employee_id', '$name', '$login_time')";
        if (mysqli_query($conn, $insert_sql)) {
            $msg = "✅ In Time recorded successfully!";
        } else {
            $msg = "❌ Error recording In Time: " . mysqli_error($conn);
        }
    }
}

// ✅ Handle Out Time
if (isset($_POST['out_time'])) {
    $logout_time = date("Y-m-d H:i:s");
    $sql_latest = "SELECT id 
                   FROM attendance 
                   WHERE employee_id = '$employee_id' 
                     AND (logout_time IS NULL OR logout_time = '' OR logout_time = '0000-00-00 00:00:00')
                   ORDER BY login_time DESC 
                   LIMIT 1";
    $result = mysqli_query($conn, $sql_latest);

    if ($row = mysqli_fetch_assoc($result)) {
        $attendance_id = $row['id'];
        $sql_update = "UPDATE attendance 
                       SET logout_time = '$logout_time' 
                       WHERE id = '$attendance_id' AND logout_time IS NULL";
        if (mysqli_query($conn, $sql_update)) {
            $attendanceRow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM attendance WHERE id='$attendance_id'"));
            $msg = "✅ Out Time recorded successfully at " . date("h:i A", strtotime($attendanceRow['logout_time']));
        } else {
            $msg = "⚠️ Error updating Out Time.";
        }
    } else {
        $msg = "⚠️ No open shift found to record Out Time.";
    }
}

// ✅ Handle file upload
if (isset($_POST['submit_file']) && isset($_FILES['file'])) {
    $fileName = $_FILES['file']['name'];
    $fileTmp = $_FILES['file']['tmp_name'];
    $targetDir = "uploads/";
    $targetFile = $targetDir . basename($fileName);

    if (move_uploaded_file($fileTmp, $targetFile)) {
        mysqli_query($conn, "UPDATE attendance SET file_path='$targetFile' WHERE employee_id='$employee_id' ORDER BY login_time DESC LIMIT 1");
        $uploadMsg = "✅ File uploaded successfully!";
    } else {
        $uploadMsg = "❌ File upload failed.";
    }
}

// ✅ Fetch latest attendance for today
$attendance = mysqli_query($conn, "SELECT * FROM attendance WHERE employee_id='$employee_id' AND DATE(login_time)='$dateToday' ORDER BY login_time DESC LIMIT 1");
$attendanceRow = mysqli_fetch_assoc($attendance);

// ✅ Determine button states
$disableIn = false;
$disableOut = false;
$disableUpload = false; // new flag for upload button

if ($attendanceRow) {
    if (empty($attendanceRow['logout_time']) || $attendanceRow['logout_time'] == '0000-00-00 00:00:00') {
        $disableIn = true;  // After In, before Out
        $disableOut = false;
        $disableUpload = false; // can still upload
    } else {
        $disableIn = false; // After Out
        $disableOut = true;
        $disableUpload = true; // disable upload after out time
    }
}

// ✅ Null-safe display for logout_time
if (!empty($attendanceRow['logout_time']) && $attendanceRow['logout_time'] != '0000-00-00 00:00:00') {
    $displayLogout = date("h:i A", strtotime($attendanceRow['logout_time']));
} else {
    $displayLogout = "Not recorded yet";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Profile</title>
<style>
/* your existing styles unchanged */
body {
    font-family: Arial, sans-serif;
    background-color: #f5f5f5;
    margin: 0;
    padding: 0;
}

header {
    background-color: #f8f9fa;
    padding: 16px 32px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

header h2 {
    color: blue;
    margin: 0;
}

header a {
    text-decoration: none;
    color: black;
    font-weight: bold;
}

.card {
    max-width: 800px;
    margin: 40px auto;
    background-color: white;
    padding: 40px;
    border-radius: 12px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.card img {
    width: 200px;
    height: 200px;
    border-radius: 80%;
    object-fit: cover;
    margin-bottom: 20px;
}

.emp-info {
    text-align: center;
}

.emp-details {
    background-color: #fffbe6;
    border: 2px solid #ffcccc;
    padding: 30px;
    border-radius: 8px;
    margin-top: 30px;
}

.emp-details h2 {
    color: #d9534f;
    margin-bottom: 20px;
}

.emp-details p {
    font-size: 16px;
    margin: 8px 0;
}

/* Logout Popup Styling */
#leaving {
    display: none;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    border: 2px solid #ccc;
    padding: 20px 30px;
    z-index: 9999;
    box-shadow: 0 0 15px rgba(0,0,0,0.3);
    border-radius: 10px;
    text-align: center;
}

#leaving .leave-header {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 15px;
}

#leaving .leave-button button {
    margin: 0 10px;
    padding: 8px 16px;
    border-radius: 5px;
    border: none;
    background-color: #007bff;
    color: white;
    cursor: pointer;
}

#leaving .leave-button button:hover {
    background-color: #0056b3;
}

#leaving .leave-button button[type="button"] {
    background-color: #6c757d;
}

#leaving .leave-button button[type="button"]:hover {
    background-color: #5a6268;
}
</style>
</head>
<script>
  setInterval(() => {
    fetch(window.location.href, { method: 'GET', cache: 'no-store' });
  }, 300000);
</script>
<body>
<header>
<h2>Hello, <?php echo $employee['fname']; ?></h2>
<a href="#" onclick="document.getElementById('leaving').style.display='block'; return false;">Logout</a>
</header>
<div class="card">
<div class="emp-info">
<img src="img/<?php echo $employee['photo']; ?>" alt="Employee Photo">
<h2><?php echo $employee['fname'] . ' ' . $employee['lname']; ?></h2>
<p><?php echo $employee['qualification']; ?></p>
</div>
<div class="emp-details">
<h2>Employee Details</h2>
<p><strong>Employee ID:</strong> <?php echo $employee['employee_id']; ?></p>
<p><strong>Personal Email:</strong> <?php echo $employee['email']; ?></p>
<p><strong>Mobile Phone:</strong> <?php echo $employee['number']; ?></p>
<p><strong>Home Address:</strong> <?php echo $employee['address']; ?></p>
<p><strong>Date of Birth:</strong> <?php echo date("d-m-Y", strtotime($employee['dob'])); ?></p>
<p><strong>Gender:</strong> <?php echo $employee['gender']; ?></p>
<p><strong>Qualification:</strong> <?php echo $employee['qualification']; ?></p>
<p><strong>Joining Date:</strong> <?php echo date("d-m-Y", strtotime($employee['joining'])); ?></p>
<form method="POST" style="margin-bottom: 15px;">
    <button type="submit" name="in_time" <?php if ($disableIn) echo "disabled"; ?>>In Time</button>
    <button type="submit" name="out_time" <?php if ($disableOut) echo "disabled"; ?>>Out Time</button>
</form>
<?php if (isset($msg)) echo "<p style='color:blue; text-align:center;'>$msg</p>"; ?>
<?php if (isset($uploadMsg)) echo "<p style='color: green; text-align:center;'>$uploadMsg</p>"; ?>
<div class="row">
<div class="col-sm-6 form-group">
<form action="" method="POST" enctype="multipart/form-data">
    <label>Upload Report File</label>
    <input type="file" name="file" class="form-control" required <?php if ($disableUpload) echo "disabled"; ?>>
    <button type="submit" name="submit_file" class="btn btn-primary mt-2" <?php if ($disableUpload) echo "disabled"; ?>>Upload</button>
</form>
</div>
</div>
</div>
</div>
<div id="leaving">
<div class="leave-header">LogOut ?</div>
<div class="leave-button">
<form action="logout.php" method="post">
<button type="submit" name="logout">Yes</button>
<button type="button" onclick="document.getElementById('leaving').style.display='none';">No</button>
</form>
</div>
</div>
</body>
</html>
