<?php

require 'config/db.php';
session_start();
if (!isset($_SESSION['employee_id'])) die('Unauthorized');

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

$today = date('Y-m-d');

$attendance_table = strtolower($dept) . '_employee_attendance';
$leave_table = 'design_employee_leave_requests';

// Check if attendance is marked today
$att_stmt = $pdo->prepare("SELECT * FROM $attendance_table WHERE employee_id=? AND att_date=?");
$att_stmt->execute([$emp_id, $today]);
$today_att = $att_stmt->fetch();

// Check if leave request exists today
$leave_stmt = $pdo->prepare("
    SELECT * 
    FROM $leave_table 
    WHERE employee_id=? AND leave_date=? 
      AND status IN ('Pending','ManagerApproved')
");
$leave_stmt->execute([$emp_id, $today]);
$today_leave = $leave_stmt->fetch();
$loginTable = $dept.'_employees_login_logs';
$lateTable  = $dept.'_employee_late_log';
$entryTable = $dept.'_employee_entry_times';

$today = date('Y-m-d');

$logs = $pdo->prepare("
    SELECT employee_id, login_time, login_date
    FROM $loginTable
    WHERE login_date=?
");
$logs->execute([$today]);

foreach($logs as $log){

    $emp        = $log['employee_id'];
    $loginDate  = $log['login_date'];
    $loginTime  = strtotime($log['login_time']);

    // 🔍 DATE-WISE custom entry time
    $et = $pdo->prepare("
        SELECT entry_time
        FROM $entryTable
        WHERE department=? 
          AND employee_id=? 
          AND entry_date=?
        LIMIT 1
    ");
    $et->execute([$dept, $emp, $loginDate]);
    $row = $et->fetch();

    // ⏰ Entry time
    if ($row) {
        $entryTime = strtotime($row['entry_time']);
    } else {
        // Default office timing
        $entryTime = strtotime('22:00:00');
    }

    // 🕒 Grace logic
    $graceStart = strtotime('-30 minutes', $entryTime);
    $lateStart  = strtotime('+15 minutes', $entryTime);

    // ❌ Ignore very early login
    if ($loginTime < $graceStart) continue;

    // ✅ Status
    $status = ($loginTime <= $lateStart) ? 'OnTime' : 'Late';

    // 🔒 Prevent duplicate for same date
    $chk = $pdo->prepare("
        SELECT id FROM $lateTable
        WHERE employee_id=? AND log_date=?
    ");
    $chk->execute([$emp, $loginDate]);

    if ($chk->rowCount() == 0) {
        $pdo->prepare("
            INSERT INTO $lateTable
            (employee_id, log_date, status, login_time)
            VALUES (?,?,?,?)
        ")->execute([
            $emp,
            $loginDate,
            $status,
            date('H:i:s', $loginTime)
        ]);
    }
}



?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="icon" type="image/png" href="images/jg.webp">
<title>JG - Suite</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<!-- Bootstrap + Icons -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet">

<style>
/* ===== Background ===== */
body{
    margin:0;
    font-family: "Segoe UI", Arial, sans-serif;
    background: linear-gradient(135deg,#050814,#0b0f1a);
    color:#fff;
    min-height:100vh;
}
.mesh{
    position:fixed; inset:0;
    background:
        radial-gradient(circle at 15% 20%, rgba(31,140,255,.25), transparent 45%),
        radial-gradient(circle at 80% 25%, rgba(255,138,0,.25), transparent 45%),
        linear-gradient(180deg,#03040a,#070b18);
    animation: hue 30s linear infinite;
    z-index:-5;
}
@keyframes hue{100%{filter:hue-rotate(30deg)}}

/* ===== Navbar ===== */
.navbar-custom{
    background:linear-gradient(90deg,#0b1220,#111827);
    padding:14px 28px;
}
.navbar-custom span,.navbar-custom .navbar-brand{color:#fff;font-weight:600}
.navbar-brand{
    display:flex;
    align-items:center;
}
.logo{
    margin-right:10px;
}
/* ===== Glass Container ===== */
.glass{
    max-width:1200px;
    margin:35px auto;
    padding:30px;
    background:rgba(255,255,255,.06);
    backdrop-filter:blur(18px);
    border-radius:20px;
    border:1px solid rgba(255,255,255,.12);
    box-shadow:0 20px 45px rgba(0,0,0,.45);
}

/* ===== Cards ===== */
.card{
    background:rgba(255,255,255,.07);
    border:none;
    border-radius:18px;
    color:#fff;
    z-index: 10;
}
.shadow-soft{box-shadow:0 10px 30px rgba(0,0,0,.35)}

.grid{
  position:fixed; inset:0;
  background:
    linear-gradient(rgba(255,255,255,.04) 1px, transparent 1px),
    linear-gradient(90deg, rgba(255,255,255,.04) 1px, transparent 1px);
  background-size:70px 70px;
  animation:grid 50s linear infinite;
  z-index:-1;
}
#particles{position:fixed;inset:0;z-index:0}
@keyframes grid{to{transform:translateY(70px)}}

/* ===== Stat Cards ===== */
.stat-card{
    padding:24px;
    text-align:center;
    transition:.35s;
    z-index: ;
}
.logo{display:flex;align-items:center;gap:10px;font-weight:600; color:white;}
.logo img{height:46px}
.logo span{color:var(--blue)}
.stat-card:hover{transform:translateY(-6px)}
.stat-card i{font-size:36px;margin-bottom:12px}
.stat-title{font-size:14px;color:#b0b3c6}
.stat-value{font-size:26px;font-weight:700}

/* ===== Buttons ===== */
.btn-rounded{
    border-radius:30px;
    padding:9px 20px;
    font-weight:600;
}
.btn-glow:hover{
    box-shadow:0 0 20px rgba(255,138,0,.6);
    transform:translateY(-2px);
}

/* Alerts */
.alert{border-radius:14px}
</style>
</head>

<body>
<div class="mesh"></div>
<div class="grid"></div>
<canvas id="particles"></canvas>

<!-- NAVBAR -->
<nav class="navbar navbar-custom d-flex justify-content-between">
    <div class="navbar-brand">
         <div class="logo">
    <img src="images/jg.webp" alt="JG">JG<span>Suite</span>
  </div>
        <i class="fa-solid fa-palette me-2"></i>
        <?= htmlspecialchars($_SESSION['department']) ?> Dashboard
    </div>
    <div>
        <span class="me-3">
            <i class="fa-solid fa-user"></i>
            <?= htmlspecialchars($_SESSION['employee_name']) ?>
        </span>
        <a href="logout.php" class="btn btn-danger btn-sm btn-rounded">
            <i class="fa-solid fa-right-from-bracket"></i>
        </a>
    </div>
</nav>

<div class="glass">

<!-- Welcome -->
<div class="card shadow-soft mb-4 p-3">
    <h4>Welcome, <?= htmlspecialchars($_SESSION['employee_name']) ?> 👋</h4>
    <p class="text-white mb-0">
        Department: <?= htmlspecialchars($_SESSION['department']) ?>
    </p>
</div>

<!-- Attendance Alert -->
<?php if(!$today_att): ?>
<div class="alert alert-warning d-flex justify-content-between align-items-center shadow-soft mb-4">
    <div>
        <i class="fa-solid fa-triangle-exclamation me-2"></i>
        Attendance not marked today
    </div>
    <form method="POST" action="mark_attendance.php">
        <button class="btn btn-success btn-rounded btn-sm btn-glow">
            <i class="fa-solid fa-check"></i> Mark Now
        </button>
    </form>
</div>
<?php endif; ?>

<!-- Quick Actions -->
<div class="d-flex flex-wrap gap-3 mb-4">
    <a href="my_attendance.php" class="btn btn-outline-primary btn-rounded btn-glow">
        <i class="fa-solid fa-calendar-check"></i> My Attendance
    </a>
    <a href="my_leaves.php" class="btn btn-outline-info btn-rounded btn-glow">
        <i class="fa-solid fa-file-lines"></i> My Leaves
    </a>
    <a href="request_attendance.php" class="btn btn-outline-warning btn-rounded btn-glow">
        <i class="fa-solid fa-clock"></i> Request Missing Attendance
    </a>
</div>

<!-- Leave Alert -->
<?php if($today_leave): ?>
    <?php if($today_leave['manager_quote'] && !$today_leave['employee_reply']): ?>
        <form method="POST" action="reply_manager.php">
            <div class="alert alert-warning shadow-soft mb-4">
                <strong><i class="fa-solid fa-user-tie"></i> Manager:</strong>
                <?= htmlspecialchars($today_leave['manager_quote']) ?>
                <input type="hidden" name="id" value="<?= $today_leave['id'] ?>">
                <input type="text" name="reply" class="form-control mt-3"
                       maxlength="25" placeholder="Reply (max 25 chars)" required>
                <button class="btn btn-primary btn-rounded btn-glow mt-3">
                    <i class="fa-solid fa-paper-plane"></i> Send
                </button>
            </div>
        </form>
    <?php else: ?>
        <div class="alert alert-info shadow-soft mb-4">
            <i class="fa-solid fa-hourglass-half me-2"></i>
            Leave request under review
        </div>
    <?php endif; ?>
<?php else: ?>
    <a href="request_leave.php" class="btn btn-info btn-rounded btn-glow mb-4">
        <i class="fa-solid fa-plus"></i> Request Leave
    </a>
<?php endif; ?>

<!-- Stats + Actions -->
<div class="row g-4 mt-2">

<div class="col-md-3">
    <div class="stat-card card shadow-soft">
        <i class="fa-solid fa-layer-group text-info"></i>
        <div class="stat-title">New Projects</div>
        <a href="projects.php" class="btn btn-sm btn-outline-info btn-rounded mt-2">Open</a>
    </div>
</div>

<div class="col-md-3">
    <div class="stat-card card shadow-soft">
        <i class="fa-solid fa-rotate text-warning"></i>
        <div class="stat-title">Revision Projects</div>
        <a href="revision_requests.php" class="btn btn-sm btn-outline-warning btn-rounded mt-2">View</a>
    </div>
</div>

<div class="col-md-3">
    <div class="stat-card card shadow-soft">
        <i class="fa-solid fa-cloud-arrow-up text-primary"></i>
        <div class="stat-title">Upload Final Files</div>
        <a href="final_files.php" class="btn btn-sm btn-outline-primary btn-rounded mt-2">Upload</a>
    </div>
</div>

<div class="col-md-3">
    <div class="stat-card card shadow-soft">
        <i class="fa-solid fa-circle-check text-success"></i>
        <div class="stat-title">Completed Projects</div>
        <a href="overall_projects.php" class="btn btn-sm btn-outline-success btn-rounded mt-2">View</a>
    </div>
</div>

<div class="col-md-4">
    <div class="stat-card card shadow-soft">
        <i class="fa-solid fa-wallet text-success"></i>
        <div class="stat-title">Salary</div>
        <div class="stat-value">$0.00</div>
    </div>
</div>

<div class="col-md-4">
    <div class="stat-card card shadow-soft">
        <i class="fa-solid fa-clock-rotate-left text-warning"></i>
        <div class="stat-title">Pending Approvals</div>
        <div class="stat-value">0</div>
    </div>
</div>

<div class="col-md-4">
    <div class="stat-card card shadow-soft">
        <i class="fa-solid fa-calendar-day text-danger"></i>
        <div class="stat-title">Attendance</div>
        <div class="stat-value">0%</div>
    </div>
</div>

</div>
</div>
<script src="assets/particles.js"></script>
</body>
</html>
