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

// =============================================================
// INTERNAL AJAX HANDLER: Fetches available dates from archives
// =============================================================
if (isset($_POST['ajax_action']) && $_POST['ajax_action'] == 'get_archive_dates') {
    $branch = $_SESSION['branch'];
    $response = ['years' => [], 'months' => []];

    try {
        // Querying the archived table
        $stmt = $conn->prepare("SELECT DISTINCT year FROM prv_emp_salary WHERE branch = ? ORDER BY year DESC");
        $stmt->execute([$branch]);
        $response['years'] = $stmt->fetchAll(PDO::FETCH_COLUMN);
        
        if (isset($_POST['selected_year'])) {
            $stmtM = $conn->prepare("SELECT DISTINCT month FROM prv_emp_salary WHERE branch = ? AND year = ? ORDER BY month ASC");
            $stmtM->execute([$branch, $_POST['selected_year']]);
            $months = $stmtM->fetchAll(PDO::FETCH_COLUMN);
            foreach($months as $m) {
                $response['months'][] = [
                    'm_num' => $m,
                    'm_name' => date('F', mktime(0, 0, 0, (int)$m, 10))
                ];
            }
        }
    } 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/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="assets/css/semi-dark.css" rel="stylesheet" />
    <link href="assets/css/header-colors.css" rel="stylesheet" />
    
    <link href="assets/plugins/select2/css/select2.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="assets/plugins/select2/css/select2-bootstrap4.css" />

    <title>Archived Salary Reports - UTCPL</title>
    
    <style>
        .mode-card { cursor: pointer; transition: all 0.2s ease-in-out; border: 1px solid #dee2e6; background-color: #fff; padding: 20px; }
        .mode-card:hover { border-color: #0056b3; background-color: #f8f9fa; }
        .mode-card.active { border: 2px solid #0056b3; background-color: #f0f7ff; position: relative; }
        .mode-card.active::after { content: "\F26E"; font-family: "bootstrap-icons"; position: absolute; top: 10px; right: 15px; color: #0056b3; font-size: 1.2rem; }
    </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 Archives</div>
                <div class="ps-3">
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb mb-0 p-0">
                            <li class="breadcrumb-item"><a href="dashboard.php"><i class="bx bx-home-alt"></i></a></li>
                            <li class="breadcrumb-item active" aria-current="page">View Previous Sheets</li>
                        </ol>
                    </nav>
                </div>
            </div>
            <hr/>

            <div class="row">
                <div class="col-xl-9 mx-auto"> 
                    <div class="card border-top border-0 border-4 border-primary shadow-sm">
                        <div class="card-body p-5">
                            
                            <form action="previous-salary-router.php" method="post">
                                <input type="hidden" name="report_category" id="report_category" value="main">

                                <h6 class="mb-3 text-uppercase fw-bold text-primary">Step 1: Select Report Category</h6>
                                <div class="row g-3 mb-4"> 
                                    <div class="col-md-6">
                                        <div class="card shadow-none rounded mode-card active" onclick="setCategory('main', this)">
                                            <div class="d-flex align-items-center">
                                                <div class="fs-2 text-primary me-3"><i class="bi bi-cash-stack"></i></div>
                                                <div>
                                                    <h6 class="mb-0 fw-bold">Main Salary</h6>
                                                    <small class="text-muted d-block">Gross, Bank, Cheque, Hold</small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="card shadow-none rounded mode-card" onclick="setCategory('ot', this)">
                                            <div class="d-flex align-items-center">
                                                <div class="fs-2 text-warning me-3"><i class="bi bi-clock-history"></i></div>
                                                <div>
                                                    <h6 class="mb-0 fw-bold">Overtime (OT)</h6>
                                                    <small class="text-muted d-block">OT Gross, Bank, Cheque, Hold</small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="mb-4">
                                    <label class="form-label fw-bold">Step 2: Sheet Type</label>
                                    <select class="form-select single-select" name="sheet_type" id="sheet_type" required>
                                        <option value="">-- Choose Sheet --</option>
                                        </select>
                                </div>

                                <div class="row mb-4">
                                    <div class="col-md-6">
                                        <label class="form-label fw-bold">Step 3: Select Year</label>
                                        <select class="form-select" name="year" id="u_year" onchange="fetchMonths()" required>
                                            <option value="">Loading years...</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label fw-bold">Step 4: Select Month</label>
                                        <select class="form-select" name="month" id="u_month" required disabled>
                                            <option value="">Select Year First</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="d-grid">
                                    <button type="submit" name="view_report" id="btn_submit" class="btn btn-primary btn-lg shadow-sm" style="background-color: #0056b3; border-color: #0056b3;" disabled>
                                        <i class="bx bx-search-alt me-2"></i>Fetch Archived Data
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php include 'system/footer.php'; ?>
    
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/plugins/select2/js/select2.min.js"></script>

    <script>
        const main_options = `
            <option value="salary_gross">Old Salary Gross Sheet</option>
            <option value="salary_bank">Old Salary Bank Sheet</option>
            <option value="salary_cheque">Old Salary Cheque Sheet</option>
            <option value="salary_hold">Old Salary Hold Sheet</option>`;
        
        const ot_options = `
            <option value="ot_gross">Old OT Gross Sheet</option>
            <option value="ot_bank">Old OT Bank Sheet</option>
            <option value="ot_cheque">Old OT Cheque Sheet</option>
            <option value="ot_hold">Old OT Hold Sheet</option>`;

        $(document).ready(function() {
            $('.single-select').select2({ theme: 'bootstrap4', width: '100%' });
            setCategory('main', $('.mode-card').first()[0]);
            fetchInitialYears();
        });

        function setCategory(cat, element) {
            $('.mode-card').removeClass('active');
            $(element).addClass('active');
            $('#report_category').val(cat);
            $('#sheet_type').html(cat === 'main' ? main_options : ot_options).trigger('change');
        }

        function fetchInitialYears() {
            $.post('previous-salary.php', { ajax_action: 'get_archive_dates' }, function(data) {
                let html = '<option value="">--- Select Year ---</option>';
                if(data.years.length > 0) {
                    data.years.forEach(y => { html += `<option value="${y}">${y}</option>`; });
                }
                $('#u_year').html(html);
            }, 'json');
        }

        function fetchMonths() {
            let yr = $('#u_year').val();
            if(!yr) {
                $('#u_month').prop('disabled', true).html('<option>Select Year First</option>');
                $('#btn_submit').prop('disabled', true);
                return;
            }
            $.post('previous-salary.php', { ajax_action: 'get_archive_dates', selected_year: yr }, function(data) {
                let html = '<option value="">--- Select Month ---</option>';
                data.months.forEach(m => { html += `<option value="${m.m_num}">${m.m_name}</option>`; });
                $('#u_month').html(html).prop('disabled', false);
                $('#btn_submit').prop('disabled', false);
            }, 'json');
        }
    </script>
</div>
</body>
</html>