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

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

$emp_filter = isset($_GET['emp']) ? intval($_GET['emp']) : 0;

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

// Handle Leave Request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_leave'])) {
    $employee_id = intval($_POST['employee_id'] ?? 0);
    $leave_type = sanitize($_POST['leave_type'] ?? 'annual');
    $start_date = $_POST['start_date'] ?? date('Y-m-d');
    $end_date = $_POST['end_date'] ?? date('Y-m-d');
    $reason = sanitize($_POST['reason'] ?? '');
    $status = sanitize($_POST['status'] ?? 'pending');

    if ($employee_id > 0 && !empty($start_date) && !empty($end_date)) {
        $total_days = (strtotime($end_date) - strtotime($start_date)) / (60 * 60 * 24) + 1;

        $stmt = $pdo->prepare("INSERT INTO employee_leaves 
            (employee_id, leave_type, start_date, end_date, total_days, reason, status, created_by) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$employee_id, $leave_type, $start_date, $end_date, $total_days, $reason, $status, $_SESSION['admin_id']]);

        $_SESSION['success_msg'] = 'Leave request added successfully!';
        header('Location: employee-leaves.php');
        exit;
    }
}

// Handle Leave Status Update
if (isset($_GET['action']) && isset($_GET['id'])) {
    $leave_id = intval($_GET['id']);
    $action = $_GET['action'];
    $status = $action == 'approve' ? 'approved' : 'rejected';

    $stmt = $pdo->prepare("UPDATE employee_leaves SET status = ?, approved_by = ?, approved_at = NOW() WHERE id = ?");
    $stmt->execute([$status, $_SESSION['admin_id'], $leave_id]);

    $_SESSION['success_msg'] = 'Leave ' . $status . ' successfully!';
    header('Location: employee-leaves.php');
    exit;
}

// Get leaves
$sql = "SELECT l.*, e.first_name, e.last_name 
        FROM employee_leaves l 
        LEFT JOIN employees e ON l.employee_id = e.id";
$params = [];
if ($emp_filter > 0) {
    $sql .= " WHERE l.employee_id = ?";
    $params[] = $emp_filter;
}
$sql .= " ORDER BY l.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$leaves = $stmt->fetchAll();

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

// When a leave is approved, automatically mark attendance as leave
if (isset($_GET['action']) && isset($_GET['id'])) {
    $leave_id = intval($_GET['id']);
    $action = $_GET['action'];
    $status = $action == 'approve' ? 'approved' : 'rejected';

    // Get leave details
    $stmt = $pdo->prepare("SELECT * FROM employee_leaves WHERE id = ?");
    $stmt->execute([$leave_id]);
    $leave = $stmt->fetch();

    if ($leave && $action == 'approve') {
        // Mark attendance for each day of the leave
        $start = strtotime($leave['start_date']);
        $end = strtotime($leave['end_date']);
        
        for ($date = $start; $date <= $end; $date = strtotime('+1 day', $date)) {
            $current_date = date('Y-m-d', $date);
            
            // Check if attendance already exists
            $stmt = $pdo->prepare("SELECT id FROM employee_attendance WHERE employee_id = ? AND date = ?");
            $stmt->execute([$leave['employee_id'], $current_date]);
            
            if (!$stmt->fetch()) {
                // Create leave attendance
                $leave_status = $leave['leave_type'] == 'sick' ? 'sick_leave' : 
                              ($leave['leave_type'] == 'casual' ? 'casual_leave' : 
                              ($leave['leave_type'] == 'emergency' ? 'emergency_leave' : 'leave'));
                
                $stmt = $pdo->prepare("INSERT INTO employee_attendance 
                    (employee_id, date, status, is_approved, note) 
                    VALUES (?, ?, ?, 1, ?)");
                $stmt->execute([
                    $leave['employee_id'], 
                    $current_date, 
                    $leave_status,
                    'Leave approved: ' . $leave['reason']
                ]);
            }
        }
    }

    $stmt = $pdo->prepare("UPDATE employee_leaves SET status = ?, approved_by = ?, approved_at = NOW() WHERE id = ?");
    $stmt->execute([$status, $_SESSION['admin_id'], $leave_id]);

    $_SESSION['success_msg'] = 'Leave ' . $status . ' successfully!';
    header('Location: employee-leaves.php');
    exit;
}

include 'header.php';
?>

<style>
.leave-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;
}

.status-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}

.status-badge.pending { background: #fcd34d; color: #92400e; }
.status-badge.approved { background: #86efac; color: #166534; }
.status-badge.rejected { background: #fca5a5; color: #991b1b; }
.status-badge.cancelled { background: #e2e8f0; color: #475569; }
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-calendar-check me-2"></i> Employee Leaves</h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#leaveModal">
            <i class="fa-solid fa-plus"></i> Request Leave
        </button>
    </div>

    <!-- Filter -->
    <div class="admin-card mb-3">
        <form method="GET" class="row g-3">
            <div class="col-md-4">
                <label class="form-label">Filter by Employee</label>
                <select name="emp" class="form-control" onchange="this.form.submit()">
                    <option value="">All Employees</option>
                    <?php foreach ($employees as $emp): ?>
                    <option value="<?php echo $emp['id']; ?>" <?php echo $emp['id'] == $emp_filter ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($emp['first_name'] . ' ' . $emp['last_name']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-8 d-flex align-items-end">
                <a href="employee-leaves.php" class="btn btn-secondary">Clear Filter</a>
            </div>
        </form>
    </div>

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

    <!-- Stats -->
    <?php
    $pending = 0; $approved = 0; $rejected = 0;
    foreach ($leaves as $leave) {
        switch($leave['status']) {
            case 'pending': $pending++; break;
            case 'approved': $approved++; break;
            case 'rejected': $rejected++; break;
        }
    }
    ?>
    <div class="leave-stats">
        <div class="stat-box">
            <div class="stat-number text-warning"><?php echo $pending; ?></div>
            <div class="stat-label">Pending</div>
        </div>
        <div class="stat-box">
            <div class="stat-number text-success"><?php echo $approved; ?></div>
            <div class="stat-label">Approved</div>
        </div>
        <div class="stat-box">
            <div class="stat-number text-danger"><?php echo $rejected; ?></div>
            <div class="stat-label">Rejected</div>
        </div>
        <div class="stat-box">
            <div class="stat-number text-primary"><?php echo count($leaves); ?></div>
            <div class="stat-label">Total</div>
        </div>
    </div>

    <!-- Leave Table -->
    <div class="admin-card">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Employee</th>
                        <th>Type</th>
                        <th>Start Date</th>
                        <th>End Date</th>
                        <th>Days</th>
                        <th>Reason</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($leaves)): ?>
                    <tr>
                        <td colspan="8" class="text-center py-4">
                            <i class="fa-regular fa-calendar fa-2x text-muted d-block mb-2"></i>
                            No leave requests found
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($leaves as $leave): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($leave['first_name'] . ' ' . $leave['last_name']); ?></td>
                        <td>
                            <span class="badge bg-secondary"><?php echo ucfirst($leave['leave_type']); ?></span>
                        </td>
                        <td><?php echo date('d M Y', strtotime($leave['start_date'])); ?></td>
                        <td><?php echo date('d M Y', strtotime($leave['end_date'])); ?></td>
                        <td class="fw-bold"><?php echo $leave['total_days']; ?></td>
                        <td><?php echo substr(htmlspecialchars($leave['reason']), 0, 30) . (strlen($leave['reason']) > 30 ? '...' : ''); ?></td>
                        <td>
                            <span class="status-badge <?php echo $leave['status']; ?>">
                                <?php echo ucfirst($leave['status']); ?>
                            </span>
                        </td>
                        <td>
                            <?php if ($leave['status'] == 'pending'): ?>
                            <a href="?action=approve&id=<?php echo $leave['id']; ?>" class="btn btn-sm btn-success" onclick="return confirm('Approve this leave?')">
                                <i class="fa-solid fa-check"></i>
                            </a>
                            <a href="?action=reject&id=<?php echo $leave['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Reject this leave?')">
                                <i class="fa-solid fa-times"></i>
                            </a>
                            <?php else: ?>
                            <span class="text-muted">-</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Request Leave Modal -->
<div class="modal fade" id="leaveModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Request Leave</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="add_leave" value="1">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Employee</label>
                        <select name="employee_id" class="form-control" required>
                            <option value="">Select Employee</option>
                            <?php foreach ($employees as $emp): ?>
                            <option value="<?php echo $emp['id']; ?>">
                                <?php echo htmlspecialchars($emp['first_name'] . ' ' . $emp['last_name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Leave Type</label>
                        <select name="leave_type" class="form-control">
                            <option value="annual">Annual</option>
                            <option value="sick">Sick</option>
                            <option value="casual">Casual</option>
                            <option value="emergency">Emergency</option>
                            <option value="maternity">Maternity</option>
                            <option value="paternity">Paternity</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Start Date</label>
                                <input type="date" name="start_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">End Date</label>
                                <input type="date" name="end_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Reason</label>
                        <textarea name="reason" class="form-control" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control">
                            <option value="pending">Pending</option>
                            <option value="approved">Approved</option>
                            <option value="rejected">Rejected</option>
                        </select>
                    </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">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>

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