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

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

$attendance_table = strtolower($dept) . '_employee_attendance';
$leave_table = '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]);

    // 🔒 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) {

    try {

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

    } catch (PDOException $e) {

        // 👇 Duplicate entry safe handle
        if ($e->getCode() == '23000') {
            // already inserted, ignore silently
            continue;
        }

        // koi aur DB error ho to throw
        throw $e;
    }
}

}


?>

<!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">
<link rel="stylesheet" href="assets/style.css">
<!-- Bootstrap & FontAwesome -->
<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>
/* ===== Animated Background ===== */

.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:mesh 30s ease-in-out infinite alternate;
  z-index:-6;
}
@keyframes mesh{0%{filter:hue-rotate(0)}100%{filter:hue-rotate(25deg)}}
.grid{
  position:fixed;inset:0;
  background:
    linear-gradient(rgba(255,255,255,.03) 1px, transparent 1px),
    linear-gradient(90deg, rgba(255,255,255,.03) 1px, transparent 1px);
  background-size:80px 80px;
  animation:grid 50s linear infinite;
  z-index:-5;
}
@keyframes grid{0%{background-position:0 0}100%{background-position:400px 400px}}

/* ===== Glass Panel ===== */
.glass-panel{
    max-width:1100px;
    margin:40px auto;
    padding:30px;
    background:rgba(255,255,255,.05);
    backdrop-filter:blur(20px);
    border-radius:20px;
    border:1px solid rgba(255,255,255,.12);
    box-shadow:0 12px 35px rgba(0,151,252,.3);
}
.logo{
    margin-right:10px;
}

/* Navbar */
.navbar-custom{
    background: linear-gradient(90deg,#0d1b2a,#1f2933);
    padding:14px 28px;
    border-radius:0;
    display:flex;
    align-items:center;
}
.navbar-custom .navbar-brand, .navbar-custom span{
    color:#fff;
    font-weight:600;
}
.navbar-brand
{
    display:flex;
    align-items:center;
    justify-content:space-evenly;

}
/* Cards */
.card{
    border:none;
    border-radius:18px;
    background: rgba(255,255,255,.05);
    backdrop-filter: blur(10px);
    color:#fff;
}
.shadow-soft{
    box-shadow:0 10px 25px rgba(0,0,0,0.15);
}

/* Stat Cards */
.stat-card{
    text-align:center;
    padding:25px;
    border-radius:18px;
    transition:.3s;
}
.stat-card:hover{
    transform:translateY(-5px);
}
.stat-card i{
    font-size:36px;
    margin-bottom:12px;
}
.stat-title{
    font-size:14px;
    color:#a0a0b0;
}
.stat-value{
    font-size:26px;
    font-weight:700;
    margin-top:4px;
}

/* Buttons */
.btn-rounded{
    border-radius:30px;
    padding:8px 20px;
    font-weight:600;
    transition:.3s;
}
.btn-rounded:hover{
    transform:translateY(-2px);
    box-shadow:0 0 20px rgba(255,138,0,.5);
}

/* Alerts */
.alert{
    border-radius:14px;
    font-size:14px;
}

/* Quick Actions */
.quick-actions a{
    display:flex;
    align-items:center;
    justify-content:center;
    gap:8px;
}
a{
    text-decoration:none;
}
</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">
    Jillion <span>Gamuts</span>
  </div>
        <i class="fa-solid fa-users-gear 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> Logout
        </a>
    </div>
</nav>

<div class="glass-panel">

    <!-- Welcome -->
    <div class="card shadow-soft mb-4 p-3">
        <h4 class="mb-1">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>
            You have not marked today's attendance
        </div>
        <form method="POST" action="mark_attendance.php">
            <button class="btn btn-success btn-rounded btn-sm">
                <i class="fa-solid fa-check"></i> Mark Now
            </button>
        </form>
    </div>
    <?php endif; ?>

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

    <!-- Leave Alerts -->
    <?php if($today_leave): ?>
        <?php if($today_leave['manager_quote'] && !$today_leave['employee_reply']): ?>
            <form method="POST" action="reply_manager.php" class="mb-4">
                <div class="alert alert-warning shadow-soft">
                    <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 to manager" required>
                    <button class="btn btn-primary btn-rounded mt-3">
                        <i class="fa-solid fa-paper-plane"></i> Send Reply
                    </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 for today is under review
            </div>
        <?php endif; ?>
    <?php endif; ?>

    <!-- Stats -->
    <div class="row g-4 mt-2">
        <a href="sales_add_project.php">
        <div class="col-md-3">
            <div class="stat-card shadow-soft">
                <i class="fa-solid fa-plus text-info"></i>
                <div class="stat-title mt-2">Add Project</div>
            </div>
        </div>
        </a>
        <a href="sent_to_designer.php">
        <div class="col-md-3">
            <div class="stat-card shadow-soft">
                <i class="fa-solid fa-paper-plane text-warning"></i>
                <div class="stat-title mt-2">Sent to Designer</div>
            </div>
        </div>
        </a>
        <a href="designer_files.php"><div class="col-md-3">
            <div class="stat-card shadow-soft">
                <i class="fa-solid fa-file-arrow-up text-primary"></i>
                <div class="stat-title mt-2">See Designer Files</div>
            </div>
        </div>
        </a>
        <a href="overall_projects.php">
        <div class="col-md-3">
            <div class="stat-card shadow-soft">
                <i class="fa-solid fa-check text-success"></i>
                <div class="stat-title mt-2">Completed Projects</div>
            </div>
        </div>
        </a>
        <div class="col-md-3">
            <div class="stat-card shadow-soft">
                <i class="fa-solid fa-wallet text-success"></i>
                <div class="stat-title mt-2">Salary</div>
                <div class="stat-value text-white">$0.00</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card shadow-soft">
                <i class="fa-solid fa-clock-rotate-left text-warning"></i>
                <div class="stat-title mt-2">Pending Approvals</div>
                <div class="stat-value text-white">0</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card shadow-soft">
                <i class="fa-solid fa-calendar-day text-danger"></i>
                <div class="stat-title mt-2">Attendance</div>
                <div class="stat-value text-white">0%</div>
            </div>
        </div>
    </div>

</div>

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