<?php
session_start();
if(!isset($_SESSION['username'])) {
    header("Location: ../login.php");
    exit();
}

include('../includes/db.php');

$supplier_id = isset($_GET['id']) ? mysqli_real_escape_string($conn, $_GET['id']) : 0;
$from_date = isset($_GET['from_date']) ? $_GET['from_date'] : date('Y-m-01');
$to_date = isset($_GET['to_date']) ? $_GET['to_date'] : date('Y-m-d');

$supplier_sql = "SELECT * FROM suppliers WHERE id='$supplier_id'";
$supplier_result = mysqli_query($conn, $supplier_sql);
$supplier = mysqli_fetch_assoc($supplier_result);
if(!$supplier) { header("Location: suppliers.php"); exit(); }

// ============================================
// GET ALL PURCHASES (Fuel Purchases)
// ============================================
$purchases_sql = "SELECT p.*, f.name as fuel_name 
                  FROM purchases p 
                  LEFT JOIN fuel_types f ON p.fuel_type_id = f.id 
                  WHERE p.supplier_id='$supplier_id' 
                  AND DATE(p.date_time) BETWEEN '$from_date' AND '$to_date' 
                  ORDER BY p.date_time ASC";
$purchases_result = mysqli_query($conn, $purchases_sql);

// ============================================
// GET ALL SUPPLIER PAYMENTS (Excluding purchase auto-entries)
// ============================================
$payments_sql = "SELECT * FROM supplier_payments 
                 WHERE supplier_id='$supplier_id' 
                 AND DATE(date_time) BETWEEN '$from_date' AND '$to_date' 
                 AND (payment_method IS NULL OR payment_method NOT IN ('purchase', 'opening_balance'))
                 ORDER BY date_time ASC";
$payments_result = mysqli_query($conn, $payments_sql);

// ============================================
// GET LUBE PURCHASES (If any)
// ============================================
$lube_purchases_sql = "SELECT lp.*, s.name as supplier_name 
                       FROM lube_purchases lp
                       LEFT JOIN suppliers s ON lp.supplier_id = s.id
                       WHERE lp.supplier_id='$supplier_id' 
                       AND DATE(lp.purchase_date) BETWEEN '$from_date' AND '$to_date'
                       ORDER BY lp.purchase_date ASC";
$lube_purchases_result = mysqli_query($conn, $lube_purchases_sql);

// ============================================
// CALCULATE TOTALS
// ============================================
$total_purchases = 0; 
$total_lube_purchases = 0;
$total_payments = 0;

// Fuel Purchases Total
mysqli_data_seek($purchases_result, 0);
while($row = mysqli_fetch_assoc($purchases_result)) { 
    $total_purchases += $row['total_amount']; 
} 
mysqli_data_seek($purchases_result, 0);

// Lube Purchases Total
mysqli_data_seek($lube_purchases_result, 0);
while($row = mysqli_fetch_assoc($lube_purchases_result)) { 
    $total_lube_purchases += $row['total_amount']; 
} 
mysqli_data_seek($lube_purchases_result, 0);

// Payments Total
mysqli_data_seek($payments_result, 0);
while($row = mysqli_fetch_assoc($payments_result)) { 
    $total_payments += $row['amount']; 
} 
mysqli_data_seek($payments_result, 0);

$total_all_purchases = $total_purchases + $total_lube_purchases;
$closing_balance = $supplier['current_balance'];
?>

<?php include('../includes/log.php'); ?>
<?php include('../includes/sd.php'); ?>

<div class="supplier-ledger-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-book"></i> Supplier Ledger</h2>
            <p>Transaction history for <?php echo htmlspecialchars($supplier['name']); ?></p>
        </div>
        <div class="header-right">
            <div class="stats-badge">
                <i class="fas fa-chart-line"></i>
                <span>Balance: Rs <?php echo number_format($closing_balance, 2); ?></span>
            </div>
        </div>
    </div>

    <!-- Filter Card -->
    <div class="filter-card">
        <div class="filter-card-header">
            <i class="fas fa-filter"></i>
            <h4>Filter Transactions</h4>
        </div>
        <div class="filter-card-body">
            <form method="GET" action="" id="filterForm">
                <input type="hidden" name="id" value="<?php echo $supplier_id; ?>">
                <div class="filter-grid">
                    <div class="filter-field">
                        <label><i class="fas fa-calendar-alt"></i> From Date</label>
                        <input type="date" name="from_date" class="modern-input" value="<?php echo $from_date; ?>">
                    </div>
                    <div class="filter-field">
                        <label><i class="fas fa-calendar-alt"></i> To Date</label>
                        <input type="date" name="to_date" class="modern-input" value="<?php echo $to_date; ?>">
                    </div>
                    <div class="filter-actions">
                        <button type="submit" class="btn-primary-custom">
                            <i class="fas fa-search"></i> Filter
                        </button>
                        <a href="supplier_ledger.php?id=<?php echo $supplier_id; ?>" class="btn-secondary-custom">
                            <i class="fas fa-sync-alt"></i> Reset
                        </a>
                        <button type="button" onclick="printLedger()" class="btn-print-custom">
                            <i class="fas fa-print"></i> Print / PDF
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Supplier Info Banner -->
    <div class="supplier-info-banner">
        <div class="supplier-icon">
            <i class="fas fa-truck"></i>
        </div>
        <div class="supplier-details">
            <h3><?php echo htmlspecialchars($supplier['name']); ?></h3>
            <div class="supplier-meta">
                <span class="info-tag"><i class="fas fa-user"></i> <?php echo htmlspecialchars($supplier['contact_person'] ?: 'N/A'); ?></span>
                <span class="info-tag"><i class="fas fa-phone"></i> <?php echo htmlspecialchars($supplier['phone']); ?></span>
                <span class="info-tag"><i class="fas fa-envelope"></i> <?php echo htmlspecialchars($supplier['email'] ?: 'N/A'); ?></span>
            </div>
        </div>
        <div class="supplier-balance">
            <span class="balance-label">Current Balance</span>
            <span class="balance-value <?php echo $closing_balance > 0 ? 'debit' : 'credit'; ?>">
                Rs <?php echo number_format(abs($closing_balance), 2); ?>
                <?php echo $closing_balance > 0 ? 'Dr' : 'Cr'; ?>
            </span>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="summary-cards">
        <div class="summary-card">
            <div class="summary-icon purchase-icon">
                <i class="fas fa-shopping-cart"></i>
            </div>
            <div class="summary-content">
                <h4>Rs <?php echo number_format($total_all_purchases, 2); ?></h4>
                <p>Total Purchases</p>
                <small>Fuel + Lube Purchases</small>
            </div>
        </div>
        <div class="summary-card">
            <div class="summary-icon payment-icon">
                <i class="fas fa-hand-holding-usd"></i>
            </div>
            <div class="summary-content">
                <h4>Rs <?php echo number_format($total_payments, 2); ?></h4>
                <p>Total Payments</p>
                <small>Amount paid to supplier</small>
            </div>
        </div>
        <div class="summary-card">
            <div class="summary-icon balance-icon">
                <i class="fas fa-balance-scale"></i>
            </div>
            <div class="summary-content">
                <h4 class="<?php echo $closing_balance > 0 ? 'debit-text' : 'credit-text'; ?>">
                    Rs <?php echo number_format(abs($closing_balance), 2); ?>
                    <small><?php echo $closing_balance > 0 ? 'Dr' : 'Cr'; ?></small>
                </h4>
                <p>Net Payable</p>
                <small>Outstanding balance</small>
            </div>
        </div>
    </div>

    <!-- Transaction History Table -->
    <div class="ledger-table-container">
        <div class="table-header-bar">
            <div class="table-title">
                <i class="fas fa-list-ul"></i>
                <h4>Transaction History</h4>
            </div>
            <div class="table-search-bar">
                <i class="fas fa-search"></i>
                <input type="text" id="tableSearch" placeholder="Search transactions..." class="search-field">
            </div>
        </div>
        <div class="table-wrapper">
            <table class="ledger-table" id="ledgerTable">
                <thead>
                    <tr>
                        <th width="5%">#</th>
                        <th width="15%">Date</th>
                        <th width="35%">Description</th>
                        <th width="10%">Type</th>
                        <th width="15%">Credit (Rs)</th>
                        <th width="15%">Debit (Rs)</th>
                        <th width="15%">Balance (Rs)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // ============================================
                    // COLLECT ALL TRANSACTIONS WITH CORRECT ORDER
                    // ============================================
                    
                    $running_balance = $supplier['opening_balance'];
                    $counter = 1;
                    $all_transactions = [];
                    
                    // Opening balance
                    $all_transactions[] = [
                        'date' => $supplier['date_time'],
                        'date_obj' => strtotime($supplier['date_time']),
                        'description' => '<strong>Opening Balance</strong>',
                        'type' => 'Opening',
                        'type_class' => 'opening',
                        'type_icon' => 'fa-chart-line',
                        'debit' => $supplier['opening_balance'],
                        'credit' => 0,
                        'is_opening' => true
                    ];
                    
                    // Add Fuel Purchases
                    mysqli_data_seek($purchases_result, 0);
                    while($p = mysqli_fetch_assoc($purchases_result)) { 
                        $fuel_name = isset($p['fuel_name']) ? $p['fuel_name'] : 'Fuel';
                        $all_transactions[] = [
                            'date' => $p['date_time'],
                            'date_obj' => strtotime($p['date_time']),
                            'description' => 'Fuel Purchase - ' . number_format($p['quantity'],2) . 'L @ Rs ' . number_format($p['rate'],2) . '/L (DO: ' . $p['do_number'] . ')',
                            'type' => 'Purchase',
                            'type_class' => 'purchase',
                            'type_icon' => 'fa-shopping-cart',
                            'debit' => $p['total_amount'],
                            'credit' => 0,
                            'is_opening' => false
                        ]; 
                    }
                    
                    // Add Lube Purchases
                    mysqli_data_seek($lube_purchases_result, 0);
                    while($lp = mysqli_fetch_assoc($lube_purchases_result)) { 
                        $all_transactions[] = [
                            'date' => $lp['purchase_date'],
                            'date_obj' => strtotime($lp['purchase_date']),
                            'description' => 'Lube Purchase - Invoice: ' . $lp['purchase_invoice'] . ' (Total: Rs ' . number_format($lp['total_amount'],2) . ')',
                            'type' => 'Purchase',
                            'type_class' => 'purchase',
                            'type_icon' => 'fa-shopping-cart',
                            'debit' => $lp['total_amount'],
                            'credit' => 0,
                            'is_opening' => false
                        ]; 
                    }
                    
                    // Add Payments
                    mysqli_data_seek($payments_result, 0);
                    while($pay = mysqli_fetch_assoc($payments_result)) { 
                        $all_transactions[] = [
                            'date' => $pay['date_time'],
                            'date_obj' => strtotime($pay['date_time']),
                            'description' => 'Payment' . ($pay['notes'] ? ' (' . $pay['notes'] . ')' : ''),
                            'type' => 'Payment',
                            'type_class' => 'payment',
                            'type_icon' => 'fa-money-bill-wave',
                            'debit' => 0,
                            'credit' => $pay['amount'],
                            'is_opening' => false
                        ]; 
                    }
                    
                    // Sort by date (oldest first)
                    usort($all_transactions, function($a, $b) {
                        return $a['date_obj'] - $b['date_obj'];
                    });
                    
                    // Display transactions
                    foreach($all_transactions as $t) {
                        $row_class = $t['type'] == 'Purchase' ? 'purchase-row' : ($t['type'] == 'Payment' ? 'payment-row' : 'opening-row');
                        
                        if(!$t['is_opening']) {
                            $running_balance += $t['debit'] - $t['credit'];
                        }
                        ?>
                        <tr class="<?php echo $row_class; ?>">
                            <td data-label="#"><?php echo $counter++; ?></td>
                            <td data-label="Date"><?php echo date('d-m-Y H:i', strtotime($t['date'])); ?></td>
                            <td data-label="Description"><?php echo $t['description']; ?></td>
                            <td data-label="Type">
                                <span class="trans-badge <?php echo $t['type_class']; ?>">
                                    <i class="fas <?php echo $t['type_icon']; ?>"></i>
                                    <?php echo $t['type']; ?>
                                </span>
                            </td>
                            <td data-label="Debit" class="debit-amount">
                                <?php echo $t['debit'] > 0 ? 'Rs ' . number_format($t['debit'], 2) : '-'; ?>
                            </td>
                            <td data-label="Credit" class="credit-amount">
                                <?php echo $t['credit'] > 0 ? 'Rs ' . number_format($t['credit'], 2) : '-'; ?>
                            </td>
                            <td data-label="Balance" class="balance-cell <?php echo $running_balance > 0 ? 'credit-balance' : 'debit-balance'; ?>">
                                <span class="balance-indicator">
                                    <i class="fas fa-chevron-<?php echo $running_balance > 0 ? 'up' : 'down'; ?>"></i>
                                    Rs <?php echo number_format(abs($running_balance), 2); ?>
                                    <?php echo $running_balance > 0 ? 'Cr' : 'Dr'; ?>
                                </span>
                            </td>
                        </tr>
                        <?php
                    }
                    
                    if($counter == 1) { 
                        ?>
                        <tr class="empty-row">
                            <td colspan="7">
                                <div class="empty-transactions">
                                    <i class="fas fa-exchange-alt"></i>
                                    <p>No transactions found</p>
                                    <small>Try changing the date range</small>
                                </div>
                            </td>
                        </tr>
                        <?php 
                    } 
                    ?>
                </tbody>
                <tfoot>
                    <tr class="totals-row">
                        <td colspan="4"><strong>GRAND TOTALS</strong></td>
                        <td class="debit-amount"><strong>Rs <?php echo number_format($total_all_purchases, 2); ?></strong></td>
                        <td class="credit-amount"><strong>Rs <?php echo number_format($total_payments, 2); ?></strong></td>
                        <td class="balance-cell <?php echo $closing_balance > 0 ? 'credit-balance' : 'debit-balance'; ?>">
                            <strong>Rs <?php echo number_format(abs($closing_balance), 2); ?> <?php echo $closing_balance > 0 ? 'Cr' : 'Dr'; ?></strong>
                        </td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>

    <!-- Back Button -->
    <div class="back-button">
        <a href="suppliers.php" class="btn-back-custom">
            <i class="fas fa-arrow-left"></i> Back to Suppliers
        </a>
    </div>
</div>

<!-- Print Template (Hidden) -->
<div id="printTemplate" style="display: none;">
    <div class="print-container">
        <div class="print-header">
            <div class="print-logo">
                <img src="../assets/logo.jpeg" alt="Logo" class="print-logo-img" onerror="this.style.display='none'">
                <div class="print-title">
                    <h1>ALFATEH PETROLEUM SERVICE</h1>
                    <p>Complete Fuel Station Management Solution</p>
                    <p class="print-address">Tando Muhammad Khan | Ashok: 03008378775</p>
                </div>
            </div>
        </div>
        
        <div class="print-report-title">
            <h2>SUPPLIER LEDGER STATEMENT</h2>
        </div>
        
        <div class="print-supplier-info">
            <div class="print-info-row">
                <div class="print-info-label">Supplier Name:</div>
                <div class="print-info-value"><strong><?php echo htmlspecialchars($supplier['name']); ?></strong></div>
            </div>
            <div class="print-info-row">
                <div class="print-info-label">Contact Person:</div>
                <div class="print-info-value"><?php echo htmlspecialchars($supplier['contact_person'] ?: 'N/A'); ?></div>
            </div>
            <div class="print-info-row">
                <div class="print-info-label">Phone:</div>
                <div class="print-info-value"><?php echo htmlspecialchars($supplier['phone']); ?></div>
            </div>
            <div class="print-info-row">
                <div class="print-info-label">Email:</div>
                <div class="print-info-value"><?php echo htmlspecialchars($supplier['email'] ?: 'N/A'); ?></div>
            </div>
            <div class="print-info-row">
                <div class="print-info-label">Address:</div>
                <div class="print-info-value"><?php echo htmlspecialchars($supplier['address'] ?: 'N/A'); ?></div>
            </div>
            <div class="print-info-row">
                <div class="print-info-label">Opening Balance:</div>
                <div class="print-info-value">Rs <?php echo number_format($supplier['opening_balance'], 2); ?></div>
            </div>
            <div class="print-info-row">
                <div class="print-info-label">Current Balance:</div>
                <div class="print-info-value <?php echo $closing_balance > 0 ? 'print-credit' : 'print-debit'; ?>">
                    Rs <?php echo number_format(abs($closing_balance), 2); ?> <?php echo $closing_balance > 0 ? 'Cr' : 'Dr'; ?>
                </div>
            </div>
        </div>
        
        <div class="print-summary">
            <div class="print-summary-item">
                <span>Total Purchases:</span>
                <strong>Rs <?php echo number_format($total_all_purchases, 2); ?></strong>
            </div>
            <div class="print-summary-item">
                <span>Total Payments:</span>
                <strong>Rs <?php echo number_format($total_payments, 2); ?></strong>
            </div>
            <div class="print-summary-item">
                <span>Net Balance:</span>
                <strong class="<?php echo $closing_balance > 0 ? 'print-credit' : 'print-debit'; ?>">
                    Rs <?php echo number_format(abs($closing_balance), 2); ?> <?php echo $closing_balance > 0 ? 'Cr' : 'Dr'; ?>
                </strong>
            </div>
        </div>
        
        <div class="print-table">
            <table class="print-transaction-table">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Date</th>
                        <th>DO/Voucher No</th>
                        <th>Description</th>
                        <th>Debit (Rs)</th>
                        <th>Credit (Rs)</th>
                        <th>Balance (Rs)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // Print version with correct order
                    $print_balance = $supplier['opening_balance'];
                    $print_counter = 1;
                    $print_transactions = [];
                    
                    // Opening balance
                    $print_transactions[] = [
                        'date' => $supplier['date_time'],
                        'voucher' => '-',
                        'description' => 'Opening Balance',
                        'debit' => $supplier['opening_balance'],
                        'credit' => 0
                    ];
                    
                    // Fuel Purchases
                    mysqli_data_seek($purchases_result, 0);
                    while($p = mysqli_fetch_assoc($purchases_result)) { 
                        $print_transactions[] = [
                            'date' => $p['date_time'],
                            'voucher' => $p['do_number'],
                            'description' => 'Fuel Purchase - ' . $p['quantity'] . 'L @ Rs ' . number_format($p['rate'],2) . '/L',
                            'debit' => $p['total_amount'],
                            'credit' => 0
                        ]; 
                    }
                    
                    // Lube Purchases
                    mysqli_data_seek($lube_purchases_result, 0);
                    while($lp = mysqli_fetch_assoc($lube_purchases_result)) { 
                        $print_transactions[] = [
                            'date' => $lp['purchase_date'],
                            'voucher' => $lp['purchase_invoice'],
                            'description' => 'Lube Purchase',
                            'debit' => $lp['total_amount'],
                            'credit' => 0
                        ]; 
                    }
                    
                    // Payments
                    mysqli_data_seek($payments_result, 0);
                    while($pay = mysqli_fetch_assoc($payments_result)) { 
                        $print_transactions[] = [
                            'date' => $pay['date_time'],
                            'voucher' => 'PY-' . $pay['id'],
                            'description' => 'Payment' . ($pay['notes'] ? ' (' . $pay['notes'] . ')' : ''),
                            'debit' => 0,
                            'credit' => $pay['amount']
                        ]; 
                    }
                    
                    usort($print_transactions, function($a, $b) { 
                        return strtotime($a['date']) - strtotime($b['date']); 
                    });
                    
                    foreach($print_transactions as $t) {
                        $print_balance += $t['debit'] - $t['credit'];
                        ?>
                        <tr>
                            <td><?php echo $print_counter++; ?></td>
                            <td><?php echo date('d-m-Y H:i', strtotime($t['date'])); ?></td>
                            <td><?php echo $t['voucher']; ?></td>
                            <td><?php echo $t['description']; ?></td>
                            <td class="print-credit"><?php echo $t['credit'] > 0 ? 'Rs ' . number_format($t['credit'], 2) : '-'; ?></td>
                            <td class="print-debit"><?php echo $t['debit'] > 0 ? 'Rs ' . number_format($t['debit'], 2) : '-'; ?></td>
                            <td class="print-balance">Rs <?php echo number_format(abs($print_balance), 2); ?> <?php echo $print_balance > 0 ? 'Cr' : 'Dr'; ?></td>
                        </tr>
                        <?php
                    }
                    ?>
                </tbody>
                <tfoot>
                    <tr class="print-total-row">
                        <td colspan="4"><strong>TOTALS</strong></td>
                        <td class="print-credit"><strong>Rs <?php echo number_format($total_all_purchases, 2); ?></strong></td>
                        <td class="print-debit"><strong>Rs <?php echo number_format($total_payments, 2); ?></strong></td>
                        <td class="print-balance"><strong>Rs <?php echo number_format(abs($closing_balance), 2); ?> <?php echo $closing_balance > 0 ? 'Cr' : 'Dr'; ?></strong></td>
                    </tr>
                </tfoot>
            </table>
        </div>
        
        <div class="print-footer">
            <div class="print-signature">
                <div>_____________________</div>
                <div>Authorized Signature</div>
            </div>
            <div class="print-stamp">
                <div>_____________________</div>
                <div>Company Stamp</div>
            </div>
            <div class="print-date">
                <div>Printed on: <?php echo date('d-m-Y H:i:s'); ?></div>
            </div>
        </div>
        
        <div class="print-footer-note">
            <p>This is a computer generated document and does not require signature.</p>
            <p>&copy; <?php echo date('Y'); ?> ALFATEH PETROLEUM SERVICE - All Rights Reserved</p>
        </div>
    </div>
</div>

<style>
/* Supplier Ledger Page Styles */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');

:root {
    --primary: #A04657;
    --primary-dark: #6b2a36;
    --primary-light: #c96b7e;
    --debit: #dc3545;
    --credit: #28a745;
    --gray-100: #f8f9fc;
    --gray-200: #e9ecef;
    --gray-300: #dee2e6;
    --gray-600: #6c757d;
    --gray-800: #343a40;
}

* {
    font-family: 'Inter', sans-serif;
}

body {
    background: #f0f2f5;
}

h1, h2, h3, h4, h5, h6,
.page-header h2,
.filter-card-header h4,
.table-title h4 {
    font-family: 'Times New Roman', serif;
}

.supplier-ledger-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 20px;
}

/* Page Header */
.page-header {
    background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
    border-radius: 20px;
    padding: 24px 32px;
    margin-bottom: 28px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: white;
    box-shadow: 0 8px 20px rgba(160,70,87,0.25);
}

.page-header h2 {
    margin: 0 0 6px 0;
    font-size: 26px;
    font-weight: 700;
}

.page-header h2 i {
    margin-right: 12px;
}

.page-header p {
    margin: 0;
    font-size: 13px;
    opacity: 0.9;
}

.stats-badge {
    background: rgba(255,255,255,0.2);
    padding: 8px 18px;
    border-radius: 40px;
    font-size: 13px;
    font-weight: 500;
    backdrop-filter: blur(10px);
}

/* Filter Card */
.filter-card {
    background: white;
    border-radius: 20px;
    margin-bottom: 28px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.05);
    overflow: hidden;
}

.filter-card-header {
    background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
    padding: 14px 24px;
    display: flex;
    align-items: center;
    gap: 10px;
    color: white;
}

.filter-card-header i {
    font-size: 18px;
}

.filter-card-header h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
}

.filter-card-body {
    padding: 24px;
}

.filter-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    align-items: end;
}

.filter-field label {
    display: block;
    margin-bottom: 6px;
    font-size: 12px;
    font-weight: 600;
    color: var(--gray-600);
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.filter-field label i {
    margin-right: 6px;
    color: var(--primary);
}

.modern-input {
    width: 100%;
    padding: 10px 14px;
    border: 1.5px solid var(--gray-300);
    border-radius: 12px;
    font-size: 14px;
    transition: all 0.2s;
    background: white;
}

.modern-input:focus {
    border-color: var(--primary);
    outline: none;
    box-shadow: 0 0 0 3px rgba(160,70,87,0.1);
}

.filter-actions {
    display: flex;
    gap: 12px;
}

.btn-primary-custom, .btn-secondary-custom, .btn-print-custom {
    padding: 10px 20px;
    border-radius: 12px;
    font-weight: 600;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.2s;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    text-decoration: none;
    border: none;
}

.btn-primary-custom {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: white;
}

.btn-primary-custom:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(160,70,87,0.3);
}

.btn-secondary-custom {
    background: var(--gray-200);
    color: var(--gray-800);
}

.btn-secondary-custom:hover {
    background: var(--gray-300);
    text-decoration: none;
    color: var(--gray-800);
}

.btn-print-custom {
    background: #6c5ce7;
    color: white;
}

.btn-print-custom:hover {
    background: #5a4ad1;
}

/* Supplier Info Banner */
.supplier-info-banner {
    background: white;
    border-radius: 20px;
    padding: 20px 28px;
    margin-bottom: 28px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 20px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.05);
    border-left: 5px solid var(--primary);
}

.supplier-icon i {
    font-size: 48px;
    color: var(--primary);
    background: rgba(160,70,87,0.1);
    padding: 12px;
    border-radius: 20px;
}

.supplier-details h3 {
    margin: 0 0 8px 0;
    font-size: 20px;
    font-weight: 700;
    color: var(--gray-800);
}

.supplier-meta {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
}

.info-tag {
    font-size: 13px;
    color: var(--gray-600);
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.info-tag i {
    color: var(--primary);
}

.supplier-balance {
    text-align: center;
    padding: 12px 20px;
    background: var(--gray-100);
    border-radius: 16px;
}

.balance-label {
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
    color: var(--gray-600);
    display: block;
    margin-bottom: 4px;
}

.balance-value {
    font-size: 24px;
    font-weight: 800;
}

.balance-value.debit { color: var(--debit); }
.balance-value.credit { color: var(--credit); }

/* Summary Cards */
.summary-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 20px;
    margin-bottom: 28px;
}

.summary-card {
    background: white;
    border-radius: 20px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 18px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    transition: all 0.2s;
}

.summary-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.1);
}

.summary-icon {
    width: 55px;
    height: 55px;
    border-radius: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.summary-icon i {
    font-size: 26px;
}

.purchase-icon { background: rgba(220,53,69,0.1); }
.purchase-icon i { color: var(--debit); }

.payment-icon { background: rgba(40,167,69,0.1); }
.payment-icon i { color: var(--credit); }

.balance-icon { background: rgba(160,70,87,0.1); }
.balance-icon i { color: var(--primary); }

.summary-content h4 {
    margin: 0;
    font-size: 22px;
    font-weight: 800;
    color: var(--gray-800);
}

.summary-content h4 small {
    font-size: 12px;
    font-weight: 500;
}

.summary-content p {
    margin: 4px 0 0;
    font-size: 13px;
    font-weight: 500;
    color: var(--gray-600);
}

.summary-content small {
    font-size: 10px;
    color: var(--gray-600);
}

.debit-text { color: var(--debit); }
.credit-text { color: var(--credit); }

/* Ledger Table Container */
.ledger-table-container {
    background: white;
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0,0,0,0.05);
    margin-bottom: 28px;
}

.table-header-bar {
    padding: 18px 24px;
    border-bottom: 1px solid var(--gray-200);
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
}

.table-title {
    display: flex;
    align-items: center;
    gap: 10px;
}

.table-title i {
    font-size: 20px;
    color: var(--primary);
}

.table-title h4 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
}

.table-search-bar {
    position: relative;
}

.table-search-bar i {
    position: absolute;
    left: 14px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--gray-600);
    font-size: 14px;
}

.search-field {
    padding: 9px 16px 9px 42px;
    border: 1.5px solid var(--gray-300);
    border-radius: 40px;
    width: 260px;
    font-size: 13px;
    transition: all 0.2s;
}

.search-field:focus {
    border-color: var(--primary);
    outline: none;
}

.table-wrapper {
    overflow-x: auto;
}

/* Ledger Table */
.ledger-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 13px;
}

.ledger-table thead th {
    padding: 14px 16px;
    background: var(--gray-100);
    font-weight: 700;
    color: var(--gray-600);
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border-bottom: 2px solid var(--gray-300);
}

.ledger-table tbody td {
    padding: 14px 16px;
    border-bottom: 1px solid var(--gray-200);
    vertical-align: middle;
}

.ledger-table tbody tr:hover td {
    background: #fef8f9;
}

/* Row Styles */
.opening-row {
    background: var(--gray-100);
    font-weight: 600;
}

.purchase-row {
    background: rgba(220,53,69,0.02);
}

.payment-row {
    background: rgba(40,167,69,0.02);
}

.totals-row {
    background: var(--gray-200);
    font-weight: 700;
}

.totals-row td {
    padding: 14px 16px;
}

/* Transaction Badges */
.trans-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 5px 12px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
}

.trans-badge.opening {
    background: var(--gray-200);
    color: var(--gray-600);
}

.trans-badge.purchase {
    background: #dc3545;
    color: white;
}

.trans-badge.payment {
    background: #28a745;
    color: white;
}

/* Amount Cells */
.debit-amount {
    color: var(--debit);
    font-weight: 600;
}

.credit-amount {
    color: var(--credit);
    font-weight: 600;
}

/* Balance Cell */
.balance-cell {
    font-weight: 700;
}

.balance-cell .balance-indicator {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 12px;
}

.debit-balance .balance-indicator {
    background: rgba(220,53,69,0.1);
    color: var(--debit);
}

.credit-balance .balance-indicator {
    background: rgba(40,167,69,0.1);
    color: var(--credit);
}

/* Empty State */
.empty-transactions {
    text-align: center;
    padding: 50px;
}

.empty-transactions i {
    font-size: 56px;
    color: var(--primary);
    opacity: 0.3;
    margin-bottom: 16px;
}

.empty-transactions p {
    font-size: 15px;
    font-weight: 500;
    color: var(--gray-600);
    margin-bottom: 5px;
}

.empty-transactions small {
    font-size: 12px;
    color: var(--gray-600);
}

.empty-row td {
    padding: 0 !important;
}

/* Back Button */
.back-button {
    text-align: center;
}

.btn-back-custom {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    padding: 12px 28px;
    background: var(--gray-200);
    color: var(--gray-800);
    border-radius: 40px;
    text-decoration: none;
    font-weight: 600;
    font-size: 14px;
    transition: all 0.2s;
}

.btn-back-custom:hover {
    background: var(--gray-300);
    text-decoration: none;
    color: var(--gray-800);
}

/* Print Styles */
@media print {
    .filter-card, .table-search-bar, .stats-badge, .btn-print-custom,
    .page-header .header-right, .back-button, .supplier-info-banner,
    .summary-cards, .table-header-bar, .ledger-table-container {
        display: none !important;
    }
    
    .print-container {
        display: block !important;
    }
    
    body {
        background: white;
        margin: 0;
        padding: 0;
    }
}

/* Print Template Styles */
.print-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    background: white;
    font-family: 'Inter', sans-serif;
    display: none;
}

.print-header {
    text-align: center;
    border-bottom: 2px solid #A04657;
    padding-bottom: 15px;
    margin-bottom: 20px;
}

.print-logo {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 20px;
    flex-wrap: wrap;
}

.print-logo-img {
    max-width: 80px;
    max-height: 80px;
    object-fit: contain;
}

.print-title h1 {
    font-family: 'Times New Roman', serif;
    color: #A04657;
    margin: 0;
    font-size: 24px;
}

.print-title p {
    margin: 5px 0;
    color: #666;
    font-size: 12px;
}

.print-address {
    font-size: 11px !important;
}

.print-report-title {
    text-align: center;
    margin-bottom: 20px;
}

.print-report-title h2 {
    font-family: 'Times New Roman', serif;
    color: #333;
    margin: 0 0 5px;
    font-size: 18px;
}

.print-report-title p {
    margin: 3px 0;
    font-size: 12px;
    color: #666;
}

.print-supplier-info {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 20px;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
}

.print-info-row {
    display: flex;
    font-size: 12px;
}

.print-info-label {
    width: 120px;
    font-weight: 600;
    color: #555;
}

.print-info-value {
    flex: 1;
    color: #333;
}

.print-summary {
    display: flex;
    justify-content: space-around;
    background: #e9ecef;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 20px;
    text-align: center;
}

.print-summary-item {
    font-size: 14px;
}

.print-summary-item span {
    display: block;
    color: #666;
    margin-bottom: 5px;
}

.print-summary-item strong {
    font-size: 18px;
}

.print-debit { color: #dc3545; }
.print-credit { color: #28a745; }

.print-table {
    margin-bottom: 20px;
    overflow-x: auto;
}

.print-transaction-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 11px;
}

.print-transaction-table th {
    background: #f8f9fa;
    padding: 10px;
    border: 1px solid #dee2e6;
    font-weight: 600;
    text-align: left;
}

.print-transaction-table td {
    padding: 8px 10px;
    border: 1px solid #dee2e6;
}

.print-total-row {
    background: #f8f9fa;
    font-weight: 600;
}

.print-footer {
    display: flex;
    justify-content: space-between;
    margin: 30px 0 20px;
    padding-top: 20px;
    border-top: 1px solid #dee2e6;
}

.print-signature, .print-stamp, .print-date {
    text-align: center;
    font-size: 10px;
    color: #666;
}

.print-signature div, .print-stamp div {
    margin-bottom: 5px;
}

.print-footer-note {
    text-align: center;
    font-size: 10px;
    color: #999;
    margin-top: 20px;
    padding-top: 10px;
    border-top: 1px dashed #dee2e6;
}

.print-footer-note p {
    margin: 3px 0;
}

/* Responsive */
@media (max-width: 992px) {
    .filter-grid {
        grid-template-columns: 1fr;
    }
    
    .filter-actions {
        flex-direction: row;
    }
    
    .supplier-info-banner {
        flex-direction: column;
        text-align: center;
    }
    
    .supplier-meta {
        justify-content: center;
    }
    
    .summary-cards {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 768px) {
    .supplier-ledger-container {
        padding: 0 12px;
    }
    
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 15px;
    }
    
    .ledger-table thead {
        display: none;
    }
    
    .ledger-table tbody td {
        display: block;
        text-align: right;
        padding-left: 50%;
        position: relative;
        border-bottom: none;
    }
    
    .ledger-table tbody td::before {
        content: attr(data-label);
        position: absolute;
        left: 16px;
        width: 45%;
        text-align: left;
        font-weight: 700;
        font-size: 11px;
        color: var(--gray-600);
    }
    
    .ledger-table tbody tr {
        display: block;
        margin-bottom: 12px;
        border: 1px solid var(--gray-200);
        border-radius: 12px;
        overflow: hidden;
    }
    
    .ledger-table tbody td:last-child {
        border-bottom: none;
    }
}

/* Scrollbar */
::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

::-webkit-scrollbar-track {
    background: var(--gray-200);
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    background: var(--primary);
    border-radius: 10px;
}

/* ===== FIXED PRINT LAYOUT: ensures credit column stays inside table ===== */
@media print {
    /* Override any responsive breakage */
    .print-container,
    .print-table,
    .print-transaction-table {
        overflow: visible !important;
    }
    .print-transaction-table {
        width: 100% !important;
        table-layout: fixed !important;
        border-collapse: collapse !important;
    }
    /* Force all cells to display as table-cell (override mobile block) */
    .print-transaction-table thead tr,
    .print-transaction-table tbody tr,
    .print-transaction-table tfoot tr,
    .print-transaction-table th,
    .print-transaction-table td {
        display: table-row !important;
    }
    .print-transaction-table th,
    .print-transaction-table td {
        display: table-cell !important;
        white-space: normal !important;
        word-break: break-word !important;
        padding: 6px 8px !important;
        text-align: left !important;
    }
    /* Ensure no pseudo-elements appear in print */
    .print-transaction-table td::before {
        content: none !important;
    }
    /* Set column widths to avoid overflow */
    .print-transaction-table th:nth-child(1), .print-transaction-table td:nth-child(1) { width: 5%; }
    .print-transaction-table th:nth-child(2), .print-transaction-table td:nth-child(2) { width: 12%; }
    .print-transaction-table th:nth-child(3), .print-transaction-table td:nth-child(3) { width: 12%; }
    .print-transaction-table th:nth-child(4), .print-transaction-table td:nth-child(4) { width: 32%; }
    .print-transaction-table th:nth-child(5), .print-transaction-table td:nth-child(5) { width: 11%; }
    .print-transaction-table th:nth-child(6), .print-transaction-table td:nth-child(6) { width: 11%; }
    .print-transaction-table th:nth-child(7), .print-transaction-table td:nth-child(7) { width: 17%; }
    /* Prevent page break inside rows */
    .print-transaction-table tr {
        page-break-inside: avoid;
        page-break-after: auto;
    }
    /* Ensure credit/debit colors are visible */
    .print-debit, .print-credit {
        font-weight: bold;
    }
}
</style>

<script>
// Table search functionality
const searchInput = document.getElementById('tableSearch');
if(searchInput) {
    searchInput.addEventListener('keyup', function() {
        let searchValue = this.value.toLowerCase();
        let table = document.getElementById('ledgerTable');
        let rows = table.getElementsByTagName('tr');
        
        for (let i = 2; i < rows.length - 1; i++) {
            let row = rows[i];
            let text = row.textContent.toLowerCase();
            if (text.includes(searchValue)) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        }
    });
}

// Print function with enhanced CSS for credit column fix
function printLedger() {
    var printContents = document.getElementById('printTemplate').innerHTML;
    var originalContents = document.body.innerHTML;
    
    // Create a new window for printing
    var printWindow = window.open('', '_blank');
    printWindow.document.write('<html><head><title>Supplier Ledger - <?php echo htmlspecialchars($supplier['name']); ?></title>');
    printWindow.document.write('<style>');
    printWindow.document.write(`
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Inter', Arial, sans-serif; padding: 20px; background: white; }
        .print-container { max-width: 1200px; margin: 0 auto; }
        .print-header { text-align: center; border-bottom: 2px solid #A04657; padding-bottom: 15px; margin-bottom: 20px; }
        .print-logo { display: flex; align-items: center; justify-content: center; gap: 20px; flex-wrap: wrap; }
        .print-title h1 { font-family: 'Times New Roman', serif; color: #A04657; margin: 0; font-size: 24px; }
        .print-title p { margin: 5px 0; color: #666; font-size: 12px; }
        .print-report-title { text-align: center; margin-bottom: 20px; }
        .print-report-title h2 { font-family: 'Times New Roman', serif; color: #333; margin: 0; font-size: 18px; }
        .print-report-title p { margin: 3px 0; font-size: 12px; color: #666; }
        .print-supplier-info { background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; padding: 15px; margin-bottom: 20px; display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; }
        .print-info-row { display: flex; font-size: 12px; }
        .print-info-label { width: 120px; font-weight: 600; color: #555; }
        .print-info-value { flex: 1; color: #333; }
        .print-summary { display: flex; justify-content: space-around; background: #e9ecef; padding: 15px; border-radius: 8px; margin-bottom: 20px; text-align: center; }
        .print-summary-item { font-size: 14px; }
        .print-summary-item span { display: block; color: #666; margin-bottom: 5px; }
        .print-summary-item strong { font-size: 18px; }
        .print-debit { color: #dc3545; }
        .print-credit { color: #28a745; }
        .print-table { margin-bottom: 20px; overflow-x: auto; }
        .print-transaction-table { width: 100%; border-collapse: collapse; font-size: 11px; table-layout: fixed; }
        .print-transaction-table th { background: #f8f9fa; padding: 10px; border: 1px solid #dee2e6; font-weight: 600; text-align: left; }
        .print-transaction-table td { padding: 8px 10px; border: 1px solid #dee2e6; }
        .print-total-row { background: #f8f9fa; font-weight: 600; }
        .print-footer { display: flex; justify-content: space-between; margin: 30px 0 20px; padding-top: 20px; border-top: 1px solid #dee2e6; }
        .print-signature, .print-stamp, .print-date { text-align: center; font-size: 10px; color: #666; }
        .print-footer-note { text-align: center; font-size: 10px; color: #999; margin-top: 20px; padding-top: 10px; border-top: 1px dashed #dee2e6; }
        /* FIX: ensure credit column stays inside table */
        .print-transaction-table th, .print-transaction-table td {
            word-break: break-word;
            white-space: normal;
        }
        .print-transaction-table th:nth-child(1), .print-transaction-table td:nth-child(1) { width: 5%; }
        .print-transaction-table th:nth-child(2), .print-transaction-table td:nth-child(2) { width: 12%; }
        .print-transaction-table th:nth-child(3), .print-transaction-table td:nth-child(3) { width: 12%; }
        .print-transaction-table th:nth-child(4), .print-transaction-table td:nth-child(4) { width: 32%; }
        .print-transaction-table th:nth-child(5), .print-transaction-table td:nth-child(5) { width: 11%; }
        .print-transaction-table th:nth-child(6), .print-transaction-table td:nth-child(6) { width: 11%; }
        .print-transaction-table th:nth-child(7), .print-transaction-table td:nth-child(7) { width: 17%; }
        .print-transaction-table tr {
            page-break-inside: avoid;
        }
        @media print {
            body { margin: 0; padding: 0; }
            .print-transaction-table td::before { content: none; }
        }
    `);
    printWindow.document.write('</style>');
    printWindow.document.write('</head><body>');
    printWindow.document.write(printContents);
    printWindow.document.write('</body></html>');
    printWindow.document.close();
    
    // Wait for images to load then print
    printWindow.onload = function() {
        printWindow.print();
        printWindow.onafterprint = function() {
            printWindow.close();
        };
    };
}
</script>

<?php include('../includes/ft.php'); ?>