<?php 
  session_start();
  // 1. Security Check
  if(empty($_SESSION['branch']) || $_SESSION['branch'] == ''){
    header("Location: index.php");
    die();
  }
  
  require_once 'system/conn.php';
  
  // 2. FETCH AVAILABLE DATA (Strict Mode)
  // We query the History Table to see exactly what Year/Month combinations exist.
  $branch_id = $_SESSION['branch'];
  
  // NOTE: Changed table to 'prv_salary_attendance' as requested
  $sql = "SELECT DISTINCT year, month FROM prv_salary_attendance 
          WHERE branch = :branch 
          ORDER BY year DESC, month DESC";
          
  $stmt = $conn->prepare($sql);
  $stmt->execute([':branch' => $branch_id]);
  $raw_data = $stmt->fetchAll(PDO::FETCH_ASSOC);

  // 3. Structure Data for JavaScript:  [ 2025 => ['01', '02'], 2024 => ['12', '11'] ]
  $date_map = [];
  if($raw_data) {
      foreach($raw_data as $row) {
          // Force month to be 2 digits (e.g., '1' becomes '01') for consistency
          $m = str_pad($row['month'], 2, '0', STR_PAD_LEFT);
          $date_map[$row['year']][] = $m;
      }
  }
?>
<!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" />
    <script src="assets/js/jquery.min.js"></script>

    <title>Previous Attendance</title>
    
    <style>
        .card {
            border: none;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .form-label {
            color: #1e293b !important;
            font-weight: 700;
            font-size: 1rem;
            margin-bottom: 0.5rem;
            display: block; 
        }

        .form-control, .form-select {
            border: 1px solid #cbd5e1;
            padding: 0.7rem 1rem; 
            font-size: 1rem;
            border-radius: 6px;
        }
        .form-control:focus, .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
    </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">Attendance History</div>
        </div>

        <div class="row">
          <div class="col-xl-6 mx-auto">
             
             <div class="card border-top border-0 border-4 border-primary">
               <div class="card-body p-4">

                <div class="d-flex align-items-center justify-content-between mb-4">
                    <div>
                        <h5 class="mb-0 text-primary">Previous Records</h5>
                        <p class="mb-0 text-secondary">View archived data from <strong>prv_salary_attendance</strong>.</p>
                    </div>
                    <div class="fs-1 text-primary"><i class="bi bi-archive"></i></div>
                </div>
                <hr class="mb-4" />

                <form action="previous-attendance-data.php" method="post">
                    
                    <div class="row g-4">
                        
                        <div class="col-md-12">
                            <label class="form-label">Select Available Year</label>
                            <select class="form-select" id="selectYear" name="year" required>
                                <option value="">--- Select Year ---</option>
                                <?php 
                                    if(!empty($date_map)) {
                                        foreach($date_map as $year => $months) {
                                            echo "<option value='$year'>$year</option>";
                                        }
                                    } else {
                                        echo "<option disabled>No Data Found</option>";
                                    }
                                ?>
                            </select>
                        </div>

                        <div class="col-md-12">
                            <label class="form-label">Select Available Month</label>
                            <select class="form-select" id="selectMonth" name="month" required disabled>
                                <option value="">--- Select Year First ---</option>
                                </select>
                            <div class="form-text text-muted small">
                                <i class="bi bi-info-circle"></i> Showing only months present in database.
                            </div>
                        </div>

                        <div class="col-12 mt-4">
                            <button type="submit" class="btn btn-primary w-100 py-2">
                                <i class="bi bi-search me-2"></i>Search Records
                            </button>
                        </div>

                    </div>
                </form>

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

      </div>
    </div>
    
    <script>
    $(document).ready(function() {
        // Pass PHP Array to JavaScript
        const availableData = <?php echo json_encode($date_map); ?>;
        
        // Month Names Map for nice display
        const monthNames = {
            '01': 'January', '02': 'February', '03': 'March', '04': 'April',
            '05': 'May',     '06': 'June',     '07': 'July',  '08': 'August',
            '09': 'September','10': 'October', '11': 'November','12': 'December'
        };

        $('#selectYear').change(function() {
            var selectedYear = $(this).val();
            var $monthSelect = $('#selectMonth');
            
            // Clear current options
            $monthSelect.empty().append('<option value="">--- Select Month ---</option>');

            if(selectedYear && availableData[selectedYear]) {
                // Enable dropdown
                $monthSelect.prop('disabled', false);
                
                // Loop through available months for this year
                var months = availableData[selectedYear];
                
                // Sort months numerically descending (optional, looks better)
                months.sort(function(a, b){return b-a}); 

                $.each(months, function(index, monthCode) {
                    var monthName = monthNames[monthCode] || monthCode;
                    $monthSelect.append('<option value="' + monthCode + '">' + monthName + '</option>');
                });
            } else {
                // Disable if no year or no data
                $monthSelect.prop('disabled', true);
                $monthSelect.append('<option value="">No data for this year</option>');
            }
        });
    });
    </script>

<?php include'system/footer.php'?>