<?php
// advance-emp-ledger.php
session_start();

// 1. Security Check
if(empty($_SESSION['branch']) || $_SESSION['branch'] == ''){
    header("Location: index.php");
    die();
}

require_once 'system/conn.php';
require_once 'system/helper.php'; 

// =============================================================
//  2. AJAX HANDLER: Fetch Employee Ledger
// =============================================================
if(isset($_POST['action']) && $_POST['action'] == 'fetch_ledger' && isset($_POST['e_id'])) {
    
    if(ob_get_length()) ob_clean();

    $e_id = $_POST['e_id'];
    $branch = $_SESSION['branch'];

    // Security Check
    $check = validateEmployeeScope($conn, $e_id, $branch);

    if($check['status'] !== 'valid') {
        echo '<div class="alert alert-danger">'.$check['message'].'</div>';
        exit;
    }

    // Fetch Advance History
    $sql = "SELECT * FROM advance WHERE e_id = ? AND branch = ? ORDER BY date DESC, adv_id DESC";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$e_id, $branch]);
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if(count($result) > 0) {
        $total_taken = 0;
        $total_paid = 0;
        ?>
        <div class="mt-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0 text-primary text-uppercase">
                    <i class="bi bi-person-lines-fill"></i> Ledger: <?php echo $check['emp_name']; ?> 
                    <small class="text-muted text-lowercase">(<?php echo $e_id; ?>)</small>
                </h5>
                <button onclick="window.print()" class="btn btn-outline-primary btn-sm d-print-none">
                    <i class="bi bi-printer"></i> Print Ledger
                </button>
            </div>

            <div class="table-responsive">
                <table class="table table-striped table-bordered align-middle">
                    <thead class="table-dark">
                        <tr>
                            <th>Date</th>
                            <th>Description</th>
                            <th class="text-end">Advance Taken (+)</th>
                            <th class="text-end">Deducted/Paid (-)</th>
                            <th class="text-end">Balance</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        foreach($result as $row) {
                            $date = date('d-M-Y', strtotime($row['date']));
                            
                            $taken = 0;
                            $deducted = 0;
                            $desc = "Advance Issued"; 

                            if($row['manual_balance'] > 0) {
                                $deducted = $row['manual_balance'];
                                $desc = "Repayment / Salary Ded.";
                            } else {
                                $taken = $row['amount'];
                            }

                            $total_taken += $taken;
                            $total_paid += $deducted;
                        ?>
                        <tr>
                            <td><?php echo $date; ?></td>
                            <td><?php echo $desc; ?></td>
                            <td class="text-end text-danger fw-bold">
                                <?php echo ($taken > 0) ? number_format($taken) : '-'; ?>
                            </td>
                            <td class="text-end text-success fw-bold">
                                <?php echo ($deducted > 0) ? number_format($deducted) : '-'; ?>
                            </td>
                            <td class="text-end fw-bold text-primary">
                                <?php echo number_format($row['remaining_amount']); ?>
                            </td>
                        </tr>
                        <?php } ?>
                    </tbody>
                    <tfoot class="bg-light">
                        <tr class="fw-bold">
                            <td colspan="2" class="text-end text-uppercase">Totals:</td>
                            <td class="text-end text-danger"><?php echo number_format($total_taken); ?></td>
                            <td class="text-end text-success"><?php echo number_format($total_paid); ?></td>
                            <td></td> 
                        </tr>
                    </tfoot>
                </table>
            </div>
            
            <div class="d-none d-print-block mt-4 text-center text-muted">
                <small>Generated on <?php echo date('d-M-Y H:i'); ?> | Utkal Team Care</small>
            </div>
        </div>
        <?php
    } else {
        echo '<div class="alert alert-light border mt-4 text-center text-primary">
                <i class="bi bi-info-circle-fill font-22 d-block mb-2"></i>
                No advance history found for <strong>'.$check['emp_name'].'</strong>.
              </div>';
    }
    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" />
    <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 rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />

    <style>
        /* Print Styles - Hides everything except the ledger card content */
        @media print {
            .sidebar-wrapper, .top-header, .page-breadcrumb, .search-container, .d-print-none, footer {
                display: none !important;
            }
            .page-content-wrapper {
                margin: 0 !important;
                padding: 0 !important;
            }
            .page-content {
                padding: 0 !important;
            }
            .card {
                border: none !important;
                box-shadow: none !important;
            }
            .card-body {
                padding: 0 !important;
            }
        }
    </style>

    <title>Employee Advance Ledger</title>
  </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">Advance Ledger</div>
              <div class="ms-auto"></div>
            </div>
            
            <hr/>
            
            <div class="card">
              <div class="card-body">
                <div class="p-4 border rounded">
                  
                    <div class="row mb-3 search-container">
                        <div class="col-md-8 mx-auto">
                            <label class="form-label text-primary fw-bold">Search Employee:</label>
                            
                            <select class="form-select single-select" id="emp_selector" data-placeholder="Type Name or ID to Search...">
                                <option></option>
                                <?php 
                                $stmt = $conn->prepare("SELECT e_id, e_name FROM emp_details WHERE branch = ? AND status = '1' ORDER BY e_name ASC");
                                $stmt->execute([$_SESSION['branch']]);
                                while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                ?>
                                    <option value="<?php echo $row['e_id']; ?>">
                                        <?php echo $row['e_name'] . " (" . $row['e_id'] . ")"; ?>
                                    </option>
                                <?php } ?>
                            </select>
                            
                        </div>
                    </div>

                    <div id="ledger-result"></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>
    $(document).ready(function() {
        
        // Initialize Select2 with Bootstrap 5 Theme
        $('.single-select').select2({
            theme: "bootstrap-5",
            width: '100%',
            placeholder: $(this).data('placeholder'),
            allowClear: true
        });

        // Trigger AJAX on Selection Change
        $('#emp_selector').on('change', function() {
            var e_id = $(this).val();
            
            if(e_id) {
                $('#ledger-result').html('<div class="text-center mt-5"><div class="spinner-border text-primary" role="status"></div><p class="mt-2 text-primary">Fetching Ledger...</p></div>');
                
                $.ajax({
                    url: window.location.href,
                    type: "POST",
                    data: { action: 'fetch_ledger', e_id: e_id },
                    success: function(response) {
                        $('#ledger-result').html(response);
                    },
                    error: function(xhr, status, error) {
                        $('#ledger-result').html('<div class="alert alert-danger">Error: ' + error + '</div>');
                    }
                });
            } else {
                $('#ledger-result').html('');
            }
        });
    });
    </script>

  </body>
</html>