<?php 

include 'db_connect.php';

$varNumberOfDays = 30;
$reportType = $_GET['report_type'];
?>
<div class="col-md-12">
    <div class="card card-outline card-success">
        <div class="card-header">
			<?php if($reportType == 'month-report'):?>
            <div class="row">
                <div class="col-md-3">
                    <div class="form-group">
                        <label>From Date</label>
                        <input type="date" name="from_date" id="from_date"
                            value="<?php if(isset($_GET['from_date'])){ echo $_GET['from_date']; } ?>"
                            class="form-control">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label>To Date</label>
                        <input type="date" name="to_date" id="to_date"
                            value="<?php if(isset($_GET['to_date'])){ echo $_GET['to_date']; } ?>" class="form-control">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label>Users<?php //echo "<pre>"; print_r($_SESSION['login_id']);?></label>

                        <select name="user_id" id="user_id" class="form-control">
                            <option value="">Select users</option>
                            <?php 
                             $role_str = '';
                             if($_SESSION['login_type'] !='1')
                             {
                                 $role_str = "  AND manager_id='".$_SESSION['login_id']."'";
                             }
                            $qry_user = $conn->query("SELECT id, concat(firstname, ' ',lastname) as name  FROM `users` WHERE type!='1' $role_str");
                             if ($qry_user->num_rows > 0)
                             { 
                                while($row_users = $qry_user->fetch_assoc()) 
                                { ?>
                            <option value="<?=$row_users['id']?>"
                                <?php if(isset($_GET['user_id'])){ echo 'selected'; } ?>><?=$row_users['name']?>
                            </option>
                            <?php  }
                             }
                         
                            ?>


                        </select>
                    </div>
                </div>

                <div class="col-md-3">
                    <div class="form-group">
                        <label></label> <br>
                        <button type="button" id="filter_btn" class="btn btn-primary" style="margin-top:24px;">Filter
                            Date</button>
                    </div>
                </div>
            </div>
			<?php endif;?>
            
            <div class="card-tools">
                <button class="btn btn-flat btn-sm bg-gradient-success btn-success" id="downloadCsvButton" onClick="downloadCsv()" ><i
                        class="fa fa-print"></i> Download Reports</button>
                        
            </div>

        </div>
        <div class="card-body p-0">
            <div class="table-responsive" id="printable">

            </div>
        </div>
       



    </div>
</div>

<?php if($reportType == 'month-report'):?>
<script>
$(document).ready(function() {
    monthly_report();

    $('#filter_btn').click(function() {
        var from_date = $('#from_date').val();
        var to_date = $('#to_date').val();
        var user_id = $('#user_id').val();
        monthly_report(from_date, to_date, user_id);

    });

});
function monthly_report(from_date = '', to_date = '', user_id = '') {
    //  alert(from_date);

    $.ajax({
        url: 'monthly_report.php',
        method: 'POST',
        data: {
            'action': 'monthly_report',
            'from_date': from_date,
            'to_date': to_date,
            'user_id': user_id
        },
        success: function(response) {
            //alert(response);
            $('#printable').html(response);
        }
    });
}
</script>
<?php endif;?>
<?php if($reportType == 'average-report'):?>
<script>
function average_report(from_date = '', to_date = '', user_id = '') {
    $.ajax({
        url: 'average_report.php',
        method: 'POST',
        data: {
            'action': 'average_report',
            'from_date': from_date,
            'to_date': to_date,
            'user_id': user_id
        },
        success: function(response) {
            $('#printable').html(response);
        }
    });
}

$(document).ready(function() {
        var fromDate = '2024-01-01';
        var toDate = '2024-12-31';

        average_report(fromDate, toDate);
});
</script>
<?php endif;?>
<script>
$('#print').click(function() {
    start_load()
    var _h = $('head').clone()
    var _p = $('#printable').clone()
    var _d = "<p class='text-center'><b>Project Progress Report as of (<?php echo date("F d, Y") ?>)</b></p>"
    _p.prepend(_d)
    _p.prepend(_h)
    var nw = window.open("", "", "width=900,height=600")
    nw.document.write(_p.html())
    nw.document.close()
    nw.print()
    setTimeout(function() {
        nw.close()
        end_load()
    }, 750)
})
</script>
<script>
function downloadCsv() {
    var csvContent = getTableCsvContent();
    var blob = new Blob([csvContent], {
        type: 'text/csv;charset=utf-8;'
    });
    var link = document.createElement('a');
    var fileName = '<?php echo $reportType;?>.csv';
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

function getTableCsvContent() {
    var csvContent = [];
    var rows = document.querySelectorAll('table tr');
    var headerRow = [];
    document.querySelectorAll('.th-day-date').forEach(function(th) {
        var weekday = th.querySelector('.month-days')?.innerText.trim() || '';
        var date = th.querySelector('.month-date')?.innerText.trim() || '';
        headerRow.push(weekday + ' ' + date);
    });
    csvContent.push('User Name,' + headerRow.join(','));
    for (var i = 1; i < rows.length; i++) {
        var cols = rows[i].querySelectorAll('td');
        var userName = cols[1]?.innerText.trim();
        if (userName !== '') {
            var rowData = [userName];
            for (var j = 2; j < cols.length; j++) {
                rowData.push(cols[j]?.innerText.trim() || '');
            }

            // Combine row data into a CSV line
            csvContent.push(rowData.join(','));
        }
    }

    return csvContent.join('\n');
}
</script>