<?php
session_start();
require 'config/db.php';

if (!isset($_SESSION['manager_id'])) {
    die('Unauthorized');
}

$dept = 'Design';
$dept = strtolower($_SESSION['department']);
$dept = preg_replace('/[^a-z0-9_]/','',$dept);


// Fetch Pending Leaves (Manager action required)
$pending_stmt = $pdo->prepare("
    SELECT r.*, e.full_name
    FROM design_employee_leave_requests r
    JOIN {$dept}_employees e ON r.employee_id = e.id
    WHERE r.status = 'Pending'
    ORDER BY r.created_at ASC
");
$pending_stmt->execute();
$pending_requests = $pending_stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch Manager Approved Leaves (HR action pending)
$hr_pending_stmt = $pdo->prepare("
    SELECT r.*, e.full_name
    FROM design_employee_leave_requests r
    JOIN {$dept}_employees e ON r.employee_id = e.id
    WHERE r.status = 'ManagerApproved'
    ORDER BY r.leave_date ASC
");
$hr_pending_stmt->execute();
$hr_pending_requests = $hr_pending_stmt->fetchAll(PDO::FETCH_ASSOC);

$hr_approve_stmt = $pdo->prepare("
    SELECT r.*, e.full_name
    FROM design_employee_leave_requests r
    JOIN {$dept}_employees e ON r.employee_id = e.id
    WHERE r.status = 'HRApproved'
    ORDER BY r.leave_date ASC
");
$hr_approve_stmt->execute();
$hr_approve_requests = $hr_approve_stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch Rejected Leaves
$rejected_stmt = $pdo->prepare("
    SELECT r.*, e.full_name
    FROM design_employee_leave_requests r
    JOIN {$dept}_employees e ON r.employee_id = e.id
    WHERE r.status = 'Rejected'
    ORDER BY r.leave_date DESC
");
$rejected_stmt->execute();
$rejected_requests = $rejected_stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?= htmlspecialchars($dept) ?> Manager – Leave Requests</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
body{
    background:#f1f5f9;
}

/* Glass container */
.glass-container{
    padding:30px;
}

/* Glass card */
.glass-card{
    background:rgba(255,255,255,.65);
    backdrop-filter: blur(14px);
    -webkit-backdrop-filter: blur(14px);
    border-radius:16px;
    padding:18px;
    margin-bottom:18px;
    box-shadow:0 10px 25px rgba(0,0,0,.08);
    border:1px solid rgba(255,255,255,.35);
}

/* Rejected highlight */
.glass-danger{
    border-left:5px solid #dc3545;
}

/* Tabs glass look */
.nav-tabs{
    border-bottom:none;
    margin-bottom:20px;
}

.nav-tabs .nav-link{
    border:none;
    color:#475569;
    font-weight:600;
    border-radius:10px;
    padding:8px 16px;
    margin-right:6px;
    background:rgba(255,255,255,.55);
}

.nav-tabs .nav-link.active{
    background:#2563eb;
    color:#fff;
}

/* Chat box */
.chat-box{
    background:rgba(255,255,255,.75);
    border-radius:10px;
    border:1px solid rgba(0,0,0,.05);
    padding:6px 8px;
    max-height:180px;
    overflow-y:auto;
    font-size:14px;
}

.chat-employee{ color:#0d6efd; margin-bottom:3px; }
.chat-manager{ color:#dc3545; margin-bottom:3px; }

/* Small buttons */
.btn-sm{
    border-radius:8px;
}
</style>
</head>
<body>

<?php include 'assets/layout_top.php'; ?>
<br><br><br>
<div class="container glass-container">

<!-- Tabs -->
<ul class="nav nav-tabs mb-3" id="leaveTab" role="tablist">
  <li class="nav-item">
    <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#pending">Pending</button>
  </li>
  <li class="nav-item">
    <button class="nav-link" data-bs-toggle="tab" data-bs-target="#hr">HR Pending</button>
  </li>
  <li class="nav-item">
    <button class="nav-link" data-bs-toggle="tab" data-bs-target="#approve">Approved</button>
  </li>
  <li class="nav-item">
    <button class="nav-link text-danger" data-bs-toggle="tab" data-bs-target="#rejected">Rejected</button>
  </li>
</ul>

<div class="tab-content">

<!-- PENDING TAB -->
<div class="tab-pane fade show active" id="pending" role="tabpanel">
<?php if(!$pending_requests): ?>
    <div class="alert alert-info">No pending leave requests for your approval.</div>
<?php else: ?>
<?php foreach($pending_requests as $r): ?>
<div class="glass-card">
    <h5><?= htmlspecialchars($r['full_name']) ?></h5>
    <p class="text-white mb-1">Leave Date: <strong><?= htmlspecialchars($r['leave_date']) ?></strong></p>

    <div class="alert alert-secondary p-2 mb-2">
        <strong>Reason:</strong><br>
        <?= htmlspecialchars($r['reason']) ?>
    </div>

    <!-- Conversation -->
    <div class="chat-box mb-2">
    <?php
    $msgs = $pdo->prepare("SELECT * FROM design_leave_messages WHERE leave_id=? ORDER BY created_at ASC");
    $msgs->execute([$r['id']]);

    if($msgs->rowCount()==0){
        echo '<span class="text-white">No conversation yet.</span>';
    } else {
        foreach($msgs as $m){
            $cls = $m['sender']=='Manager' ? 'chat-manager' : 'chat-employee';
            echo "<div class='$cls'><b>{$m['sender']}:</b> ".htmlspecialchars($m['message'])."</div>";
        }
    }
    ?>
    </div>

    <!-- Ask Question -->
    <form method="POST" action="send_message.php" class="d-flex gap-2 mb-2">
        <input type="hidden" name="leave_id" value="<?= $r['id'] ?>">
        <input type="text" name="message" class="form-control form-control-sm"
               maxlength="25" placeholder="Ask (max 25 chars)" required>
        <button class="btn btn-warning btn-sm">Send</button>
    </form>

    <!-- Approve + Reject -->
    <div class="d-flex gap-2">
        <form method="POST" action="approve_leave.php"
              onsubmit="return confirm('Approve this leave and send to HR?')">
            <input type="hidden" name="id" value="<?= $r['id'] ?>">
            <button class="btn btn-success btn-sm">Approve</button>
        </form>

        <form method="POST" action="reject_leave.php"
              onsubmit="return confirm('Reject this leave request?')">
            <input type="hidden" name="id" value="<?= $r['id'] ?>">
            <button class="btn btn-danger btn-sm">Reject</button>
        </form>
    </div>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>

<!-- HR PENDING TAB -->
<div class="tab-pane fade" id="hr" role="tabpanel">
<?php if(!$hr_pending_requests): ?>
    <div class="alert alert-info">No leaves approved by you pending HR finalization.</div>
<?php else: ?>
    <?php foreach($hr_pending_requests as $r): ?>
    <div class="glass-card">
        <h5><?= htmlspecialchars($r['full_name']) ?></h5>
        <p class="text-white mb-1">Leave Date: <strong><?= htmlspecialchars($r['leave_date']) ?></strong></p>
        <div class="alert alert-secondary p-2 mb-2"><strong>Reason:</strong><br><?= htmlspecialchars($r['reason']) ?></div>

        <!-- Conversation -->
        <div class="chat-box mb-2">
        <?php
        $msgs = $pdo->prepare("SELECT * FROM design_leave_messages WHERE leave_id=? ORDER BY created_at ASC");
        $msgs->execute([$r['id']]);
        if($msgs->rowCount()==0){ echo '<span class="text-white">No conversation yet.</span>'; }
        else{
            foreach($msgs as $m){
                $cls = $m['sender']=='Manager'?'chat-manager':'chat-employee';
                echo "<div class='$cls'><b>{$m['sender']}:</b> ".htmlspecialchars($m['message'])."</div>";
            }
        }
        ?>
        </div>
    </div>
    <?php endforeach; ?>
<?php endif; ?>
</div>

<!-- APPROVED TAB -->
<div class="tab-pane fade" id="approve" role="tabpanel">
<?php if(!$hr_approve_requests): ?>
    <div class="alert alert-info">No approved leaves yet.</div>
<?php else: ?>
    <?php foreach($hr_approve_requests as $r): ?>
    <div class="glass-card">
        <h5><?= htmlspecialchars($r['full_name']) ?></h5>
        <p class="text-muted mb-1">Leave Date: <strong><?= htmlspecialchars($r['leave_date']) ?></strong></p>
        <div class="alert alert-secondary p-2 mb-2"><strong>Reason:</strong><br><?= htmlspecialchars($r['reason']) ?></div>

        <!-- Conversation -->
        <div class="chat-box mb-2">
        <?php
        $msgs = $pdo->prepare("SELECT * FROM design_leave_messages WHERE leave_id=? ORDER BY created_at ASC");
        $msgs->execute([$r['id']]);
        if($msgs->rowCount()==0){ echo '<span class="text-muted">No conversation yet.</span>'; }
        else{
            foreach($msgs as $m){
                $cls = $m['sender']=='Manager'?'chat-manager':'chat-employee';
                echo "<div class='$cls'><b>{$m['sender']}:</b> ".htmlspecialchars($m['message'])."</div>";
            }
        }
        ?>
        </div>
    </div>
    <?php endforeach; ?>
<?php endif; ?>
</div>

<!-- REJECTED TAB -->
<div class="tab-pane fade" id="rejected" role="tabpanel">
<?php if(!$rejected_requests): ?>
    <div class="alert alert-info">No rejected leave requests.</div>
<?php else: ?>
    <?php foreach($rejected_requests as $r): ?>
    <div class="glass-card glass-danger">
        <h5><?= htmlspecialchars($r['full_name']) ?></h5>
        <p class="text-white mb-1">Leave Date: <strong><?= htmlspecialchars($r['leave_date']) ?></strong></p>
        <span class="badge bg-danger mb-2">Rejected</span>
        <div class="alert alert-secondary p-2 mb-2"><strong>Reason:</strong><br><?= htmlspecialchars($r['reason']) ?></div>

        <!-- Conversation -->
        <div class="chat-box">
        <?php
        $msgs = $pdo->prepare("SELECT * FROM design_leave_messages WHERE leave_id=? ORDER BY created_at ASC");
        $msgs->execute([$r['id']]);
        if($msgs->rowCount()==0){ echo '<span class="text-white">No conversation.</span>'; }
        else{
            foreach($msgs as $m){
                $cls = $m['sender']=='Manager'?'chat-manager':'chat-employee';
                echo "<div class='$cls'><b>{$m['sender']}:</b> ".htmlspecialchars($m['message'])."</div>";
            }
        }
        ?>
        </div>
    </div>
    <?php endforeach; ?>
<?php endif; ?>
</div>

</div>

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

<?php include 'assets/layout_bottom.php'; ?>
