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

ini_set('display_errors', 1);
error_reporting(E_ALL);

if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    $_SESSION['error'] = "Please log in to continue.";
    header("Location: index.php");
    exit();
}

$stmt = $conn->prepare("SELECT id, username, role FROM users WHERE id = ?");
$stmt->bind_param("s", $_SESSION['user_id']);
$stmt->execute();
$user_result = $stmt->get_result();

if ($user_result->num_rows === 0) {
    unset($_SESSION['user_id']);
    $_SESSION['error'] = "User not found.";
    header("Location: index.php");
    exit();
}

$user = $user_result->fetch_assoc();
$employee_id = $user['id'];
$user_role = strtolower(trim($user['role']));
$stmt->close();

/* HELPER: UPSERT LEAVE BALANCE */
if (!function_exists('upsertLeaveBalance')) {
    function upsertLeaveBalance($conn, $userId, $type, $balance) {
        $sql = "SELECT id FROM leave_balance WHERE user_id = ? AND leave_type = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ss", $userId, $type);
        $stmt->execute();
        $res = $stmt->get_result();
        $row = $res->fetch_assoc();
        $stmt->close();

        if ($row) {
            $up = $conn->prepare("UPDATE leave_balance SET balance = ? WHERE id = ?");
            $up->bind_param("ii", $balance, $row['id']);
            $up->execute();
            $up->close();
        } else {
            $ins = $conn->prepare("INSERT INTO leave_balance (user_id, leave_type, balance) VALUES (?, ?, ?)");
            $ins->bind_param("ssi", $userId, $type, $balance);
            $ins->execute();
            $ins->close();
        }
    }
}

/* HR: UPDATE BALANCE */
if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['action']) && $_POST['action'] === 'update_leave_balance' &&
    in_array($user_role, ['admin', 'superadmin'])
) {
    $emp_id = trim($_POST['employee_id'] ?? '');
    $pl = (int)($_POST['pl_balance'] ?? 0);
    $sl = (int)($_POST['sl_balance'] ?? 0);

    if ($emp_id !== '') {
        upsertLeaveBalance($conn, $emp_id, 'PL', $pl);
        upsertLeaveBalance($conn, $emp_id, 'SL', $sl);
        $_SESSION['message'] = "Leave balance updated successfully.";
    } else {
        $_SESSION['error'] = "Invalid employee selected.";
    }
    header("Location: leave_dashboard.php");
    exit();
}

/* FETCH MY BALANCE */
$my_leave_balance = ['PL' => 0, 'SL' => 0];
$stmt = $conn->prepare("SELECT leave_type, balance FROM leave_balance WHERE user_id = ?");
$stmt->bind_param("s", $employee_id);
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
    if ($row['leave_type'] === 'PL') $my_leave_balance['PL'] = (int)$row['balance'];
    if ($row['leave_type'] === 'SL') $my_leave_balance['SL'] = (int)$row['balance'];
}
$stmt->close();

/* HR: ALL EMPLOYEES BALANCES */
$all_balances_rows = [];
if (in_array($user_role, ['admin', 'superadmin'])) {
    $sql = "
        SELECT u.id, u.username,
               MAX(CASE WHEN lb.leave_type = 'PL' THEN lb.balance END) AS pl_balance,
               MAX(CASE WHEN lb.leave_type = 'SL' THEN lb.balance END) AS sl_balance
        FROM users u LEFT JOIN leave_balance lb ON lb.user_id = u.id
        GROUP BY u.id, u.username ORDER BY u.username
    ";
    $result = $conn->query($sql);
    while ($row = $result->fetch_assoc()) {
        $all_balances_rows[] = $row;
    }
}

/* EDIT PREFILL */
$edit_emp_id = 0; $edit_pl = 0; $edit_sl = 0;
if (in_array($user_role, ['admin', 'superadmin']) && isset($_GET['edit_emp_id'])) {
    $edit_emp_id = (int)$_GET['edit_emp_id'];
    $stmt = $conn->prepare("SELECT leave_type, balance FROM leave_balance WHERE user_id = ?");
    $stmt->bind_param("s", $edit_emp_id);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($r = $res->fetch_assoc()) {
        if ($r['leave_type'] === 'PL') $edit_pl = (int)$r['balance'];
        if ($r['leave_type'] === 'SL') $edit_sl = (int)$r['balance'];
    }
    $stmt->close();
}

/* FIXED FUNCTION: employee_id optional */
function fetchRequests($conn, $sql, $user_role, $employee_id = null) {
    $requests = [];
    if (in_array($user_role, ['admin', 'superadmin'])) {
        $result = $conn->query($sql);
        while ($row = $result->fetch_assoc()) {
            $requests[] = $row;
        }
    } else {
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("s", $employee_id);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $requests[] = $row;
        }
        $stmt->close();
    }
    return $requests;
}

/* FETCH ALL LEAVE REQUESTS */
$base_sql = "
    SELECT 
        lr.id, lr.employee_id, u.username, lr.leave_type, lr.start_date, lr.end_date,
        lr.reason, lr.status, lr.applied_on,
        lr.delegate_to_name, lr.work_description,
        lr.permission_date, lr.permission_time_from, lr.permission_time_to, lr.permission_hours
    FROM leave_requests lr
    LEFT JOIN users u ON lr.employee_id = u.id
";

$pending_sql  = $base_sql . " WHERE lr.status = 'Pending' ORDER BY lr.applied_on DESC";
$approved_sql = $base_sql . " WHERE lr.status = 'Approved' ORDER BY lr.applied_on DESC";
$rejected_sql = $base_sql . " WHERE lr.status = 'Rejected' ORDER BY lr.applied_on DESC";

if (!in_array($user_role, ['admin', 'superadmin'])) {
    $pending_sql  .= " AND lr.employee_id = ?";
    $approved_sql .= " AND lr.employee_id = ?";
    $rejected_sql .= " AND lr.employee_id = ?";
}

$pending  = fetchRequests($conn, $pending_sql, $user_role, $employee_id);
$approved = fetchRequests($conn, $approved_sql, $user_role, $employee_id);
$rejected = fetchRequests($conn, $rejected_sql, $user_role, $employee_id);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?= in_array($user_role, ['admin','superadmin']) ? 'Leave Approval Dashboard' : 'My Leave Requests' ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root {
            --primary: #4361ee;
            --primary-dark: #3f37c9;
            --success: #4cc9f0;
            --danger: #f72585;
            --warning: #f8961e;
            --card-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', sans-serif;
        }
        .hamburger {
            position: fixed;
            top: 15px;
            left: 15px;
            z-index: 1100;
            background: var(--primary);
            border: none;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            box-shadow: 0 4px 15px rgba(67,97,238,0.3);
        }
        .sidebar {
            position: fixed;
            top: 0;
            left: -280px;
            width: 280px;
            height: 100%;
            background: linear-gradient(to bottom, var(--primary), var(--primary-dark));
            transition: left 0.3s ease;
            z-index: 1050;
            padding-top: 80px;
            box-shadow: 5px 0 20px rgba(0,0,0,0.15);
        }
        .sidebar.active { left: 0; }
        .sidebar a {
            color: rgba(255,255,255,0.9);
            padding: 15px 25px;
            display: block;
            font-size: 1.05rem;
            transition: all 0.2s;
        }
        .sidebar a:hover, .sidebar a.active {
            background: rgba(255,255,255,0.15);
            padding-left: 35px;
        }
        .sidebar h2 { color: white; text-align: center; margin: 20px 0; font-weight: 600; }
        .content { padding: 20px; margin-top: 60px; }
        .content.active { margin-left: 280px; }
        .card {
            border: none;
            border-radius: 16px;
            box-shadow: var(--card-shadow);
            overflow: hidden;
            margin-bottom: 25px;
        }
        .card-header {
            background: var(--primary);
            color: white;
            font-weight: 600;
            padding: 18px 25px;
        }
        .table thead { background: var(--primary); color: white; }
        .badge-pending { background: #ffc107; color: #000; }
        .badge-approved { background: #28a745; }
        .badge-rejected { background: #dc3545; }
        .status-tabs {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin: 30px 0;
            flex-wrap: wrap;
        }
        .status-tab {
            padding: 12px 30px;
            background: #e9ecef;
            border-radius: 50px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s;
        }
        .status-tab.active {
            background: var(--primary);
            color: white;
            box-shadow: 0 4px 15px rgba(67,97,238,0.4);
        }
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        @media (max-width: 768px) {
            .content { margin-top: 20px; padding: 15px; }
            .content.active { margin-left: 0; }
        }
    </style>
</head>
<body>
    <button class="hamburger btn shadow-lg" onclick="toggleSidebar()">
        <i class="fas fa-bars fa-lg"></i>
    </button>

    <div class="sidebar" id="sidebar">
        <h2>Mypeopleconnect</h2>
        <a href="dashboard_admin.php">Organisation Chart</a>
        <a href="manage_users.php">Employee Details</a>
        <a href="leave_dashboard.php" class="active">Leave Dashboard</a>
        <a href="grievance_dashboard.php">Grievance Portal</a>
        <li><a class="dropdown-item" href="change_password.php">Change Password</a></li>
        <a href="logout.php" class="text-danger">Logout</a>
    </div>

    <div class="content" id="content">
        <h1 class="text-center mb-4 fw-bold" style="color: var(--primary);">
            <?= in_array($user_role, ['admin','superadmin']) ? 'Leave Approval Dashboard' : 'My Leave Requests' ?>
        </h1>

        <?php if (isset($_SESSION['message'])): ?>
            <div class="alert alert-success rounded-4 shadow-sm text-center py-3">
                <?= htmlspecialchars($_SESSION['message']); unset($_SESSION['message']); ?>
            </div>
        <?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger rounded-4 shadow-sm text-center py-3">
                <?= htmlspecialchars($_SESSION['error']); unset($_SESSION['error']); ?>
            </div>
        <?php endif; ?>

        <!-- My Leave Balance -->
        <div class="card mb-5">
            <div class="card-header"><h5><i class="fas fa-balance-scale me-2"></i>My Leave Balance</h5></div>
            <div class="card-body">
                <div class="row g-4 text-center">
                    <div class="col-6">
                        <div class="p-4 bg-light rounded-4 shadow-sm">
                            <h5>Privilege Leave (PL)</h5>
                            <h3 class="text-primary"><?= $my_leave_balance['PL'] ?></h3>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="p-4 bg-light rounded-4 shadow-sm">
                            <h5>Sick Leave (SL)</h5>
                            <h3 class="text-primary"><?= $my_leave_balance['SL'] ?></h3>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- HR Balance Config (if admin) -->
        <?php if (in_array($user_role, ['admin','superadmin'])): ?>
        <div class="card mb-5">
            <div class="card-header"><h5><i class="fas fa-cog me-2"></i>Configure Employee Leave Balance</h5></div>
            <div class="card-body">
                <form method="POST" class="row g-3 align-items-end">
                    <input type="hidden" name="action" value="update_leave_balance">
                    <div class="col-md-5">
                        <select name="employee_id" class="form-select form-select-lg" required>
                            <option value="">Select Employee</option>
                            <?php foreach ($all_balances_rows as $emp): ?>
                            <option value="<?= $emp['id'] ?>" <?= $edit_emp_id == $emp['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($emp['username']) ?> (ID: <?= $emp['id'] ?>)
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <input type="number" name="pl_balance" class="form-control form-control-lg" placeholder="PL" value="<?= $edit_pl ?>" required>
                    </div>
                    <div class="col-md-2">
                        <input type="number" name="sl_balance" class="form-control form-control-lg" placeholder="SL" value="<?= $edit_sl ?>" required>
                    </div>
                    <div class="col-md-3">
                        <button type="submit" class="btn btn-primary btn-lg w-100">Save Balance</button>
                    </div>
                </form>
            </div>
        </div>
        <?php endif; ?>

        <!-- Tabs -->
        <div class="status-tabs">
            <div class="status-tab active" onclick="showTab('pending')">Pending Requests</div>
            <div class="status-tab" onclick="showTab('approved')">Approved</div>
            <div class="status-tab" onclick="showTab('rejected')">Rejected</div>
        </div>

        <!-- PENDING REQUESTS - NOW AT THE TOP -->
        <div id="pending-tab" class="tab-content active">
            <div class="card">
                <div class="card-header"><h5><i class="fas fa-clock me-2"></i>Pending Requests</h5></div>
                <div class="card-body">
                    <?php if (count($pending) > 0): ?>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead>
                                <tr>
                                    <th>Employee</th>
                                    <th>Type</th>
                                    <th>Date / Time</th>
                                    <th>Delegate To</th>
                                    <th>Work Description</th>
                                    <th>Reason</th>
                                    <th>Applied On</th>
                                    <?php if (in_array($user_role, ['admin','superadmin'])): ?><th>Actions</th><?php endif; ?>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($pending as $req): ?>
                                <tr>
                                    <td><strong><?= htmlspecialchars($req['username']) ?></strong></td>
                                    <td><span class="badge badge-pending"><?= htmlspecialchars($req['leave_type']) ?></span></td>
                                    <td>
                                        <?php if ($req['leave_type'] === 'Permission'): ?>
                                            <strong><?= date('M d, Y', strtotime($req['permission_date'])) ?></strong><br>
                                            <small><?= $req['permission_time_from'] ?> - <?= $req['permission_time_to'] ?> (<?= number_format($req['permission_hours'], 2) ?> hrs)</small>
                                        <?php else: ?>
                                            <?= date('M d', strtotime($req['start_date'])) ?> - <?= date('M d, Y', strtotime($req['end_date'])) ?>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= $req['delegate_to_name'] ? htmlspecialchars($req['delegate_to_name']) : '<em class="text-muted">None</em>' ?></td>
                                    <td><?= $req['work_description'] ? nl2br(htmlspecialchars(substr($req['work_description'], 0, 100))) . (strlen($req['work_description']) > 100 ? '...' : '') : '<em class="text-muted">None</em>' ?></td>
                                    <td><?= htmlspecialchars(substr($req['reason'], 0, 80)) ?><?= strlen($req['reason']) > 80 ? '...' : '' ?></td>
                                    <td><?= date('M d, Y', strtotime($req['applied_on'])) ?></td>
                                    <?php if (in_array($user_role, ['admin','superadmin'])): ?>
                                    <td>
                                        <a href="approve_leaves.php?id=<?= $req['id'] ?>&status=Approved" class="btn btn-success btn-sm">Approve</a>
                                        <a href="approve_leaves.php?id=<?= $req['id'] ?>&status=Rejected" class="btn btn-danger btn-sm">Reject</a>
                                    </td>
                                    <?php endif; ?>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php else: ?>
                    <p class="text-center text-muted py-5 fs-5">No pending requests at this time.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Approved -->
        <div id="approved-tab" class="tab-content">
            <div class="card">
                <div class="card-header"><h5><i class="fas fa-check-circle me-2"></i>Approved Requests</h5></div>
                <div class="card-body">
                    <?= renderRequestTable($approved) ?>
                </div>
            </div>
        </div>

        <!-- Rejected -->
        <div id="rejected-tab" class="tab-content">
            <div class="card">
                <div class="card-header"><h5><i class="fas fa-times-circle me-2"></i>Rejected Requests</h5></div>
                <div class="card-body">
                    <?= renderRequestTable($rejected) ?>
                </div>
            </div>
        </div>
    </div>

<?php
function renderRequestTable($requests) {
    if (count($requests) === 0) {
        return '<p class="text-center text-muted py-5 fs-5">No requests found.</p>';
    }
    ob_start(); ?>
    <div class="table-responsive">
        <table class="table table-hover align-middle">
            <thead>
                <tr>
                    <th>Employee</th>
                    <th>Type</th>
                    <th>Date / Time</th>
                    <th>Delegate To</th>
                    <th>Work Description</th>
                    <th>Reason</th>
                    <th>Applied On</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($requests as $req): ?>
                <tr>
                    <td><strong><?= htmlspecialchars($req['username']) ?></strong></td>
                    <td><span class="badge <?= $req['status'] === 'Approved' ? 'badge-approved' : 'badge-rejected' ?>"><?= htmlspecialchars($req['leave_type']) ?></span></td>
                    <td>
                        <?php if ($req['leave_type'] === 'Permission'): ?>
                            <strong><?= date('M d, Y', strtotime($req['permission_date'])) ?></strong><br>
                            <small><?= $req['permission_time_from'] ?> - <?= $req['permission_time_to'] ?></small>
                        <?php else: ?>
                            <?= date('M d', strtotime($req['start_date'])) ?> - <?= date('M d, Y', strtotime($req['end_date'])) ?>
                        <?php endif; ?>
                    </td>
                    <td><?= $req['delegate_to_name'] ? htmlspecialchars($req['delegate_to_name']) : '<em class="text-muted">None</em>' ?></td>
                    <td><?= $req['work_description'] ? nl2br(htmlspecialchars(substr($req['work_description'], 0, 100))) . '...' : '<em class="text-muted">None</em>' ?></td>
                    <td><?= htmlspecialchars(substr($req['reason'], 0, 80)) ?>...</td>
                    <td><?= date('M d, Y', strtotime($req['applied_on'])) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php return ob_get_clean();
}
?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('active');
            document.getElementById('content').classList.toggle('active');
        }

        function showTab(tab) {
            document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
            document.getElementById(tab + '-tab').classList.add('active');
            document.querySelectorAll('.status-tab').forEach(el => el.classList.remove('active'));
            event.target.classList.add('active');
        }
    </script>
</body>
</html>