<?php
/* =============================================================================
 * File   : team_dashboard.php
 * Purpose: Modern mobile-first Team Dashboard with compact tiles (like screenshot)
 * Extras : Lightweight “AI Insight” (rule-based) that highlights what to act on
 * Stack  : Core PHP + MySQLi (NO PDO). DB in ../config.php
 * DB     : utf8mb4 / utf8mb4_general_ci
 * ============================================================================*/

date_default_timezone_set('Asia/Kolkata');
include('../config.php');

@session_start();
$user_id = isset($_SESSION['user_id1']) ? $_SESSION['user_id1'] : null;
if (!$user_id) { header('Location: index.php'); exit; }

/* Keep session alive */
$timeout = 60 * 60 * 24 * 365; $s_name = session_name();
if (isset($_COOKIE[$s_name])) { setcookie($s_name, $_COOKIE[$s_name], time() + $timeout, '/'); }

/* Charset/collation */
@mysqli_set_charset($conn, 'utf8mb4');
@mysqli_query($conn, "SET NAMES 'utf8mb4' COLLATE 'utf8mb4_general_ci'");
@mysqli_query($conn, "SET collation_connection='utf8mb4_general_ci'");

/* Helper */
if (!function_exists('h')) { function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); } }

/* Logged-in employee row */
$sqlMe = "SELECT * FROM hr_dump WHERE empid='".mysqli_real_escape_string($conn,(string)$user_id)."' LIMIT 1";
$resMe = mysqli_query($conn, $sqlMe);
$me    = $resMe ? mysqli_fetch_assoc($resMe) : null;
if (!$me) {
    echo "<!doctype html><html><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><title>Team Dashboard</title></head><body><p style='padding:24px;font:15px system-ui'>User not found in <code>hr_dump</code>.</p></body></html>";
    exit;
}
$myEmpNo = isset($me['Employee_Number']) ? (string)$me['Employee_Number'] : '';
$myEmpNoSafe = mysqli_real_escape_string($conn,$myEmpNo);

/* Counts */
$cntReporting = 0;
if ($r = mysqli_query($conn, "SELECT COUNT(*) c FROM hr_dump WHERE Functional_Reporting='$myEmpNoSafe' AND Status='Active'")) { $cntReporting = (int) (mysqli_fetch_assoc($r)['c'] ?? 0); }

$hasBHTeam = false;
if ($r = mysqli_query($conn, "SELECT bh_empid FROM hr_dump WHERE bh_empid='$myEmpNoSafe' LIMIT 1")) { $hasBHTeam = (bool) mysqli_fetch_assoc($r); }

$leavePending = $leaveApproved = $leaveRejected = 0;
$sqlLeaves = "
    SELECT 
      SUM(CASE WHEN Status IN ('Pending','PENDING','pending') THEN 1 ELSE 0 END) p,
      SUM(CASE WHEN Status IN ('Approved','APPROVED','approved') THEN 1 ELSE 0 END) a,
      SUM(CASE WHEN Status IN ('Rejected','REJECTED','rejected') THEN 1 ELSE 0 END) r
    FROM emp_leave
    WHERE Functional_Reporting='$myEmpNoSafe'
";
if ($r = mysqli_query($conn,$sqlLeaves)) {
    $row = mysqli_fetch_assoc($r);
    $leavePending  = (int)($row['p'] ?? 0);
    $leaveApproved = (int)($row['a'] ?? 0);
    $leaveRejected = (int)($row['r'] ?? 0);
}

$cntAllTeam = 0;
if ($r = mysqli_query($conn, "SELECT COUNT(*) c FROM hr_dump WHERE Status='Active' AND (Functional_Reporting='$myEmpNoSafe' OR bh_empid='$myEmpNoSafe')")) { $cntAllTeam = (int) (mysqli_fetch_assoc($r)['c'] ?? 0); }

/* ---------- “AI Insight” (simple rule-based) ---------- */
$insightIcon = 'fas fa-sparkles'; // fallback (Font Awesome may not have sparkles; will show square)
$insightText = "All clear. No pending actions.";
$insightTone = "ok";
if ($leavePending > 0) {
    $insightText = "You have $leavePending pending leave".($leavePending>1?'s':'')." to review today.";
    $insightTone = "warn";
} elseif ($cntReporting === 0) {
    $insightText = "No direct reports mapped. Verify reporting structure if this seems incorrect.";
    $insightTone = "info";
} elseif ($hasBHTeam) {
    $insightText = "Branch-head mapping detected. View BH team attendance for a wider picture.";
    $insightTone = "info";
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport"
          content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, viewport-fit=cover" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>Team Dashboard • IC AMS</title>

    <?php include('header.php'); ?>

    <style>
        :root{
            --bg:#f4f7ff;
            --card:#ffffff;
            --muted:#6b7280;
            --text:#0f172a;
            --ring:0 0 0 3px rgba(29,78,216,.25);
            --glass: rgba(255,255,255,.6);
            --soft: 0 12px 28px rgba(2,6,23,.06);
            --soft2: 0 16px 34px rgba(2,6,23,.08);
            --brand1:#3764d7;
            --brand2:#6ad3f7;
        }
        *{box-sizing:border-box; min-width:0;}
        html,body{height:100%;}
        body{
            margin:0;
            font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
            color:var(--text);
            background:
                radial-gradient(900px 600px at -10% -20%, #e7efff 0%, transparent 60%),
                radial-gradient(900px 600px at 110% 10%, #eefbff 0%, transparent 60%),
                var(--bg);
        }

        /* page pad with safe-area + bottom-nav clearance */
        #appCapsule{
            min-height:100dvh;
            padding: max(8px, env(safe-area-inset-top)) max(12px, env(safe-area-inset-right)) max(88px, env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left));
        }
        .wallet-card{
            background:var(--glass);
            backdrop-filter: blur(8px);
            -webkit-backdrop-filter: blur(8px);
            border:1px solid rgba(255,255,255,.45);
            border-radius:18px;
            box-shadow: var(--soft);
            overflow:hidden;
        }
        .inner-pad{ padding:12px; }

        /* Section title like screenshot */
        .section-label{
            font-size:11px; letter-spacing:.7px; font-weight:800; color:#8088a1;
            text-transform:uppercase; margin:8px 6px 8px;
            background:#fff;
            display:inline-block; padding:8px 12px; border-radius:12px;
            box-shadow: 0 6px 16px rgba(2,6,23,.06);
        }

        /* AI INSIGHT pill */
        .ai-pill{
            display:flex; align-items:flex-start; gap:10px;
            background: #f8fbff; border:1px dashed #cfe3ff; color:#1e3a8a;
            padding:10px 12px; border-radius:14px; margin:8px 6px 12px;
            box-shadow: var(--soft);
        }
        .ai-pill.warn{ background:#fff7ed; border-color:#fed7aa; color:#9a3412; }
        .ai-pill.ok{ background:#f0fdf4; border-color:#bbf7d0; color:#065f46; }
        .ai-pill .icon{
            width:32px; height:32px; border-radius:10px; display:flex; align-items:center; justify-content:center;
            background: linear-gradient(135deg, var(--brand1), var(--brand2)); color:#fff;
            box-shadow: inset 0 0 0 1px rgba(255,255,255,.25);
            flex-shrink:0;
        }
        .ai-pill .txt{ font-size:13px; line-height:1.35; font-weight:600; }

        /* Compact tiles exactly like screenshot — 3 per row on phones */
        .tiles{ display:grid; gap:10px; grid-template-columns: repeat(3, minmax(0,1fr)); padding: 6px; }
        /* If the screen is very narrow <340px, fall back to 2 */
        @media (max-width: 340px){ .tiles{ grid-template-columns: repeat(2, minmax(0,1fr)); } }
        .tile{
            background: var(--card);
            border:1px solid #eef2ff;
            border-radius:16px;
            box-shadow: var(--soft);
            padding:10px 8px;
            text-align:center;
            text-decoration:none;
            color:inherit;
            display:flex; flex-direction:column; align-items:center; justify-content:center;
            min-height: 96px;
            transition: transform .12s ease, box-shadow .12s ease, border-color .12s ease;
        }
        .tile:hover{ transform: translateY(-2px); box-shadow: var(--soft2); border-color:#e5e7eb; }
        .tile:focus-visible{ outline:none; box-shadow: var(--soft2), var(--ring); }

        .tile .ico{
            width:44px; height:44px; border-radius:12px; display:flex; align-items:center; justify-content:center;
            margin-bottom:6px;
            background: linear-gradient(135deg, #5b8def, #6ee7f9);
            color:#fff; box-shadow: inset 0 0 0 1px rgba(255,255,255,.25);
            font-size:18px;
        }
        .tile .ico.blue{ background: linear-gradient(135deg, #5b8def, #6ee7f9); }
        .tile .ico.green{ background: linear-gradient(135deg, #22c55e, #86efac); }
        .tile .ico.red{ background: linear-gradient(135deg, #ef4444, #fecaca); }
        .tile .ico.navy{ background: linear-gradient(135deg, #3b82f6, #93c5fd); }

        .tile .label{ font-weight:800; font-size:12.5px; color:#0b1224; line-height:1.2; }
        .tile .badge{
            display:inline-block; margin-top:6px;
            min-width:22px; padding: 2px 6px; font-weight:800; font-size:11px;
            border-radius:999px; border:1px solid #e5e7eb; background:#f8fafc; color:#334155;
        }
        .badge.ok    { background:#ecfdf5; border-color:#bbf7d0; color:#065f46; }
        .badge.danger{ background:#fef2f2; border-color:#fecaca; color:#991b1b; }

        /* Two white panels like screenshot */
        .panel{
            background:#ffffff; border:1px solid #eef2ff; border-radius:16px;
            margin: 8px 6px 14px; box-shadow: var(--soft);
        }

        /* Small text wrapping */
        .label span{ display:block; }

        /* Footer spacing is handled by #appCapsule bottom pad */
        img{ max-width:100%; height:auto; }
    </style>
</head>
<body>

<div id="appCapsule">
    <div class="wallet-card">
        <div class="inner-pad">
            <?php include('include/wallet-balance.php'); ?>

            <!-- AI INSIGHT -->
            <div class="ai-pill <?php echo h($insightTone); ?>" role="status" aria-live="polite">
                <div class="icon"><i class="fas fa-robot" aria-hidden="true"></i></div>
                <div class="txt"><?php echo h($insightText); ?></div>
            </div>

            <!-- TEAM LEAVES -->
            <div class="panel">
                <div class="section-label">Team Leaves</div>
                <div class="tiles">
                    <a class="tile" href="team-leave-pending.php" aria-label="Pending Leave">
                        <div class="ico blue"><i class="fas fa-hourglass-half" aria-hidden="true"></i></div>
                        <div class="label"><span>Pending</span><span>Leave</span></div>
                        <span class="badge"><?php echo (int)$leavePending; ?></span>
                    </a>
                    <a class="tile" href="team-leave-approved.php" aria-label="Approved Leave">
                        <div class="ico green"><i class="fas fa-check" aria-hidden="true"></i></div>
                        <div class="label"><span>Approved</span><span>Leave</span></div>
                        <span class="badge ok"><?php echo (int)$leaveApproved; ?></span>
                    </a>
                    <a class="tile" href="team-leave-rejected.php" aria-label="Rejected Leave">
                        <div class="ico red"><i class="fas fa-times" aria-hidden="true"></i></div>
                        <div class="label"><span>Rejected</span><span>Leave</span></div>
                        <span class="badge danger"><?php echo (int)$leaveRejected; ?></span>
                    </a>
                </div>
            </div>

            <!-- TEAM ATTENDANCE -->
            <div class="panel">
                <div class="section-label">Team Attendance</div>
                <div class="tiles">
                    <a class="tile" href="team-dr.php" aria-label="Reporting Team">
                        <div class="ico navy"><i class="fas fa-users" aria-hidden="true"></i></div>
                        <div class="label"><span>Reporting</span><span>Team</span></div>
                        <span class="badge"><?php echo (int)$cntReporting; ?></span>
                    </a>
                    <a class="tile" href="team-dr-all.php" aria-label="All Team">
                        <div class="ico navy"><i class="fas fa-users-cog" aria-hidden="true"></i></div>
                        <div class="label"><span>All</span><span>Team</span></div>
                        <span class="badge"><?php echo (int)$cntAllTeam; ?></span>
                    </a>
                    <?php if ($hasBHTeam): ?>
                        <a class="tile" href="team-dr-bh-all.php" aria-label="Branch Head Team">
                            <div class="ico blue"><i class="fas fa-sitemap" aria-hidden="true"></i></div>
                            <div class="label"><span>Branch</span><span>Head Team</span></div>
                        </a>
                    <?php else: ?>
                        <div class="tile" style="opacity:.35; pointer-events:none;">
                            <div class="ico blue"><i class="fas fa-sitemap" aria-hidden="true"></i></div>
                            <div class="label"><span>Branch</span><span>Head Team</span></div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

        </div>
    </div>

    <?php include('include/copyright.php'); ?>
</div>

<?php include('footer.php'); ?>
</body>
</html>
