<?php
ob_start(); 
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 Advance History
// =============================================================
if(isset($_POST['action']) && $_POST['action'] == 'fetch_history' && isset($_POST['e_id'])) {
    
    if(ob_get_length()) ob_clean(); // Ensure clean output

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

    // Validate Employee
    $check = validateEmployeeScope($conn, $e_id, $branch);

    if($check['status'] !== 'valid') {
        echo '<div class="alert alert-warning mt-3">
                <div class="d-flex align-items-center">
                    <div class="font-24"><i class="bi bi-shield-lock-fill"></i></div>
                    <div class="ms-2">
                        <h6 class="mb-0">Security Alert</h6>
                        <div>'. $check['message'] .'</div>
                    </div>
                </div>
              </div>';
        exit;
    }

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

    if(count($history) > 0) {
        $total_taken = 0;
        
        echo '<div class="table-responsive mt-3">';
        echo '<h6 class="mb-2 text-uppercase text-secondary">Advance Ledger</h6>';
        echo '<table class="table table-bordered table-striped table-hover">';
        echo '<thead class="table-dark"><tr><th>Date</th><th>Amount Taken</th><th>Balance (After)</th></tr></thead>';
        echo '<tbody>';
        
        foreach($history as $row) {
            $total_taken += $row['amount'];
            $nice_date = date("d-M-Y", strtotime($row['date']));
            
            echo "<tr>";
            echo "<td>" . $nice_date . "</td>";
            echo "<td class='text-danger fw-bold'>" . number_format($row['amount']) . "</td>";
            echo "<td class='text-success fw-bold'>" . number_format($row['remaining_amount']) . "</td>";
            echo "</tr>";
        }
        
        // Total Row
        echo '<tr class="table-light fw-bold">';
        echo '<td>TOTAL</td>';
        echo '<td class="text-danger">' . number_format($total_taken) . '</td>';
        echo '<td></td>'; 
        echo '</tr>';

        echo '</tbody></table></div>';
    } else {
        echo '<div class="alert alert-info mt-3"><i class="bi bi-info-circle"></i> No advance history found.</div>';
    }
    exit; 
}

// =============================================================
//  3. FORM SUBMISSION LOGIC
// =============================================================
$message = "";

if(isset($_POST["submit"])){
    
    $e_id   = $_POST['ename'];
    $amount = $_POST['amount'];
    $date   = $_POST['date'];
    
    $year  = date('Y', strtotime($date));
    $month = date('m', strtotime($date));
    
    $branch = $_SESSION['branch'];
    $manual_balance = 0;
    $status = 1;

    // Validation
    $check = validateEmployeeScope($conn, $e_id, $branch);
    
    if($check['status'] !== 'valid') {
        $message = "<div class='alert alert-danger border-0 bg-danger alert-dismissible fade show py-2'>
                        <div class='d-flex align-items-center'>
                            <div class='font-35 text-white'><i class='bi bi-lock-fill'></i></div>
                            <div class='ms-3'>
                                <h6 class='mb-0 text-white'>Transaction Blocked</h6>
                                <div class='text-white'>". $check['message'] ."</div>
                            </div>
                        </div>
                        <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
                    </div>";
    } else {
        // Get Previous Balance
        $sql_prev = "SELECT remaining_amount FROM `advance` WHERE e_id = ? AND branch = ? ORDER BY adv_id DESC LIMIT 1";
        $sth = $conn->prepare($sql_prev);
        $sth->execute([$e_id, $branch]);
        $row = $sth->fetch(PDO::FETCH_ASSOC);

        $current_balance = ($row && isset($row['remaining_amount'])) ? $row['remaining_amount'] : 0;
        $remaining_amount = $current_balance + $amount;

        // Insert New Advance
        $query = "INSERT INTO `advance` 
                  (`e_id`, `amount`, `date`, `month`, `year`, `manual_balance`, `remaining_amount`, `branch`, `status`) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
                  
        $stmt = $conn->prepare($query);
        $result = $stmt->execute([
            $e_id, $amount, $date, $month, $year, $manual_balance, $remaining_amount, $branch, $status
        ]);

        if($result){
            $emp_display = $check['emp_name'] ?? $e_id;
            
            $message = "<div class='alert alert-success border-0 bg-success alert-dismissible fade show py-2'>
                            <div class='d-flex align-items-center'>
                                <div class='font-35 text-white'><i class='bi bi-check-circle-fill'></i></div>
                                <div class='ms-3'>
                                    <h6 class='mb-0 text-white'>Success!</h6>
                                    <div class='text-white'>Advance issued to <b>$emp_display</b>. New Balance: <strong>$remaining_amount</strong></div>
                                </div>
                            </div>
                            <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
                        </div>";      
        } else {
            $message = "<div class='alert alert-danger border-0 bg-danger alert-dismissible fade show py-2'>
                            <div class='d-flex align-items-center'>
                                <div class='font-35 text-white'><i class='bi bi-x-circle-fill'></i></div>
                                <div class='ms-3'>
                                    <h6 class='mb-0 text-white'>Error!</h6>
                                    <div class='text-white'>Database insertion failed.</div>
                                </div>
                            </div>
                            <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
                        </div>";
        }
    }
} 
?>
<!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>Issue Advance</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">Issue Advance</div>
            <div class="ms-auto"></div>
          </div>
            
            <div id="alert-container">
                <?php echo $message; ?>
            </div>
            
            <hr/>
            <div class="card">
              <div class="card-body">
                <div class="p-4 border rounded">
                  <form method="POST" enctype="multipart/form-data" action="">
                                               
                    <div class="row mb-3">
                      <div class="col-md-4 col-sm-12">
                        <h6>Employee Name :</h6>
                        <div class="input-field">
                            <input list="brow" id="ename" class="form-control" name="ename" required autocomplete="off" placeholder="Type to search...">
                            <datalist id="brow">
                            <?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'];?></option>
                            <?php } ?>
                            </datalist>  
                        </div>
                      </div>

                      <div class="col-md-4 col-sm-12">
                        <h6>Amount :</h6>
                        <div class="input-field">
                          <input type="number" class="form-control" name="amount" required>
                        </div>
                      </div>

                      <div class="col-md-4 col-sm-12">
                        <h6>Date :</h6>
                        <div class="input-field">
                          <input type="date" class="form-control" name="date" value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                      </div>
                    </div>
                        
                    <div class="row mb-3">                       
                      <div class="col-12">
                        <button class="btn btn-primary" type="submit" name="submit" value="submit" >Issue Advance</button>
                      </div>
                    </div>
                  </form>
                  
                  <div id="ledger_display"></div>

                </div>
              </div>
            </div>
                
          </div>
        </div>
      </div>
    </div>
    
    <script>
    $(document).ready(function() {
        
        // Fetch History on Employee Selection
        $('#ename').on('change', function() {
            var e_id = this.value;
            
            if(e_id){
                $("#ledger_display").html('<div class="text-center p-3"><div class="spinner-border text-primary" role="status"></div><br>Loading history...</div>');
                
                $.ajax({
                    url: window.location.href, 
                    type: "POST",
                    data: { e_id: e_id, action: 'fetch_history' },
                    success: function(result){
                        $("#ledger_display").html(result);
                    },
                    error: function(xhr, status, error) {
                        $("#ledger_display").html('<div class="alert alert-danger">Error fetching history.</div>');
                    }
                });
            } else {
                $("#ledger_display").html('');
            }
        });

        // Auto-Hide Alerts
        window.setTimeout(function() {
            $(".alert").fadeTo(500, 0).slideUp(500, function(){
                $(this).remove(); 
            });
        }, 4000);
    });
    </script>

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