<?php
/* -----------------------------------------------------------------------------
 * IC AMS • Leave Dashboard (PHP + MySQLi, NO PDO)
 * - DB connection in ../config.php
 * - Collation enforced: utf8mb4_general_ci
 * - Fixes:
 *   1) Guard null array offsets for CL/SL/PL balances (removed warnings).
 *   2) Replaced non-existent column 'Functional_Reporting_Status' from POW query.
 *   3) Cleaned unused/duplicated queries; safe defaults when data is missing.
 * ---------------------------------------------------------------------------*/
date_default_timezone_set('Asia/Kolkata');
include('../config.php');
@mysqli_set_charset($conn, 'utf8mb4');
@mysqli_query($conn, "SET NAMES 'utf8mb4' COLLATE 'utf8mb4_general_ci'");
@mysqli_query($conn, "SET collation_connection='utf8mb4_general_ci'");

@session_start();
@$user_id1   = $_SESSION['user_id1'];
@$idvfied1   = $_SESSION['idverified1'];
@$namevfied1 = $_SESSION['namevfied1'];
if (!isset($_SESSION['user_id1'])) {
    header("Location: index.php");
    exit;
}

/* Persist session cookie for long-lived login */
$timeout = 60 * 60 * 24 * 365;
$s_name  = session_name();
if (isset($_COOKIE[$s_name])) {
    setcookie($s_name, $_COOKIE[$s_name], time() + $timeout, '/');
}

/* ---- Helpers ---- */
if (!function_exists('h')) { function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); } }
function num($v, $def = 0){ return is_numeric($v) ? (int)$v : (int)$def; }

/* ---- Current user basics ---- */
$fetch1 = null;
$sel1   = mysqli_query($conn, "SELECT * FROM hr_dump WHERE empid='" . mysqli_real_escape_string($conn, (string)@$user_id1) . "' LIMIT 1");
if ($sel1) { $fetch1 = mysqli_fetch_assoc($sel1); }

/* ---- Leave balance (IC) ---- */
$dataIClv = ['CL'=>0, 'SL'=>0, 'PL'=>0]; // safe defaults
$IClvSql  = "SELECT * FROM ic_leave_balance WHERE empid='" . mysqli_real_escape_string($conn, (string)@$user_id1) . "' LIMIT 1";
$IClv     = mysqli_query($conn, $IClvSql);
if ($IClv) {
    $row = mysqli_fetch_assoc($IClv);
    if ($row) {
        // Some setups use EL (Earned Leave) instead of PL. Map gracefully.
        $dataIClv['CL'] = num($row['CL'] ?? 0);
        $dataIClv['SL'] = num($row['SL'] ?? 0);
        $dataIClv['PL'] = num($row['PL'] ?? ($row['EL'] ?? 0));
    }
}

/* ---- MIS count this month ---- */
$currYear  = date("Y");
$currMonth = date("Y-m");
$misCount  = 0;
$misSql    = "SELECT COUNT(*) AS total 
              FROM emp_leave 
              WHERE empid='" . mysqli_real_escape_string($conn, (string)@$user_id1) . "'
                AND LeaveCategory='MIS-P'
                AND created_at LIKE '" . mysqli_real_escape_string($conn, $currMonth) . "%'";
$misRes = mysqli_query($conn, $misSql);
if ($misRes) {
    $misRow   = mysqli_fetch_assoc($misRes);
    $misCount = num($misRow['total'] ?? 0);
}

/* ---- COFF (POW) availability ----
 * Removed non-existent column 'Functional_Reporting_Status'.
 * We treat an approved POW credit as available COFF.
 */
$coffAvailable = false;
$coffSql = "SELECT 1 
            FROM pow 
            WHERE empid='" . mysqli_real_escape_string($conn, (string)@$user_id1) . "'
              AND Status='POW'
              AND Admin_Status='Approved'
            LIMIT 1";
$coffRes = mysqli_query($conn, $coffSql);
if ($coffRes && mysqli_fetch_assoc($coffRes)) {
    $coffAvailable = true;
}

/* (Optional) Birthday/Marriage checks (kept if needed later, not used in UI) */
$BMresult = mysqli_query($conn, "SELECT id FROM emp_leave WHERE empid='" . mysqli_real_escape_string($conn, (string)@$user_id1) . "' AND LeaveCategory='BDY' AND DateFrom LIKE '" . mysqli_real_escape_string($conn, $currYear) . "%' LIMIT 1");
$MRGresult = mysqli_query($conn, "SELECT id FROM emp_leave WHERE empid='" . mysqli_real_escape_string($conn, (string)@$user_id1) . "' AND LeaveCategory='MRG' AND DateFrom LIKE '" . mysqli_real_escape_string($conn, $currYear) . "%' LIMIT 1");
?>
<!doctype html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; 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>Dashboard IC AMS</title>
</head>
<body>
<?php include('header.php'); ?>

<div id="appCapsule">
    <div class="section wallet-card-section pt-1 mb-4">
        <div class="wallet-card">

            <?php include('include/wallet-balance.php'); ?>

            <div class="row text-center">
                <div class="wallet-footer"><h6 class="text-center">Leave Dashboard</h6></div>

                <div class="col-sm-6 mt-1">
                    <div class="row">
                        <div class="col-4">
                            <a href="leave-request-mis.php">
                                <div class="icon-wrapper leave-active"><i class="fas fa-user-clock"></i></div>
                                <?php
                                // If 2 or more MIS already taken this month, mark as NA
                                if ($misCount >= 2) {
                                    echo "<b class='pstrong text-danger'>MIS(NA)</b>";
                                } else {
                                    echo '<b class="pstrong">MIS Taken (' . $misCount . ')</b>';
                                }
                                ?>
                            </a>
                        </div>

                        <div class="col-4">
                            <a href="leave-request-cl.php">
                                <div class="icon-wrapper"><i class="fas fa-business-time"></i></div>
                                <?php
                                if ($dataIClv['CL'] <= 0) {
                                    echo "<b class='pstrong text-danger'>CL(NA)</b>";
                                } else {
                                    echo '<b class="pstrong">CL (' . $dataIClv['CL'] . ')</b>';
                                }
                                ?>
                            </a>
                        </div>

                        <div class="col-4">
                            <a href="leave-request-sl.php">
                                <div class="icon-wrapper"><i class="fas fa-procedures"></i></div>
                                <?php
                                if ($dataIClv['SL'] <= 0) {
                                    echo "<b class='pstrong text-danger'>SL(NA)</b>";
                                } else {
                                    echo '<b class="pstrong">SL (' . $dataIClv['SL'] . ')</b>';
                                }
                                ?>
                            </a>
                        </div>
                    </div>
                </div>

                <div class="col-sm-6 mt-1">
                    <div class="row">
                        <div class="col-4">
                            <a href="leave-request-pl.php">
                                <div class="icon-wrapper"><i class="fas fa-user"></i></div>
                                <?php
                                // Display as PL; if your UI label needs EL, change the label text only.
                                if ($dataIClv['PL'] <= 0) {
                                    echo "<b class='pstrong text-danger'>PL(NA)</b>";
                                } else {
                                    echo '<b class="pstrong">PL (' . $dataIClv['PL'] . ')</b>';
                                }
                                ?>
                            </a>
                        </div>

                        <div class="col-4">
                            <a href="leave-request-coff.php">
                                <div class="icon-wrapper"><i class="fas fa-clipboard-list"></i></div>
                                <?php
                                if ($coffAvailable) {
                                    echo "<b class='pstrong text-success'>COFF</b>";
                                } else {
                                    echo '<b class="pstrong text-danger">COFF(NA)</b>';
                                }
                                ?>
                            </a>
                        </div>

                        <div class="col-4">
                            <a href="leave-request-od.php">
                                <div class="icon-wrapper"><i class="fas fa-laptop-house"></i></div>
                                <strong class="pstrong">Apply OD</strong>
                            </a>
                        </div>
                    </div>
                </div>

                <div class="col-sm-6 mt-1">
                    <div class="row">
                        <div class="col-6">
                            <a href="leave-view-last.php">
                                <div class="icon-wrapper bg-primary text-white"><i class="fas fa-calendar-alt"></i></div>
                                <strong class="pstrong">View Last Month</strong>
                            </a>
                        </div>
                        <div class="col-6">
                            <a href="leave-view-current.php">
                                <div class="icon-wrapper bg-success text-white"><i class="fas fa-calendar-week"></i></div>
                                <strong class="pstrong">View Current Month</strong>
                            </a>
                        </div>
                    </div>
                </div>

            </div><!-- /.row -->

        </div><!-- /.wallet-card -->
    </div><!-- /.section -->
    <?php include('include/copyright.php'); ?>
</div><!-- /#appCapsule -->

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