<?php
session_start();
if(empty($_SESSION['branch']) || $_SESSION['branch'] == ''){
    header("Location: index.php");
    die();
}
require_once 'system/conn.php';

// =============================================================
//  INTERNAL AJAX HANDLER
// =============================================================
if (isset($_POST['ajax_action']) && $_POST['ajax_action'] == 'get_employees') {
    
    $branch = $_SESSION['branch'];
    $year   = $_POST['year'] ?? '';
    $month  = $_POST['month'] ?? '';
    $type   = $_POST['type'] ?? 'current'; 

    $response = [];

    if($year && $month) {
        try {
            $table = ($type === 'current') ? 'emp_salary' : 'prv_emp_salary';

            $stmt = $conn->prepare("
                SELECT DISTINCT emp_id, name 
                FROM `$table`
                WHERE branch = ? AND year = ? AND month = ?
                ORDER BY name ASC
            ");
            
            $stmt->execute([$branch, $year, $month]);
            $response = $stmt->fetchAll(PDO::FETCH_ASSOC);

        } catch (Exception $e) {
            $response = []; 
        }
    }

    header('Content-Type: application/json');
    echo json_encode($response);
    exit; 
}
// =============================================================

// Calculate "Current" Salary Period (Last Month)
$curYear  = date('Y', strtotime("-1 month"));
$curMonth = date('m', strtotime("-1 month"));
$curMonthName = date('F Y', strtotime("-1 month"));
?>
<!doctype html>
<html lang="en" class="semi-dark">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <link href="assets/css/pace.min.css" rel="stylesheet" />
    <script src="assets/js/pace.min.js"></script>
    <link href="assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet" />
    <link href="assets/plugins/simplebar/css/simplebar.css" rel="stylesheet" />
    <link href="assets/plugins/metismenu/css/metisMenu.min.css" rel="stylesheet" />
    <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/bootstrap-extended.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
    <link href="assets/css/icons.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">
    <link href="assets/css/dark-theme.css" rel="stylesheet" />
    <link href="assets/css/semi-dark.css" rel="stylesheet" />
    <link href="assets/css/header-colors.css" rel="stylesheet" />
    
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />

    <title>Generate Salary Slip</title>
    
    <style>
        .mode-card {
            cursor: pointer;
            transition: all 0.2s ease-in-out;
            border: 1px solid #dee2e6;
            background-color: #fff;
            padding: 15px; 
        }
        .mode-card:hover {
            border-color: #0d6efd;
            background-color: #f8f9fa;
        }
        .mode-card.active {
            border: 2px solid #0d6efd;
            background-color: #e7f1ff; 
            position: relative;
        }
        .mode-card.active::after {
            content: "\F26E"; 
            font-family: "bootstrap-icons";
            position: absolute;
            top: 5px;
            right: 5px;
            color: #0d6efd;
            font-size: 1.2rem;
        }
        .select2-container .select2-selection--single {
            height: 38px !important; 
            padding: 5px;
            border: 1px solid #ced4da;
        }
        .select2-container--bootstrap-5 .select2-selection {
            border-color: #ced4da;
        }
    </style>
</head>
<body>
<div class="wrapper">
    <?php include 'system/header.php'; ?>
    <div class="page-content-wrapper">
        <div class="page-content">
            
            <div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
                <div class="breadcrumb-title pe-3">Salary Slip Generation</div>
            </div>
            <hr/>

            <div class="row">
                <div class="col-xl-8 mx-auto"> 
                    <div class="card shadow-sm">
                        <div class="card-body p-4">
                            
                            <form action="salary-slip-single-view.php" method="post" target="_blank">
                                <input type="hidden" name="salary_type" id="salary_type" value="current">

                                <h6 class="mb-2 text-secondary">Step 1: Slip Type</h6>
                                <div class="row g-2 mb-4"> 
                                    <div class="col-md-6">
                                        <div class="card shadow-none rounded mode-card active" onclick="setMode('current', this)">
                                            <div class="d-flex align-items-center">
                                                <div class="fs-3 text-primary me-3"><i class="bi bi-calendar-check"></i></div>
                                                <div>
                                                    <h6 class="mb-0 fw-bold">Current Slip</h6>
                                                    <small class="text-muted d-block" style="font-size: 0.85rem;"><?= $curMonthName ?></small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="card shadow-none rounded mode-card" onclick="setMode('old', this)">
                                            <div class="d-flex align-items-center">
                                                <div class="fs-3 text-warning me-3"><i class="bi bi-archive"></i></div>
                                                <div>
                                                    <h6 class="mb-0 fw-bold">Old / Archive</h6>
                                                    <small class="text-muted d-block" style="font-size: 0.85rem;">Past records</small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label class="form-label fw-bold">Step 2: Year</label>
                                        <select class="form-select" name="year" id="year" onchange="fetchEmployees()">
                                            <?php 
                                            $nowYear = date('Y');
                                            for($i = $nowYear; $i >= $nowYear - 5; $i--) { 
                                                echo "<option value='$i'>$i</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label fw-bold">Step 3: Month</label>
                                        <select class="form-select" name="month" id="month" onchange="fetchEmployees()">
                                            <?php
                                            for($m=1; $m<=12; $m++){
                                                $mPad = str_pad($m, 2, '0', STR_PAD_LEFT);
                                                $mName = date('F', mktime(0, 0, 0, $m, 10));
                                                echo "<option value='$mPad'>$mName</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>

                                <div class="mb-4">
                                    <label class="form-label fw-bold">Step 4: Select Employee</label>
                                    <select class="form-select select2" name="ename" id="ename" required>
                                        <option value="">-- First Select Year & Month --</option>
                                    </select>
                                    <div id="loading-msg" class="text-primary small mt-1" style="display:none;">
                                        <i class="spinner-border spinner-border-sm me-1"></i> Loading list...
                                    </div>
                                </div>

                                <div class="d-grid">
                                    <button type="submit" name="submit" class="btn btn-primary btn-lg">
                                        <i class="bi bi-file-earmark-pdf me-2"></i>Generate Single Slip
                                    </button>
                                </div>

                            </form>

                            <div class="mt-5 pt-4 border-top">
                                <h6 class="mb-3 text-secondary text-center">— OR —</h6>
                                
                                <div class="d-grid">
                                    <a href="salary-slip-current-all-emp-view" target="_blank" class="btn btn-outline-dark btn-lg">
                                        <i class="bi bi-printer-fill me-2"></i>Print All Current Slips (Bulk)
                                    </a>
                                    <small class="text-center text-muted mt-2">
                                        Generates slips for ALL employees for the current month in one click.
                                    </small>
                                </div>
                            </div>

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

        </div>
    </div>
    <?php include 'system/footer.php'; ?>
    
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <script>
        const CUR_YEAR  = "<?= $curYear ?>";
        const CUR_MONTH = "<?= $curMonth ?>";

        $(document).ready(function() {
            $('.select2').select2({
                theme: 'bootstrap-5',
                width: '100%',
                placeholder: 'Type name to search...',
                allowClear: true
            });

            setMode('current', $('.mode-card').first()[0]);
        });

        function setMode(mode, element) {
            $('.mode-card').removeClass('active');
            $(element).addClass('active');
            $('#salary_type').val(mode);

            if(mode === 'current') {
                $('#year').val(CUR_YEAR).css('pointer-events', 'none').css('background-color', '#e9ecef');
                $('#month').val(CUR_MONTH).css('pointer-events', 'none').css('background-color', '#e9ecef');
            } else {
                $('#year').css('pointer-events', 'auto').css('background-color', '#fff');
                $('#month').css('pointer-events', 'auto').css('background-color', '#fff');
            }
            fetchEmployees();
        }

        function fetchEmployees() {
            let year  = $('#year').val();
            let month = $('#month').val();
            let type  = $('#salary_type').val();

            if(!year || !month) return;

            $('#ename').prop('disabled', true);
            $('#loading-msg').show();
            $('#ename').empty().trigger('change');

            $.ajax({
                url: 'salary-slip.php',
                type: 'POST',
                data: { 
                    ajax_action: 'get_employees', 
                    year: year, 
                    month: month, 
                    type: type 
                },
                dataType: 'json',
                success: function(data) {
                    $('#ename').empty(); 
                    if(data.length > 0) {
                        let options = '<option value="">-- Select Employee --</option>';
                        $.each(data, function(key, emp) {
                            options += '<option value="'+emp.emp_id+'">'+emp.name+' ('+emp.emp_id+')</option>';
                        });
                        $('#ename').append(options);
                    } else {
                        $('#ename').append('<option value="">No Salary Records Found</option>');
                    }
                    $('#ename').trigger('change'); 
                    $('#ename').prop('disabled', false);
                    $('#loading-msg').hide();
                },
                error: function() {
                    $('#loading-msg').hide();
                    $('#ename').prop('disabled', false);
                }
            });
        }
    </script>
</div>
</body>
</html>