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

// Check if user is logged in and has 'md' role
if (!isset($_SESSION['user_id']) || strtolower($_SESSION['role']) !== 'md') {
    header("Location: index.php");
    exit();
}

// Get parameters from URL
$user_id = isset($_GET['user_id']) ? $_GET['user_id'] : '';
$month = isset($_GET['month']) ? (int)$_GET['month'] : date('m');
$year = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');

// Validate month and year
if ($month < 1 || $month > 12) {
    $month = date('m');
}
if ($year < 2000 || $year > 2100) {
    $year = date('Y');
}

$month_year = sprintf("%d-%02d", $year, $month);

// Fetch attendance details
$query = "SELECT a.*, COALESCE(u.first_name, '') AS first_name, COALESCE(u.last_name, '') AS last_name
          FROM attendancetech a
          LEFT JOIN users u ON a.user_id = u.id
          WHERE a.user_id = ? AND DATE_FORMAT(a.attendance_date, '%Y-%m') = ?
          ORDER BY a.attendance_date DESC";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, "ss", $user_id, $month_year);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Attendance Details - <?php echo htmlspecialchars($user_id); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        h2 {
            font-size: 1.5rem;
            color: #2c3e50;
            margin-bottom: 20px;
        }
        .table {
            width: 100%;
            border-collapse: collapse;
        }
        .table th, .table td {
            padding: 12px;
            border: 1px solid #ddd;
            text-align: left;
            font-size: 0.9rem;
        }
        .table th {
            background: #2c3e50;
            color: white;
            font-weight: 600;
        }
        .table tr:nth-child(even) {
            background: #f9f9f9;
        }
        .table tr:hover {
            background: #e8f4f8;
        }
        .table-responsive {
            overflow-x: auto;
        }
        .btn-back {
            margin-top: 20px;
        }
        @media (max-width: 576px) {
            .table {
                font-size: 0.75rem;
                display: block;
                overflow-x: auto;
            }
            h2 {
                font-size: 1.2rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>Attendance Details for <?php echo htmlspecialchars(trim($result->num_rows > 0 ? ($result->fetch_assoc()['first_name'] . ' ' . $result->fetch_assoc()['last_name']) : $user_id)); ?></h2>
        <div class="table-responsive">
            <table class="table table-bordered table-striped">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>In Time</th>
                        <th>Out Time</th>
                        <th>Status</th>
                        <th>Hours</th>
                        <th>Late By</th>
                        <th>Early Exit</th>
                        <th>Approval Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // Reset result pointer to start
                    mysqli_data_seek($result, 0);
                    if ($result->num_rows > 0) {
                        while ($row = mysqli_fetch_assoc($result)) {
                            $hours = number_format($row['working_hours'] ?? 0, 2);
                            echo "<tr>
                                    <td>" . date('d-m-Y', strtotime($row['attendance_date'])) . "</td>
                                    <td>" . ($row['in_time'] ?: '-') . "</td>
                                    <td>" . ($row['out_time'] ?: '-') . "</td>
                                    <td>" . ($row['status'] ?: 'N/A') . "</td>
                                    <td>" . $hours . "</td>
                                    <td>" . ($row['late_by'] ?: '-') . "</td>
                                    <td>" . ($row['early_exit'] ?: '-') . "</td>
                                    <td>" . htmlspecialchars(ucfirst($row['approval_status'] ?? 'Pending')) . "</td>
                                  </tr>";
                        }
                    } else {
                        echo "<tr><td colspan='8' class='text-center'>No attendance data found for the selected period.</td></tr>";
                    }
                    mysqli_stmt_close($stmt);
                    ?>
                </tbody>
            </table>
        </div>
        <a href="payroll_approval.php?month=<?php echo $month; ?>&year=<?php echo $year; ?>" class="btn btn-primary btn-back">Back to Approval</a>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>