<?php
require_once 'config.php';
require_once 'auth_functions.php';
requireLogin();

$user_id      = $_SESSION['user_id'];
$current_year = date('Y');

// Initialize leave balance for current year if not exists
$sql_check = "SELECT * FROM leave_balance WHERE user_id = $user_id AND year = $current_year";
$result_check = $conn->query($sql_check);
if ($result_check->num_rows === 0) {
    $sql_insert = "INSERT INTO leave_balance (user_id, year) VALUES ($user_id, $current_year)";
    $conn->query($sql_insert);
}

// Get leave statistics
$sql_stats   = "SELECT * FROM leave_balance WHERE user_id = $user_id AND year = $current_year";
$leave_stats = $conn->query($sql_stats)->fetch_assoc();

// Get pending leaves count
$sql_pending   = "SELECT COUNT(*) as pending FROM leave_applications WHERE user_id = $user_id AND status = 'pending'";
$pending_count = $conn->query($sql_pending)->fetch_assoc()['pending'];

// Get approved leaves count
$sql_approved    = "SELECT COUNT(*) as approved FROM leave_applications WHERE user_id = $user_id AND status = 'approved'";
$approved_count  = $conn->query($sql_approved)->fetch_assoc()['approved'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Dashboard - Leave Management System</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <style>
        body {
            background-color: #27F2F5;
        }
        .navbar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .stats-card {
            border-radius: 10px;
            border: none;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            transition: transform 0.3s;
        }
        .stats-card:hover {
            transform: translateY(-5px);
        }
        .card-casual   { border-left: 4px solid #a7283dff; background-color: #d30e0eff; }
        .card-medical  { border-left: 4px solid #17a2b8;   background-color: #eb147fff; }
        .card-duty     { border-left: 4px solid #ffc107;   background-color: #ec1621ff; }
        .card-pending  { border-left: 4px solid #fd7e14;   background-color: #7a16ecff; }
        .card-approved { border-left: 4px solid #20c997;   background-color: #ecba16ff; }
    </style>
</head>
<body>
    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <i class="fas fa-calendar-check"></i> Leave Management System
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="user_dashboard.php">
                            <i class="fas fa-home"></i> Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="apply_leave.php">
                            <i class="fas fa-plus-circle"></i> Apply Leave
                        </a>
                    </li>

                    <!-- NEW: Leave Guidelines button -->
                    <li class="nav-item">
                        <a class="nav-link" href="guidelines.pdf" target="_blank">
                            <i class="fas fa-file-pdf"></i> Leave Guidelines
                        </a>
                    </li>

                    <!-- NEW: All Leaves button (opens separate page) -->
                    <li class="nav-item">
                        <a class="nav-link" href="all_leaves_user_view.php">
                            <i class="fas fa-users"></i> All Leaves
                        </a>
                    </li>

                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user"></i> <?php echo $_SESSION['full_name']; ?>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <h2 class="mb-4">Welcome, <?php echo $_SESSION['full_name']; ?>!</h2>
        
        <!-- Leave Statistics Cards -->
        <div class="row mb-4">
            <div class="col-md-3 mb-3">
                <div class="card stats-card card-casual">
                    <div class="card-body">
                        <h6 class="card-title text-muted">Casual Leaves</h6>
                        <h3 class="mb-0"><?php echo $leave_stats['casual_leaves_used']; ?> / 20</h3>
                        <small class="text-muted">Available: <?php echo 20 - $leave_stats['casual_leaves_used']; ?></small>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="card stats-card card-medical">
                    <div class="card-body">
                        <h6 class="card-title text-muted">Medical Leaves</h6>
                        <h3 class="mb-0"><?php echo $leave_stats['medical_leaves_used']; ?> / 21</h3>
                        <small class="text-muted">Available: <?php echo 21 - $leave_stats['medical_leaves_used']; ?></small>
                    </div>
                </div>
            </div>
            <div class="col-md-2 mb-3">
                <div class="card stats-card card-duty">
                    <div class="card-body">
                        <h6 class="card-title text-muted">Duty Leaves</h6>
                        <h3 class="mb-0"><?php echo $leave_stats['duty_leaves_used']; ?></h3>
                        <small class="text-muted">Unlimited</small>
                    </div>
                </div>
            </div>
            <div class="col-md-2 mb-3">
                <div class="card stats-card card-pending">
                    <div class="card-body">
                        <h6 class="card-title text-muted">Pending</h6>
                        <h3 class="mb-0"><?php echo $pending_count; ?></h3>
                        <small class="text-muted">Requests</small>
                    </div>
                </div>
            </div>
            <div class="col-md-2 mb-3">
                <div class="card stats-card card-approved">
                    <div class="card-body">
                        <h6 class="card-title text-muted">Approved</h6>
                        <h3 class="mb-0"><?php echo $approved_count; ?></h3>
                        <small class="text-muted">This Year</small>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filter Section -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-filter"></i> Filter Leave History</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <label>Start Date</label>
                        <input type="date" id="filter_start_date" class="form-control">
                    </div>
                    <div class="col-md-4">
                        <label>End Date</label>
                        <input type="date" id="filter_end_date" class="form-control">
                    </div>
                    <div class="col-md-4">
                        <label>&nbsp;</label>
                        <button class="btn btn-primary w-100" onclick="filterLeaves()">
                            <i class="fas fa-search"></i> Filter
                        </button>
                        <button class="btn btn-secondary w-100 mt-2" onclick="downloadMyLeavesPDF()">
                            <i class="fas fa-download"></i> Download PDF
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Leave Applications Table -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-list"></i> My Leave Applications</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="leavesTable" class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>Leave Type</th>
                                <th>Start Date</th>
                                <th>End Date</th>
                                <th>Days</th>
                                <th>Reason</th>
                                <th>Apply Date</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script>
        let table;
        
        $(document).ready(function() {
            loadLeaves();
        });
        
        function loadLeaves() {
            if (table) {
                table.destroy();
            }
            
            table = $('#leavesTable').DataTable({
                ajax: {
                    url: 'ajax_get_my_leaves.php',
                    dataSrc: ''
                },
                columns: [
                    { data: 'leave_type' },
                    { data: 'start_date' },
                    { data: 'end_date' },
                    { data: 'number_of_days' },
                    { data: 'reason' },
                    { data: 'apply_date' },
                    { 
                        data: 'status',
                        render: function(data) {
                            let badgeClass = data === 'approved' ? 'success' : (data === 'rejected' ? 'danger' : 'warning');
                            return `<span class="badge bg-${badgeClass}">${data.toUpperCase()}</span>`;
                        }
                    }
                ],
                order: [[5, 'desc']]
            });
        }
        
        function filterLeaves() {
            const startDate = $('#filter_start_date').val();
            const endDate   = $('#filter_end_date').val();
            
            if (table) {
                table.destroy();
            }
            
            table = $('#leavesTable').DataTable({
                ajax: {
                    url: 'ajax_get_my_leaves.php',
                    data: { start_date: startDate, end_date: endDate },
                    dataSrc: ''
                },
                columns: [
                    { data: 'leave_type' },
                    { data: 'start_date' },
                    { data: 'end_date' },
                    { data: 'number_of_days' },
                    { data: 'reason' },
                    { data: 'apply_date' },
                    { 
                        data: 'status',
                        render: function(data) {
                            let badgeClass = data === 'approved' ? 'success' : (data === 'rejected' ? 'danger' : 'warning');
                            return `<span class="badge bg-${badgeClass}">${data.toUpperCase()}</span>`;
                        }
                    }
                ],
                order: [[5, 'desc']]
            });
        }
        
        function downloadMyLeavesPDF() {
            const startDate = $('#filter_start_date').val();
            const endDate   = $('#filter_end_date').val();
            window.open(`download_my_leaves_pdf.php?start_date=${startDate}&end_date=${endDate}`, '_blank');
        }
    </script>
</body>
</html>
