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

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

$success_message = "";
$error_message = "";
$supplier_id = isset($_GET['supplier_id']) ? (int)$_GET['supplier_id'] : (isset($_POST['supplier_id']) ? (int)$_POST['supplier_id'] : 0);
$supplier = null;

// Get supplier details if ID exists
if($supplier_id > 0) {
    $supplier_sql = "SELECT * FROM suppliers WHERE id = '$supplier_id'";
    $supplier_result = mysqli_query($conn, $supplier_sql);
    $supplier = mysqli_fetch_assoc($supplier_result);
}

// Get all suppliers for dropdown
$suppliers_sql = "SELECT id, name, current_balance, opening_balance, contact_person, phone FROM suppliers ORDER BY name";
$suppliers_result = mysqli_query($conn, $suppliers_sql);

// Get bank accounts for dropdown
$bank_accounts_sql = "SELECT id, bank_name, account_title, balance FROM bank_accounts ORDER BY bank_name";
$bank_accounts_result = mysqli_query($conn, $bank_accounts_sql);

// Add Payment
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_payment'])) {
    $supplier_id = mysqli_real_escape_string($conn, $_POST['supplier_id']);
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
    $bank_id = isset($_POST['bank_id']) ? intval($_POST['bank_id']) : 0;
    $notes = mysqli_real_escape_string($conn, $_POST['notes']);
    $date_time = date('Y-m-d H:i:s');
    
    if(empty($supplier_id)) {
        $error_message = "Please select a supplier!";
    } elseif($amount <= 0) {
        $error_message = "Amount must be greater than 0!";
    } elseif($payment_method == 'bank' && empty($bank_id)) {
        $error_message = "Please select a bank account for bank payment!";
    } else {
        // Get current supplier balance
        $check_sql = "SELECT current_balance FROM suppliers WHERE id = '$supplier_id'";
        $check_result = mysqli_query($conn, $check_sql);
        $supplier_check = mysqli_fetch_assoc($check_result);
        
        if($amount > $supplier_check['current_balance']) {
            $error_message = "Amount cannot exceed current balance! Maximum payable: Rs " . number_format($supplier_check['current_balance'], 2);
        } else {
            mysqli_begin_transaction($conn);
            
            try {
                // For bank payment, check bank balance first
                if($payment_method == 'bank' && $bank_id > 0) {
                    $bank_check_sql = "SELECT balance FROM bank_accounts WHERE id = '$bank_id'";
                    $bank_check_result = mysqli_query($conn, $bank_check_sql);
                    $bank_data = mysqli_fetch_assoc($bank_check_result);
                    if($bank_data['balance'] < $amount) {
                        throw new Exception("Insufficient bank balance! Available: Rs " . number_format($bank_data['balance'], 2));
                    }
                }
                
                // Insert payment record
                $sql = "INSERT INTO supplier_payments (supplier_id, amount, payment_method, notes, date_time) 
                        VALUES ('$supplier_id', '$amount', '$payment_method', '$notes', '$date_time')";
                
                if(!mysqli_query($conn, $sql)) {
                    throw new Exception("Failed to insert payment: " . mysqli_error($conn));
                }
                
                // Update supplier balance (decrease)
                $update_supplier = "UPDATE suppliers SET current_balance = current_balance - $amount WHERE id = '$supplier_id'";
                if(!mysqli_query($conn, $update_supplier)) {
                    throw new Exception("Failed to update supplier balance");
                }
                
                // For bank payment, deduct from bank account
                if($payment_method == 'bank' && $bank_id > 0) {
                    // Update bank balance (deduct amount)
                    $update_bank = "UPDATE bank_accounts SET balance = balance - $amount WHERE id = '$bank_id'";
                    if(!mysqli_query($conn, $update_bank)) {
                        throw new Exception("Failed to update bank balance");
                    }
                    
                    // Insert into bank book as withdrawal
                    $bank_book_sql = "INSERT INTO bank_book (bank_id, entry_type, amount, description, reference_no, date_time) 
                                      VALUES ('$bank_id', 'Withdrawal', '$amount', 'Supplier Payment - " . mysqli_real_escape_string($conn, $supplier['name'] ?? '') . "', 'SUP-$supplier_id', '$date_time')";
                    if(!mysqli_query($conn, $bank_book_sql)) {
                        throw new Exception("Failed to record bank transaction");
                    }
                }
                
                mysqli_commit($conn);
                $success_message = "Payment of Rs " . number_format($amount, 2) . " recorded successfully!";
                
                // Refresh supplier data
                $supplier_sql = "SELECT * FROM suppliers WHERE id = '$supplier_id'";
                $supplier_result = mysqli_query($conn, $supplier_sql);
                $supplier = mysqli_fetch_assoc($supplier_result);
                
            } catch (Exception $e) {
                mysqli_rollback($conn);
                $error_message = "Error: " . $e->getMessage();
            }
        }
    }
}

// Get payment history for selected supplier
$payments_result = null;
$total_paid = 0;
if($supplier_id > 0 && $supplier) {
    $payments_sql = "SELECT * FROM supplier_payments WHERE supplier_id = '$supplier_id' ORDER BY id DESC";
    $payments_result = mysqli_query($conn, $payments_sql);
    
    while($row = mysqli_fetch_assoc($payments_result)) {
        $total_paid += $row['amount'];
    }
    mysqli_data_seek($payments_result, 0);
}
?>

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

<div class="payments-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-hand-holding-usd"></i> Supplier Payments</h2>
            <p>Record payments to suppliers and manage outstanding balances</p>
        </div>
        <div class="header-right">
            <a href="suppliers.php" class="btn-back"><i class="fas fa-arrow-left"></i> Back to Suppliers</a>
        </div>
    </div>

    <!-- Success/Error Messages -->
    <?php if($success_message): ?>
        <div class="alert-custom alert-success">
            <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
            <button class="close-alert" onclick="this.parentElement.remove();">&times;</button>
        </div>
    <?php endif; ?>
    
    <?php if($error_message): ?>
        <div class="alert-custom alert-danger">
            <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
            <button class="close-alert" onclick="this.parentElement.remove();">&times;</button>
        </div>
    <?php endif; ?>

    <div class="row g-4">
        <!-- Supplier Selection & Payment Form -->
        <div class="col-lg-5">
            <div class="form-card">
                <div class="form-card-header">
                    <i class="fas fa-plus-circle"></i>
                    <h4>Record Payment</h4>
                </div>
                <div class="form-card-body">
                    <form method="POST" action="" id="paymentForm">
                        <div class="input-group-custom">
                            <label><i class="fas fa-truck"></i> Select Supplier <span class="required">*</span></label>
                            <select name="supplier_id" id="supplier_id" class="form-control-modern" required onchange="this.form.submit()">
                                <option value="">-- Select Supplier --</option>
                                <?php 
                                mysqli_data_seek($suppliers_result, 0);
                                while($sup = mysqli_fetch_assoc($suppliers_result)): 
                                    $selected = ($supplier_id == $sup['id']) ? 'selected' : '';
                                ?>
                                    <option value="<?php echo $sup['id']; ?>" 
                                            data-balance="<?php echo $sup['current_balance']; ?>"
                                            data-contact="<?php echo htmlspecialchars($sup['contact_person'] ?? ''); ?>"
                                            data-phone="<?php echo htmlspecialchars($sup['phone'] ?? ''); ?>"
                                            data-opening="<?php echo $sup['opening_balance']; ?>"
                                            data-name="<?php echo htmlspecialchars($sup['name']); ?>"
                                            <?php echo $selected; ?>>
                                        <?php echo htmlspecialchars($sup['name']); ?> 
                                        (Balance: Rs <?php echo number_format($sup['current_balance'], 2); ?>)
                                    </option>
                                <?php endwhile; ?>
                            </select>
                            <small class="input-help">Select supplier to record payment</small>
                        </div>
                        
                        <?php if($supplier && $supplier_id > 0): ?>
                            <!-- Supplier Info Card -->
                            <div class="supplier-info-card">
                                <div class="supplier-avatar"><i class="fas fa-building"></i></div>
                                <div class="supplier-details">
                                    <h4><?php echo htmlspecialchars($supplier['name']); ?></h4>
                                    <div class="info-grid">
                                        <div class="info-item"><i class="fas fa-user"></i> <?php echo htmlspecialchars($supplier['contact_person'] ?? 'N/A'); ?></div>
                                        <div class="info-item"><i class="fas fa-phone"></i> <?php echo htmlspecialchars($supplier['phone'] ?? 'N/A'); ?></div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="balance-card">
                                <div class="balance-row">
                                    <span>Opening Balance:</span>
                                    <strong>Rs <?php echo number_format($supplier['opening_balance'] ?? 0, 2); ?></strong>
                                </div>
                                <div class="balance-row">
                                    <span>Current Balance:</span>
                                    <strong class="<?php echo ($supplier['current_balance'] ?? 0) > 0 ? 'text-danger' : 'text-success'; ?>">Rs <?php echo number_format($supplier['current_balance'] ?? 0, 2); ?></strong>
                                </div>
                            </div>
                            
                            <div class="input-group-custom">
                                <label><i class="fas fa-money-bill-wave"></i> Payment Method <span class="required">*</span></label>
                                <select name="payment_method" id="payment_method" class="form-control-modern" required onchange="toggleBankField()">
                                    <option value="cash">Cash</option>
                                    <option value="bank">Bank (Direct Withdrawal)</option>
                                </select>
                            </div>
                            
                            <!-- Bank Account Selection (shown only when bank is selected) -->
                            <div class="input-group-custom" id="bank_div" style="display: none;">
                                <label><i class="fas fa-university"></i> Select Bank Account <span class="required">*</span></label>
                                <select name="bank_id" id="bank_id" class="form-control-modern" onchange="updateBankInfo()">
                                    <option value="">-- Select Bank Account --</option>
                                    <?php 
                                    mysqli_data_seek($bank_accounts_result, 0);
                                    while($bank = mysqli_fetch_assoc($bank_accounts_result)): 
                                    ?>
                                        <option value="<?php echo $bank['id']; ?>"
                                                data-bank-balance="<?php echo $bank['balance']; ?>"
                                                data-bank-name="<?php echo htmlspecialchars($bank['bank_name']); ?>">
                                            <?php echo htmlspecialchars($bank['bank_name']); ?> - 
                                            <?php echo htmlspecialchars($bank['account_title']); ?> 
                                            (Balance: Rs <?php echo number_format($bank['balance'], 2); ?>)
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                                <small class="input-help">Amount will be deducted from selected bank account</small>
                            </div>
                            
                            <!-- Bank Info Box (shown when bank is selected) -->
                            <div class="bank-info-box" id="bankInfoBox" style="display: none;">
                                <div class="info-row">
                                    <span><i class="fas fa-university"></i> Bank Balance:</span>
                                    <strong id="displayBankBalance">Rs 0.00</strong>
                                </div>
                                <div class="info-row" style="color: #dc3545;">
                                    <span><i class="fas fa-arrow-down"></i> After Withdrawal:</span>
                                    <strong id="displayNewBankBalance">Rs 0.00</strong>
                                </div>
                            </div>
                            
                            <div class="input-group-custom">
                                <label><i class="fas fa-rupee-sign"></i> Payment Amount <span class="required">*</span></label>
                                <input type="number" step="0.01" name="amount" id="amount" class="form-control-modern" required placeholder="Enter payment amount" onkeyup="validateAmount()">
                                <small class="input-help">Maximum payable: Rs <?php echo number_format($supplier['current_balance'], 2); ?></small>
                            </div>
                            
                            <div class="payment-preview" id="paymentPreview" style="display: none;">
                                <div class="preview-row">
                                    <span><i class="fas fa-info-circle"></i> Amount to Pay:</span>
                                    <strong id="previewAmount">Rs 0.00</strong>
                                </div>
                                <div class="preview-divider"></div>
                                <div class="preview-row">
                                    <span><i class="fas fa-chart-line"></i> New Balance:</span>
                                    <strong id="previewNewBalance">Rs 0.00</strong>
                                </div>
                            </div>
                            
                            <div class="input-group-custom">
                                <label><i class="fas fa-sticky-note"></i> Notes</label>
                                <textarea name="notes" class="form-control-modern" rows="2" placeholder="Payment reference or notes (optional)"></textarea>
                            </div>
                            
                            <button type="submit" name="add_payment" class="btn-submit">
                                <i class="fas fa-save"></i> Record Payment
                            </button>
                        <?php elseif($supplier_id == 0): ?>
                            <div class="no-supplier-warning">
                                <i class="fas fa-info-circle"></i>
                                <p>Select a supplier to record payment</p>
                                <small>Please select a supplier from the dropdown above</small>
                            </div>
                        <?php endif; ?>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- Payment History Table -->
        <div class="col-lg-7">
            <div class="table-card">
                <div class="table-card-header">
                    <div class="header-info">
                        <i class="fas fa-history"></i>
                        <h4>Payment History</h4>
                    </div>
                    <?php if($supplier): ?>
                        <div class="table-stats">
                            Total Paid: <strong>Rs <?php echo number_format($total_paid, 2); ?></strong>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="table-card-body">
                    <div class="table-responsive">
                        <table class="modern-table" id="paymentsTable">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Date & Time</th>
                                    <th>Payment Method</th>
                                    <th>Amount (Rs)</th>
                                    <th>Notes</th>
                                </td>
                            </thead>
                            <tbody>
                                <?php if($payments_result && mysqli_num_rows($payments_result) > 0): ?>
                                    <?php $sn = 1; while($payment = mysqli_fetch_assoc($payments_result)): ?>
                                        <tr>
                                            <td data-label="#"><?php echo $sn++; ?></td>
                                            <td data-label="Date & Time"><?php echo date('d-m-Y H:i:s', strtotime($payment['date_time'])); ?></td>
                                            <td data-label="Payment Method">
                                                <span class="method-badge <?php echo $payment['payment_method'] == 'bank' ? 'bank' : ''; ?>">
                                                    <?php echo ucfirst($payment['payment_method'] ?? 'cash'); ?>
                                                </span>
                                            </div>
                                            <td data-label="Amount" class="payment-amount">Rs <?php echo number_format($payment['amount'], 2); ?></td>
                                            <td data-label="Notes"><?php echo htmlspecialchars($payment['notes'] ?: '—'); ?></td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="5" class="empty-state">
                                            <i class="fas fa-hand-holding-usd"></i>
                                            <p>No payments recorded yet</p>
                                            <?php if($supplier): ?>
                                                <small>Record your first payment for this supplier</small>
                                            <?php else: ?>
                                                <small>Select a supplier to view payment history</small>
                                            <?php endif; ?>
                                        </div>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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

* {
    font-family: 'Poppins', sans-serif;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background: #f5f7fb;
    overflow-x: hidden;
}

h1, h2, h3, h4, h5, h6,
.page-header h2,
.form-card-header h4,
.header-info h4,
.modern-table th {
    font-family: 'Poppins', sans-serif;
    font-weight: 600;
}

/* Main Content */
.main-content {
    margin-left: 280px;
    padding: 15px 20px;
    transition: all 0.3s;
    background: #f5f7fb;
}

.payments-container {
    max-width: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
}

/* Page Header */
.page-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    border-radius: 16px;
    padding: 16px 24px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
    width: 100%;
}

.page-header h2 {
    color: #fff;
    margin: 0 0 4px 0;
    font-size: 22px;
}

.page-header p {
    color: rgba(255,255,255,0.9);
    margin: 0;
    font-size: 12px;
}

.btn-back {
    background: rgba(255,255,255,0.2);
    color: #fff;
    padding: 6px 18px;
    border-radius: 40px;
    text-decoration: none;
    font-weight: 600;
    font-size: 12px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: all 0.3s;
}

.btn-back:hover {
    background: rgba(255,255,255,0.3);
    color: #fff;
}

/* Alerts */
.alert-custom {
    padding: 12px 20px;
    border-radius: 14px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 13px;
    width: 100%;
}

.alert-success {
    background: #e8f5e9;
    color: #2e7d32;
    border-left: 4px solid #28a745;
}

.alert-danger {
    background: #ffebee;
    color: #c62828;
    border-left: 4px solid #dc3545;
}

.close-alert {
    background: none;
    border: none;
    font-size: 22px;
    cursor: pointer;
    opacity: 0.5;
}

/* Form Card */
.form-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    border: 1px solid #f0f0f0;
}

.form-card-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    padding: 14px 20px;
    display: flex;
    align-items: center;
    gap: 8px;
    color: #fff;
}

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

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

.form-card-body {
    padding: 20px;
}

.input-group-custom {
    margin-bottom: 16px;
}

.input-group-custom label {
    display: block;
    margin-bottom: 6px;
    font-weight: 600;
    color: #333;
    font-size: 12px;
}

.input-group-custom label i {
    color: #A04657;
    margin-right: 5px;
}

.required {
    color: #dc3545;
}

.form-control-modern {
    width: 100%;
    padding: 9px 12px;
    border: 2px solid #e8e8e8;
    border-radius: 10px;
    font-size: 13px;
    transition: all 0.2s;
    background: #fafafa;
}

.form-control-modern:focus {
    border-color: #A04657;
    outline: none;
    background: #fff;
}

.input-help {
    display: block;
    font-size: 10px;
    color: #999;
    margin-top: 4px;
}

/* Supplier Info Card */
.supplier-info-card {
    background: #f8f9fc;
    border-radius: 12px;
    padding: 12px;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    gap: 12px;
    border: 1px solid #f0f0f0;
}

.supplier-avatar i {
    font-size: 36px;
    color: #A04657;
}

.supplier-details h4 {
    margin: 0 0 5px 0;
    font-size: 14px;
}

.info-grid {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
}

.info-item {
    font-size: 11px;
    color: #555;
    display: flex;
    align-items: center;
    gap: 4px;
}

.info-item i {
    color: #A04657;
}

/* Balance Card */
.balance-card {
    background: #f8f9fa;
    border-radius: 12px;
    padding: 10px 14px;
    margin-bottom: 16px;
    border-left: 4px solid #A04657;
}

.balance-row {
    display: flex;
    justify-content: space-between;
    padding: 4px 0;
    font-size: 12px;
}

.balance-row strong {
    font-size: 14px;
}

.text-danger {
    color: #dc3545 !important;
}

.text-success {
    color: #28a745 !important;
}

/* Bank Info Box */
.bank-info-box {
    background: #ffebee;
    border-radius: 10px;
    padding: 10px 12px;
    margin-bottom: 16px;
    border-left: 4px solid #dc3545;
}

.bank-info-box .info-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 4px;
    font-size: 11px;
}

.bank-info-box .info-row:last-child {
    margin-bottom: 0;
}

/* Payment Preview */
.payment-preview {
    background: #f8f9ff;
    border-radius: 10px;
    padding: 10px;
    margin-bottom: 16px;
    border: 1px solid #e8e8ff;
}

.preview-row {
    display: flex;
    justify-content: space-between;
    padding: 4px 0;
    font-size: 11px;
}

.preview-row strong {
    color: #A04657;
}

.preview-divider {
    height: 1px;
    background: #e8e8ff;
    margin: 4px 0;
}

.btn-submit {
    width: 100%;
    padding: 10px;
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    color: #fff;
    border: none;
    border-radius: 10px;
    font-weight: 600;
    font-size: 13px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
}

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

/* No Supplier Warning */
.no-supplier-warning {
    text-align: center;
    padding: 40px 20px;
    background: #f8f9fa;
    border-radius: 12px;
}

.no-supplier-warning i {
    font-size: 48px;
    color: #A04657;
    margin-bottom: 12px;
    opacity: 0.5;
}

.no-supplier-warning p {
    font-size: 13px;
    font-weight: 600;
    color: #555;
    margin-bottom: 4px;
}

.no-supplier-warning small {
    font-size: 11px;
    color: #999;
}

/* Table Card */
.table-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    border: 1px solid #f0f0f0;
    width: 100%;
}

.table-card-header {
    padding: 12px 20px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}

.header-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.header-info i {
    font-size: 18px;
    color: #A04657;
}

.header-info h4 {
    margin: 0;
    font-size: 15px;
}

.table-stats {
    font-size: 11px;
    color: #666;
}

.table-stats strong {
    color: #A04657;
    font-size: 14px;
    margin-left: 5px;
}

.table-responsive {
    overflow-x: auto;
    width: 100%;
}

.modern-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
    min-width: 700px;
}

.modern-table th {
    padding: 10px 12px;
    background: #f8f9fa;
    font-weight: 700;
    color: #555;
    font-size: 11px;
    border-bottom: 1px solid #e8e8e8;
}

.modern-table td {
    padding: 10px 12px;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
    font-size: 12px;
}

.payment-amount {
    color: #28a745;
    font-weight: 700;
}

.method-badge {
    background: #e3f2fd;
    color: #1976d2;
    padding: 3px 10px;
    border-radius: 20px;
    font-size: 10px;
    font-weight: 600;
    display: inline-block;
}

.method-badge.bank {
    background: #ffebee;
    color: #c62828;
}

.empty-state {
    text-align: center;
    padding: 40px !important;
}

.empty-state i {
    font-size: 48px;
    color: #A04657;
    opacity: 0.4;
    margin-bottom: 12px;
    display: block;
}

.empty-state p {
    margin: 0;
    color: #666;
    font-size: 13px;
}

.empty-state small {
    color: #999;
    font-size: 11px;
}

/* Responsive */
@media (max-width: 1100px) {
    .row.g-4 {
        flex-direction: column;
    }
    .col-lg-5, .col-lg-7 {
        width: 100%;
    }
}

@media (max-width: 992px) {
    .main-content {
        margin-left: 0;
        padding: 12px 15px;
    }
}

@media (max-width: 768px) {
    .main-content {
        padding: 10px;
    }
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 12px;
        padding: 14px 18px;
    }
    .page-header h2 {
        font-size: 18px;
    }
    .supplier-info-card {
        flex-direction: column;
        text-align: center;
    }
    .info-grid {
        justify-content: center;
    }
    .form-card-body {
        padding: 16px;
    }
    .modern-table th {
        display: none;
    }
    .modern-table td {
        display: block;
        text-align: right;
        padding-left: 45%;
        position: relative;
    }
    .modern-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 12px;
        width: 40%;
        text-align: left;
        font-weight: 700;
        font-size: 10px;
        color: #A04657;
    }
    .modern-table tr {
        display: block;
        margin-bottom: 10px;
        border: 1px solid #e8e8e8;
        border-radius: 10px;
        overflow: hidden;
    }
}

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

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    background: #A04657;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
    background: #6b2a36;
}
</style>

<script>
// Validate amount and show preview
function validateAmount() {
    const amount = parseFloat(document.getElementById('amount')?.value) || 0;
    const supplierSelect = document.getElementById('supplier_id');
    const selectedOption = supplierSelect.options[supplierSelect.selectedIndex];
    const currentBalance = parseFloat(selectedOption.getAttribute('data-balance')) || 0;
    const previewDiv = document.getElementById('paymentPreview');
    
    if(amount > 0 && previewDiv) {
        previewDiv.style.display = 'block';
        document.getElementById('previewAmount').innerHTML = 'Rs ' + amount.toFixed(2);
        const newBalance = currentBalance - amount;
        document.getElementById('previewNewBalance').innerHTML = 'Rs ' + newBalance.toFixed(2);
        
        if(newBalance < 0) {
            document.getElementById('previewNewBalance').style.color = '#dc3545';
        } else if(newBalance === 0) {
            document.getElementById('previewNewBalance').style.color = '#28a745';
        } else {
            document.getElementById('previewNewBalance').style.color = '#A04657';
        }
    } else if(previewDiv) {
        previewDiv.style.display = 'none';
    }
    
    const paymentMethod = document.getElementById('payment_method')?.value;
    if(paymentMethod === 'bank') {
        updateBankInfo();
    }
}

// Toggle bank field based on payment method
function toggleBankField() {
    const paymentMethod = document.getElementById('payment_method').value;
    const bankDiv = document.getElementById('bank_div');
    const bankInfoBox = document.getElementById('bankInfoBox');
    const isBank = (paymentMethod === 'bank');
    
    if(bankDiv) {
        bankDiv.style.display = isBank ? 'block' : 'none';
    }
    if(bankInfoBox) {
        bankInfoBox.style.display = isBank ? 'block' : 'none';
    }
    
    if(isBank) {
        document.getElementById('bank_id')?.setAttribute('required', 'required');
        updateBankInfo();
    } else {
        document.getElementById('bank_id')?.removeAttribute('required');
    }
}

// Update bank information
function updateBankInfo() {
    const bankSelect = document.getElementById('bank_id');
    if(!bankSelect) return;
    
    const selectedOption = bankSelect.options[bankSelect.selectedIndex];
    const bankBalance = parseFloat(selectedOption.getAttribute('data-bank-balance')) || 0;
    const amount = parseFloat(document.getElementById('amount')?.value) || 0;
    
    document.getElementById('displayBankBalance').innerHTML = 'Rs ' + bankBalance.toFixed(2);
    
    const newBalance = bankBalance - amount;
    const newBalanceSpan = document.getElementById('displayNewBankBalance');
    newBalanceSpan.innerHTML = 'Rs ' + newBalance.toFixed(2);
    
    if(amount > bankBalance) {
        newBalanceSpan.style.color = '#dc3545';
        newBalanceSpan.innerHTML += ' (Insufficient!)';
    } else {
        newBalanceSpan.style.color = '#dc3545';
    }
}

// Auto hide alerts
document.querySelectorAll('.alert-custom').forEach(alert => {
    setTimeout(() => {
        if(alert) alert.style.opacity = '0';
        setTimeout(() => {
            if(alert && alert.parentElement) alert.remove();
        }, 300);
    }, 5000);
});

// Add event listeners
document.getElementById('amount')?.addEventListener('input', function() {
    validateAmount();
    if(document.getElementById('payment_method')?.value === 'bank') {
        updateBankInfo();
    }
});

document.getElementById('bank_id')?.addEventListener('change', updateBankInfo);

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    toggleBankField();
    validateAmount();
});
</script>

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