<?php
// admin/employee-attendance.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (!isAdmin()) {
    header('Location: login.php');
    exit;
}

$emp_id = isset($_GET['emp']) ? intval($_GET['emp']) : 0;
$month = isset($_GET['month']) ? $_GET['month'] : date('Y-m');
$date_range = explode('-', $month);
$year = $date_range[0];
$month_num = $date_range[1];

// Get employee list for dropdown
$employees = $pdo->query("SELECT id, first_name, last_name FROM employees WHERE status = 1 ORDER BY first_name")->fetchAll();

// Get selected employee name
$employee_name = '';
if ($emp_id > 0) {
    $stmt = $pdo->prepare("SELECT first_name, last_name FROM employees WHERE id = ?");
    $stmt->execute([$emp_id]);
    $emp = $stmt->fetch();
    $employee_name = $emp ? $emp['first_name'] . ' ' . $emp['last_name'] : '';
}

// Get attendance for selected employee and month
$attendance = [];
if ($emp_id > 0) {
    $stmt = $pdo->prepare("SELECT * FROM employee_attendance 
                           WHERE employee_id = ? AND YEAR(date) = ? AND MONTH(date) = ?
                           ORDER BY date ASC");
    $stmt->execute([$emp_id, $year, $month_num]);
    $attendance = $stmt->fetchAll();
}

// Mark attendance
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mark_attendance'])) {
    $date = $_POST['date'] ?? date('Y-m-d');
    $status = $_POST['status'] ?? 'present';
    $check_in = $_POST['check_in'] ?? null;
    $check_out = $_POST['check_out'] ?? null;
    $note = sanitize($_POST['note'] ?? '');

    // Check if attendance already exists
    $stmt = $pdo->prepare("SELECT id FROM employee_attendance WHERE employee_id = ? AND date = ?");
    $stmt->execute([$emp_id, $date]);
    if ($stmt->fetch()) {
        $stmt = $pdo->prepare("UPDATE employee_attendance SET 
            status = ?, check_in = ?, check_out = ?, note = ? 
            WHERE employee_id = ? AND date = ?");
        $stmt->execute([$status, $check_in, $check_out, $note, $emp_id, $date]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO employee_attendance 
            (employee_id, date, check_in, check_out, status, note) 
            VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$emp_id, $date, $check_in, $check_out, $status, $note]);
    }

    $_SESSION['success_msg'] = 'Attendance marked successfully!';
    header('Location: employee-attendance.php?emp=' . $emp_id . '&month=' . $month);
    exit;
}

$success_msg = $_SESSION['success_msg'] ?? '';
unset($_SESSION['success_msg']);

// Update the INSERT/UPDATE query to include is_approved
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mark_attendance'])) {
    $date = $_POST['date'] ?? date('Y-m-d');
    $status = $_POST['status'] ?? 'present';
    $check_in = $_POST['check_in'] ?? null;
    $check_out = $_POST['check_out'] ?? null;
    $note = sanitize($_POST['note'] ?? '');
    $is_approved = isset($_POST['is_approved']) ? 1 : 0;

    // If status is present, auto approve
    if ($status == 'present' || $status == 'late' || $status == 'half_day') {
        $is_approved = 1;
    }

    // Check if attendance already exists
    $stmt = $pdo->prepare("SELECT id FROM employee_attendance WHERE employee_id = ? AND date = ?");
    $stmt->execute([$emp_id, $date]);
    if ($stmt->fetch()) {
        $stmt = $pdo->prepare("UPDATE employee_attendance SET 
            status = ?, check_in = ?, check_out = ?, note = ?, is_approved = ? 
            WHERE employee_id = ? AND date = ?");
        $stmt->execute([$status, $check_in, $check_out, $note, $is_approved, $emp_id, $date]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO employee_attendance 
            (employee_id, date, check_in, check_out, status, note, is_approved) 
            VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$emp_id, $date, $check_in, $check_out, $status, $note, $is_approved]);
    }

    $_SESSION['success_msg'] = 'Attendance marked successfully!';
    header('Location: employee-attendance.php?emp=' . $emp_id . '&month=' . $month);
    exit;
}

include 'header.php';
?>

<style>
.attendance-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 15px;
    margin-bottom: 20px;
}

.stat-box {
    background: #fff;
    border-radius: 10px;
    padding: 15px;
    text-align: center;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
}

.stat-box .stat-number {
    font-size: 24px;
    font-weight: 700;
}

.stat-box .stat-label {
    font-size: 12px;
    color: #64748b;
}

.attendance-calendar {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 5px;
    background: #fff;
    padding: 15px;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
}

.day-header {
    text-align: center;
    font-weight: 600;
    color: #64748b;
    padding: 8px 0;
    font-size: 12px;
}

.day-cell {
    text-align: center;
    padding: 12px 5px;
    border-radius: 8px;
    font-size: 13px;
    cursor: default;
    min-height: 50px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 1px solid #e2e8f0;
}

.day-cell .date-num {
    font-weight: 600;
}

.day-cell .status-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-top: 3px;
}

.day-cell.present {
    background: #f0fdf4;
    border-color: #86efac;
}
.day-cell.present .status-dot { background: #22c55e; }

.day-cell.absent {
    background: #fef2f2;
    border-color: #fca5a5;
}
.day-cell.absent .status-dot { background: #ef4444; }

.day-cell.late {
    background: #fffbeb;
    border-color: #fcd34d;
}
.day-cell.late .status-dot { background: #f59e0b; }

.day-cell.half_day {
    background: #f0f9ff;
    border-color: #93c5fd;
}
.day-cell.half_day .status-dot { background: #3b82f6; }

.day-cell.holiday {
    background: #f5f3ff;
    border-color: #c4b5fd;
}
.day-cell.holiday .status-dot { background: #8b5cf6; }

.day-cell.leave {
    background: #fdf2f8;
    border-color: #f9a8d4;
}
.day-cell.leave .status-dot { background: #ec4899; }

.day-cell.empty {
    border: none;
    background: transparent;
}

.attendance-form {
    background: #fff;
    padding: 20px;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
    margin-bottom: 20px;
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-clock me-2"></i> Employee Attendance</h2>
        <div>
            <a href="employees.php" class="btn btn-secondary">
                <i class="fa-solid fa-arrow-left"></i> Back
            </a>
        </div>
    </div>

    <!-- Filter -->
    <div class="admin-card mb-3">
        <form method="GET" class="row g-3">
            <div class="col-md-4">
                <label class="form-label">Employee</label>
                <select name="emp" class="form-control" onchange="this.form.submit()">
                    <option value="">Select Employee</option>
                    <?php foreach ($employees as $emp): ?>
                    <option value="<?php echo $emp['id']; ?>" <?php echo $emp['id'] == $emp_id ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($emp['first_name'] . ' ' . $emp['last_name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">Month</label>
                <input type="month" name="month" class="form-control" value="<?php echo $month; ?>" onchange="this.form.submit()">
            </div>
            <?php if ($emp_id > 0): ?>
            <div class="col-md-5 d-flex align-items-end">
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#attendanceModal">
                    <i class="fa-solid fa-plus"></i> Mark Attendance
                </button>
            </div>
            <?php endif; ?>
        </form>
    </div>

    <?php if ($success_msg): ?>
    <div class="alert alert-success"><?php echo $success_msg; ?></div>
    <?php endif; ?>

    <?php if ($emp_id > 0 && $employee_name): ?>

    <!-- Stats -->
    <?php
    $present = 0; $absent = 0; $late = 0; $half_day = 0; $holiday = 0; $leave = 0;
    $total_days = cal_days_in_month(CAL_GREGORIAN, $month_num, $year);
    foreach ($attendance as $att) {
        switch($att['status']) {
            case 'present': $present++; break;
            case 'absent': $absent++; break;
            case 'late': $late++; break;
            case 'half_day': $half_day++; break;
            case 'holiday': $holiday++; break;
            case 'leave': $leave++; break;
        }
    }
    ?>
    <div class="attendance-stats">
        <div class="stat-box">
            <div class="stat-number text-success"><?php echo $present; ?></div>
            <div class="stat-label">Present</div>
        </div>
        <div class="stat-box">
            <div class="stat-number text-danger"><?php echo $absent; ?></div>
            <div class="stat-label">Absent</div>
        </div>
        <div class="stat-box">
            <div class="stat-number text-warning"><?php echo $late; ?></div>
            <div class="stat-label">Late</div>
        </div>
        <div class="stat-box">
            <div class="stat-number text-info"><?php echo $half_day; ?></div>
            <div class="stat-label">Half Day</div>
        </div>
        <div class="stat-box">
            <div class="stat-number text-purple"><?php echo $holiday; ?></div>
            <div class="stat-label">Holiday</div>
        </div>
        <div class="stat-box">
            <div class="stat-number text-pink"><?php echo $leave; ?></div>
            <div class="stat-label">Leave</div>
        </div>
    </div>

    <!-- Calendar -->
    <div class="attendance-calendar">
        <div class="day-header">Sun</div>
        <div class="day-header">Mon</div>
        <div class="day-header">Tue</div>
        <div class="day-header">Wed</div>
        <div class="day-header">Thu</div>
        <div class="day-header">Fri</div>
        <div class="day-header">Sat</div>

        <?php
        $first_day = strtotime($year . '-' . $month_num . '-01');
        $start_day = date('w', $first_day);
        $days_in_month = cal_days_in_month(CAL_GREGORIAN, $month_num, $year);

        for ($i = 0; $i < $start_day; $i++) {
            echo '<div class="day-cell empty"></div>';
        }

        for ($day = 1; $day <= $days_in_month; $day++) {
            $date = $year . '-' . sprintf('%02d', $month_num) . '-' . sprintf('%02d', $day);
            $status = '';
            $status_text = '';
            foreach ($attendance as $att) {
                if ($att['date'] == $date) {
                    $status = $att['status'];
                    break;
                }
            }
            $class = $status ? $status : 'empty';
            ?>
            <div class="day-cell <?php echo $class; ?>" title="<?php echo $status ? ucfirst($status) : 'No record'; ?>">
                <div class="date-num"><?php echo $day; ?></div>
                <?php if ($status): ?>
                <div class="status-dot"></div>
                <?php endif; ?>
            </div>
            <?php
        }
        ?>
    </div>

    <?php else: ?>
    <div class="alert alert-info">
        <i class="fa-solid fa-info-circle me-2"></i> 
        Please select an employee to view attendance.
    </div>
    <?php endif; ?>
</div>

<!-- Mark Attendance Modal -->
<div class="modal fade" id="attendanceModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Mark Attendance</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="mark_attendance" value="1">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Employee</label>
                        <p class="fw-bold"><?php echo $employee_name; ?></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Date</label>
                        <input type="date" name="date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control">
                            <option value="present">Present</option>
                            <option value="absent">Absent</option>
                            <option value="late">Late</option>
                            <option value="half_day">Half Day</option>
                            <option value="holiday">Holiday</option>
                            <option value="leave">Leave</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Check In Time</label>
                        <input type="time" name="check_in" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Check Out Time</label>
                        <input type="time" name="check_out" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Note</label>
                        <textarea name="note" class="form-control" rows="2"></textarea>
                    </div>
                </div>
                // In the attendance modal, add:
<div class="mb-3">
    <div class="form-check">
        <input type="checkbox" name="is_approved" class="form-check-input" id="isApproved" checked>
        <label class="form-check-label" for="isApproved">Is this absence approved?</label>
    </div>
</div>


                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Attendance</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>