<?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_salary_info') {
      
      $branch = $_SESSION['branch'];
      $eid    = $_POST['emp_id'] ?? '';
      
      $response = ['found' => false];

      if($eid) {
          try {
              // 1. Get Date of Joining (DOJ)
              $stmt = $conn->prepare("SELECT e_doj FROM emp_details WHERE e_id = ? AND branch = ?");
              $stmt->execute([$eid, $branch]);
              $emp = $stmt->fetch(PDO::FETCH_ASSOC);

              if($emp && !empty($emp['e_doj']) && $emp['e_doj'] != '0000-00-00') {
                  
                  $dojTime = strtotime($emp['e_doj']);
                  $minYear = (int)date('Y', $dojTime);
                  $minMonth= (int)date('m', $dojTime);
                  
                  // 2. Calculate "To" Date (Strictly Last Month)
                  $maxTime = strtotime("-1 month"); 
                  $maxYear = (int)date('Y', $maxTime);
                  $maxMonth= (int)date('m', $maxTime);

                  // 3. Generate Year Range (From Joining Year -> Max Year)
                  // FIX: We use $maxYear as the ceiling, NOT the current system year.
                  if($minYear > $maxYear) $minYear = $maxYear; // Safety check

                  $years = [];
                  for ($y = $maxYear; $y >= $minYear; $y--) {
                      $years[] = $y;
                  }

                  $response['found'] = true;
                  $response['years'] = $years; 
                  
                  // Send Limits to JS
                  $response['min_year']  = $minYear;
                  $response['min_month'] = $minMonth; 
                  $response['max_year']  = $maxYear;
                  $response['max_month'] = $maxMonth;

                  $response['text_info'] = "Joining Date: " . date('d F Y', $dojTime);
              } 
              else {
                   $response['error'] = "Date of Joining not found. Defaulting to recent years.";
                   // Fallback: Last 5 years from 'Last Month'
                   $maxTime = strtotime("-1 month");
                   $maxYear = (int)date('Y', $maxTime);
                   
                   $response['years'] = range($maxYear, $maxYear-5);
                   $response['min_year'] = $maxYear - 5; $response['min_month'] = 1;
                   $response['max_year'] = $maxYear;     $response['max_month'] = (int)date('m', $maxTime);
              }

          } catch (Exception $e) {
              $response['error'] = $e->getMessage();
          }
      }

      header('Content-Type: application/json');
      echo json_encode($response);
      exit; 
  }
  // =============================================================
?>
<!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>Employee Salary History</title>
    
    <style>
        .select2-container .select2-selection--single {
            height: 38px !important;
            border: 1px solid #ced4da;
        }
        .select2-container--bootstrap-5 .select2-selection {
            border-color: #ced4da;
        }
        .info-box {
            background-color: #e8f4ff;
            border: 1px solid #b6dfff;
            color: #0c5460;
            padding: 10px;
            border-radius: 5px;
            font-size: 0.90rem;
            display: none; 
            margin-bottom: 20px;
        }
    </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">Employee Salary History</div>
            <div class="ms-auto"></div>
          </div>
            <hr/>

            <div class="row">
              <div class="col-xl-9 mx-auto">
                <div class="card shadow-sm">
                  <div class="card-body">
                    <div class="p-4">
                      
                      <form method="post" action="emp-report-process.php" target="_blank" id="historyForm">
                        
                        <div class="row mb-2">
                            <div class="col-12">
                                <label class="form-label fw-bold">Select Employee</label>
                                <select class="form-select select2" name="ename" id="ename" required>
                                    <option value="">-- Select Employee --</option>
                                    <?php 
                                    $stmt = $conn->prepare("SELECT e_id, e_name FROM emp_details WHERE branch = ? ORDER BY e_name ASC");
                                    $stmt->execute([$_SESSION['branch']]);
                                    $users = $stmt->fetchAll();
                                    foreach($users as $row) { ?>
                                        <option value="<?php echo $row['e_id']?>"><?php echo $row['e_name'];?> (<?php echo $row['e_id']?>)</option>
                                    <?php }?>
                                </select>
                                <div id="loading-msg" class="text-primary small mt-1" style="display:none;">
                                    <i class="spinner-border spinner-border-sm me-1"></i> Checking database...
                                </div>
                            </div>
                        </div>

                        <div id="range-info" class="info-box">
                            <i class="bi bi-calendar-check me-2"></i>
                            <span id="range-text"></span>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="card bg-light border-0 h-100">
                                    <div class="card-body">
                                        <h6 class="text-primary mb-3">From (Start Date)</h6>
                                        <div class="mb-2">
                                            <label class="form-label small text-muted">Year</label>
                                            <select class="form-select" id="fromyear" name="fromyear" required disabled>
                                                <option value="">Select Employee First</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label class="form-label small text-muted">Month</label>
                                            <select class="form-select" id="frommonth" name="frommonth" required disabled>
                                                <option value="">Select Year First</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="card bg-light border-0 h-100">
                                    <div class="card-body">
                                        <h6 class="text-success mb-3">To (End Date)</h6>
                                        <div class="mb-2">
                                            <label class="form-label small text-muted">Year</label>
                                            <select class="form-select" id="toyear" name="toyear" required disabled>
                                                <option value="">Select Employee First</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label class="form-label small text-muted">Month</label>
                                            <select class="form-select" id="tomonth" name="tomonth" required disabled>
                                                <option value="">Select Year First</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">                                
                            <div class="col-12 d-grid">
                                <button type="submit" name="submit" id="btn-generate" class="btn btn-primary btn-lg" disabled>
                                    <i class="bi bi-file-earmark-spreadsheet me-2"></i>Generate History Report
                                </button>
                            </div>
                        </div>

                       </form>    
                    </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>
        var LIMITS = {
            minYear: 0, minMonth: 0,
            maxYear: 0, maxMonth: 0
        };

        const MONTHS = [
            {v:'01', n:'January'}, {v:'02', n:'February'}, {v:'03', n:'March'},
            {v:'04', n:'April'},   {v:'05', n:'May'},      {v:'06', n:'June'},
            {v:'07', n:'July'},    {v:'08', n:'August'},   {v:'09', n:'September'},
            {v:'10', n:'October'}, {v:'11', n:'November'}, {v:'12', n:'December'}
        ];

        $(document).ready(function() {
            $('.select2').select2({
                theme: 'bootstrap-5',
                width: '100%',
                placeholder: 'Search for Employee...',
                allowClear: true
            });

            $('#ename').on('change', function() {
                fetchSalaryData();
            });

            // Re-populate months when year changes to apply strict limits
            $('#fromyear').on('change', function() { populateMonths('from'); });
            $('#toyear').on('change', function() { populateMonths('to'); });
        });

        function fetchSalaryData() {
            let empId = $('#ename').val();
            
            // Reset
            $('#fromyear, #toyear, #frommonth, #tomonth, #btn-generate').prop('disabled', true);
            $('#fromyear, #toyear').empty().append('<option value="">Loading...</option>');
            $('#range-info').slideUp();

            if(!empId) return;

            $('#loading-msg').show();
            
            $.ajax({
                url: 'emp-salary-history.php',
                type: 'POST',
                data: { ajax_action: 'get_salary_info', emp_id: empId },
                dataType: 'json',
                success: function(data) {
                    $('#loading-msg').hide();

                    if(data.found) {
                        LIMITS.minYear = parseInt(data.min_year);
                        LIMITS.minMonth = parseInt(data.min_month);
                        LIMITS.maxYear = parseInt(data.max_year);
                        LIMITS.maxMonth = parseInt(data.max_month);

                        let yearOptions = '';
                        $.each(data.years, function(index, year) {
                            yearOptions += '<option value="'+year+'">'+year+'</option>';
                        });
                        $('#fromyear, #toyear').empty().append(yearOptions);
                        
                        // Set Defaults (Min for From, Max for To)
                        $('#fromyear').val(data.min_year);
                        $('#toyear').val(data.max_year);

                        // Populate Months with Strict Limits
                        populateMonths('from', data.min_month);
                        populateMonths('to', data.max_month);

                        $('#range-text').html('<strong>' + data.text_info + '</strong>');
                        $('#range-info').removeClass('alert-danger').addClass('alert-info').slideDown();

                        $('#fromyear, #toyear, #frommonth, #tomonth, #btn-generate').prop('disabled', false);

                    } else {
                        let msg = data.error ? data.error : 'Data Missing.';
                        $('#range-text').text(msg);
                        $('#range-info').show();
                        $('#fromyear, #toyear').empty().append('<option value="">No Data</option>');
                    }
                },
                error: function() {
                    $('#loading-msg').hide();
                    alert('System error.');
                }
            });
        }

        function populateMonths(type, selectedMonthVal = null) {
            let yearSel = (type === 'from') ? '#fromyear' : '#toyear';
            let monthSel = (type === 'from') ? '#frommonth' : '#tomonth';
            
            let selectedYear = parseInt($(yearSel).val());
            let start = 1; 
            let end = 12;

            // Strict Logic:
            // 1. If this is the "Joining Year", hide months before joining
            if(type === 'from' && selectedYear === LIMITS.minYear) {
                start = LIMITS.minMonth;
            }
            
            // 2. If this is the "Current/Last Year", hide future months
            // (e.g., If Max is Jan 2026, and 2026 is selected, hide Feb-Dec)
            if(type === 'to' && selectedYear === LIMITS.maxYear) {
                end = LIMITS.maxMonth;
            }

            // Generate
            $(monthSel).empty();
            let hasSelection = false;
            
            for(let i = start; i <= end; i++) {
                let monthVal = (i < 10) ? '0' + i : '' + i; 
                let monthName = MONTHS[i-1].n;
                let isSelected = '';
                
                if(selectedMonthVal && parseInt(selectedMonthVal) === i) {
                    isSelected = 'selected';
                    hasSelection = true;
                }
                
                $(monthSel).append(`<option value="${monthVal}" ${isSelected}>${monthName}</option>`);
            }
            
            // If the previously selected month is no longer valid (e.g. user switched year), select the first available
            if(!hasSelection) {
                 $(monthSel + ' option:first').prop('selected', true);
            }
        }
    </script>
  </body>
</html>