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

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

$gp_id = isset($_GET['gp_id']) ? intval($_GET['gp_id']) : 0;
$success_message = "";
$error_message = "";

// Get GP details
$gp_sql = "SELECT * FROM general_parties WHERE id = $gp_id";
$gp_result = mysqli_query($conn, $gp_sql);
$gp = mysqli_fetch_assoc($gp_result);

if(!$gp) {
    header("Location: general_parties.php");
    exit();
}

// 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 Received Record (Company gave money to party)
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_received'])) {
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
    $bank_id = isset($_POST['bank_id']) ? intval($_POST['bank_id']) : 0;
    $date_time = mysqli_real_escape_string($conn, $_POST['date_time']);
    $date_created = date('Y-m-d H:i:s');
    
    if(empty($amount) || $amount <= 0) {
        $error_message = "Please enter a valid amount greater than 0!";
    } elseif($payment_method == 'bank' && empty($bank_id)) {
        $error_message = "Please select a bank account for bank payment!";
    } else {
        mysqli_begin_transaction($conn);
        try {
            // For bank payment, check bank balance first (since money is going OUT)
            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 received record
            $sql = "INSERT INTO gp_received (gp_id, gp_name, amount, description, payment_method, date_time, user_name, date_created) 
                    VALUES ($gp_id, '{$gp['gp_name']}', $amount, '$description', '$payment_method', '$date_time', '{$_SESSION['username']}', '$date_created')";
            
            if(!mysqli_query($conn, $sql)) {
                throw new Exception("Failed to insert record: " . mysqli_error($conn));
            }
            
            // Update GP current balance (Increase - Company paid party, so party owes more)
            $update = "UPDATE general_parties SET current_balance = current_balance + $amount WHERE id = $gp_id";
            mysqli_query($conn, $update);
            
            // Handle bank transaction
            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', 'GP Payment Given - {$gp['gp_name']}', 'GP-REC-$gp_id', '$date_created')";
                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) . " given to party successfully!";
            
            // Refresh GP data
            $gp_sql = "SELECT * FROM general_parties WHERE id = $gp_id";
            $gp_result = mysqli_query($conn, $gp_sql);
            $gp = mysqli_fetch_assoc($gp_result);
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    }
}

// Get all received records for this GP
$received_sql = "SELECT * FROM gp_received WHERE gp_id = $gp_id ORDER BY id DESC";
$received_result = mysqli_query($conn, $received_sql);

// Calculate total received
$total_received = 0;
while($row = mysqli_fetch_assoc($received_result)) {
    $total_received += $row['amount'];
}
mysqli_data_seek($received_result, 0);
?>

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

<div class="gp-received-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-hand-holding-usd"></i> GP Payment Given</h2>
            <p>Record payments given to <?php echo htmlspecialchars($gp['gp_name']); ?></p>
        </div>
        <div class="header-right">
            <div class="stats-badge">
                <i class="fas fa-chart-line"></i>
                <span>Current Balance: Rs <?php echo number_format($gp['current_balance'], 2); ?></span>
            </div>
        </div>
    </div>

    <!-- Party Info Banner -->
    <div class="party-info-banner">
        <div class="party-icon">
            <i class="fas fa-address-book"></i>
        </div>
        <div class="party-details">
            <h3><?php echo htmlspecialchars($gp['gp_name']); ?></h3>
            <div class="party-meta">
                <span class="info-tag"><i class="fas fa-id-card"></i> <?php echo htmlspecialchars($gp['gp_id']); ?></span>
                <span class="info-tag"><i class="fas fa-phone"></i> <?php echo htmlspecialchars($gp['gp_phone']); ?></span>
                <span class="info-tag"><i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($gp['gp_address'] ?: 'N/A'); ?></span>
            </div>
        </div>
        <div class="party-balance">
            <span class="balance-label">Current Balance</span>
            <span class="balance-value <?php echo $gp['current_balance'] > 0 ? 'debit' : ($gp['current_balance'] < 0 ? 'credit' : ''); ?>">
                Rs <?php echo number_format(abs($gp['current_balance']), 2); ?>
                <?php echo $gp['current_balance'] > 0 ? 'Dr' : ($gp['current_balance'] < 0 ? 'Cr' : ''); ?>
            </span>
        </div>
    </div>

    <!-- Action Buttons -->
    <div class="action-buttons-bar">
        <a href="general_parties.php" class="btn-back">
            <i class="fas fa-arrow-left"></i> Back to Parties
        </a>
        <a href="gp_ledger.php?id=<?php echo $gp_id; ?>" class="btn-ledger">
            <i class="fas fa-book"></i> View Full Ledger
        </a>
    </div>

    <!-- Alerts -->
    <?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="content-grid">
        <!-- Add Received Form -->
        <div class="form-card">
            <div class="form-card-header">
                <i class="fas fa-plus-circle"></i>
                <h4>Record Payment Taken From Party</h4>
            </div>
            <div class="form-card-body">
                <form method="POST" action="" id="paymentForm">
                    <div class="input-group-custom">
                        <label><i class="fas fa-rupee-sign"></i> Amount <span class="required">*</span></label>
                        <input type="number" step="0.01" name="amount" id="amount" class="form-control-modern" required placeholder="Enter amount" onkeyup="updateAmountPreview()">
                        <small class="input-help">Amount being given to the party</small>
                    </div>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-calendar-alt"></i> Date <span class="required">*</span></label>
                        <input type="date" name="date_time" class="form-control-modern" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-money-bill-wave"></i> Payment Method</label>
                        <select name="payment_method" id="payment_method" class="form-control-modern" 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-align-left"></i> Description</label>
                        <textarea name="description" class="form-control-modern" rows="2" placeholder="Enter description (e.g., Advance payment, Expense reimbursement, etc.)"></textarea>
                        <small class="input-help">Optional - Reason for payment</small>
                    </div>
                    
                    <div class="amount-preview" id="amountPreview" style="display: none;">
                        <div class="preview-row">
                            <span><i class="fas fa-info-circle"></i> Payment Amount:</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 <?php echo number_format($gp['current_balance'], 2); ?></strong>
                        </div>
                    </div>
                    
                    <button type="submit" name="add_received" class="btn-submit">
                        <i class="fas fa-save"></i> Record Payment
                    </button>
                </form>
            </div>
        </div>
        
        <!-- Payment Given History Table -->
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info">
                    <i class="fas fa-history"></i>
                    <h4>Payment Given History (To Party)</h4>
                </div>
                <div class="table-stats">
                    Total Given: <strong>Rs <?php echo number_format($total_received, 2); ?></strong>
                </div>
            </div>
            <div class="table-card-body">
                <div class="table-responsive">
                    <table class="modern-table" id="receivedTable">
                        <thead>
                            <tr>
                                <th width="5%">#</th>
                                <th width="12%">Date</th>
                                <th width="28%">Description</th>
                                <th width="13%">Payment Method</th>
                                <th width="15%">Amount (Rs)</th>
                                <th width="13%">Given By</th>
                                <th width="14%">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(mysqli_num_rows($received_result) > 0): ?>
                                <?php 
                                $sr_no = 1;
                                while($row = mysqli_fetch_assoc($received_result)): 
                                ?>
                                    <tr>
                                        <td data-label="#"><?php echo $sr_no++; ?></td>
                                        <td data-label="Date"><?php echo date('d-m-Y', strtotime($row['date_time'])); ?></td>
                                        <td data-label="Description">
                                            <?php echo htmlspecialchars($row['description'] ?: '—'); ?>
                                        </div>
                                        </td>
                                        <td data-label="Payment Method">
                                            <span class="method-badge <?php echo $row['payment_method']; ?>">
                                                <i class="fas <?php 
                                                    echo $row['payment_method'] == 'cash' ? 'fa-money-bill-wave' : 
                                                        ($row['payment_method'] == 'bank_transfer' ? 'fa-university' :
                                                        ($row['payment_method'] == 'bank' ? 'fa-university' :
                                                        ($row['payment_method'] == 'cheque' ? 'fa-money-check' : 'fa-globe'))); 
                                                ?>"></i>
                                                <?php echo ucfirst(str_replace('_', ' ', $row['payment_method'])); ?>
                                            </span>
                                        </div>
                                        </td>
                                        <td data-label="Amount" class="debit-amount">Rs <?php echo number_format($row['amount'], 2); ?></td>
                                        <td data-label="Given By">
                                            <span class="user-badge">
                                                <i class="fas fa-user-circle"></i> <?php echo htmlspecialchars($row['user_name']); ?>
                                            </span>
                                        </div>
                                        <td>
                                            <a href="gp_received_delete.php?id=<?php echo $row['id']; ?>&gp_id=<?php echo $gp_id; ?>" 
                                               class="btn-action btn-delete" 
                                               onclick="return confirm('Delete this payment record? This will affect the balance!')"
                                               title="Delete Record">
                                                <i class="fas fa-trash-alt"></i>
                                            </a>
                                        </div>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="7" class="empty-state">
                                        <i class="fas fa-inbox"></i>
                                        <p>No payment records found</p>
                                        <small>Record your first payment given using the form</small>
                                    </div>
                                    </tr>
                            <?php endif; ?>
                        </tbody>
                        <tfoot>
                            <tr class="totals-row">
                                <td colspan="4"><strong>Total Given to Party</strong></td>
                                <td class="debit-amount"><strong>Rs <?php echo number_format($total_received, 2); ?></strong></td>
                                <td colspan="2"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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

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

body {
    background: #f5f7fb;
}

/* Headings */
h1, h2, h3, h4, h5, h6,
.page-header h2,
.form-card-header h4,
.header-info h4 {
    font-family: 'Times New Roman', serif;
}

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

/* Page Header */
.page-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    border-radius: 24px;
    padding: 28px 32px;
    margin-bottom: 28px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
    box-shadow: 0 4px 20px rgba(160,70,87,0.2);
}

.page-header h2 {
    margin: 0 0 8px 0;
    font-size: 28px;
    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: 10px 20px;
    border-radius: 40px;
    font-size: 14px;
    font-weight: 600;
    backdrop-filter: blur(10px);
}

/* Party Info Banner */
.party-info-banner {
    background: white;
    border-radius: 20px;
    padding: 20px 28px;
    margin-bottom: 20px;
    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 #A04657;
}

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

.party-details h3 {
    margin: 0 0 8px 0;
    font-size: 20px;
    font-weight: 700;
}

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

.info-tag {
    font-size: 13px;
    color: #666;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

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

.party-balance {
    text-align: center;
    padding: 12px 24px;
    background: #f8f9fc;
    border-radius: 16px;
}

.balance-label {
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
    color: #666;
    display: block;
}

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

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

/* Action Buttons */
.action-buttons-bar {
    display: flex;
    gap: 12px;
    margin-bottom: 28px;
    flex-wrap: wrap;
}

.btn-back, .btn-ledger {
    padding: 10px 24px;
    border-radius: 40px;
    font-weight: 600;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.2s;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.btn-back {
    background: #f0f0f0;
    color: #555;
}
.btn-back:hover {
    background: #e0e0e0;
    text-decoration: none;
    color: #555;
}

.btn-ledger {
    background: #6c5ce7;
    color: white;
}
.btn-ledger:hover {
    background: #5a4ad1;
    text-decoration: none;
    color: white;
}

/* Alerts */
.alert-custom {
    padding: 16px 24px;
    border-radius: 16px;
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    animation: slideIn 0.3s ease;
    font-weight: 500;
}

@keyframes slideIn {
    from { transform: translateY(-20px); opacity: 0; }
    to { transform: translateY(0); opacity: 1; }
}

.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: 24px;
    cursor: pointer;
    opacity: 0.5;
}

/* Content Grid */
.content-grid {
    display: grid;
    grid-template-columns: 380px 1fr;
    gap: 28px;
}

/* Form Card */
.form-card {
    background: #fff;
    border-radius: 24px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0,0,0,0.04);
    border: 1px solid #f0f0f0;
    height: fit-content;
}

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

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

.form-card-header h4 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #fff;
}

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

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

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

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

.required {
    color: #dc3545;
}

.form-control-modern {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid #e8e8e8;
    border-radius: 14px;
    font-size: 14px;
    transition: all 0.3s;
    font-weight: 500;
    background: #fafafa;
}

.form-control-modern:focus {
    border-color: #A04657;
    outline: none;
    background: #fff;
    box-shadow: 0 0 0 3px rgba(160,70,87,0.1);
}

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

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

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

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

/* Amount Preview */
.amount-preview {
    background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
    border-radius: 14px;
    padding: 14px;
    margin-bottom: 24px;
    border: 1px solid #ffcc80;
}

.preview-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 6px 0;
    font-size: 13px;
}

.preview-row strong {
    color: #e65100;
    font-weight: 700;
}

.preview-divider {
    height: 1px;
    background: #ffcc80;
    margin: 8px 0;
}

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

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

/* Table Card */
.table-card {
    background: #fff;
    border-radius: 24px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0,0,0,0.04);
    border: 1px solid #f0f0f0;
}

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

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

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

.header-info h4 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
}

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

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

/* Modern Table */
.modern-table {
    width: 100%;
    border-collapse: collapse;
}

.modern-table th {
    padding: 14px 16px;
    background: #f8f9fc;
    font-weight: 700;
    color: #445566;
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border-bottom: 2px solid #e8e8e8;
}

.modern-table td {
    padding: 14px 16px;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
    font-size: 13px;
    color: #444;
}

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

.debit-amount {
    color: #ff9800;
    font-weight: 700;
}

/* Method Badge */
.method-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
}

.method-badge.cash {
    background: #e8f5e9;
    color: #2e7d32;
}

.method-badge.bank_transfer, .method-badge.bank {
    background: #e3f2fd;
    color: #1565c0;
}

.method-badge.cheque {
    background: #fff3e0;
    color: #e65100;
}

.method-badge.online {
    background: #e8eaf6;
    color: #283593;
}

.method-badge.credit_card {
    background: #fce4ec;
    color: #c2185b;
}

.user-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: #f0f0f0;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 11px;
    color: #555;
}

.totals-row {
    background: #e9ecef;
    font-weight: 700;
}

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

/* Action Buttons */
.btn-action {
    width: 34px;
    height: 34px;
    border-radius: 10px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
    transition: all 0.2s;
}

.btn-delete {
    background: #ffebee;
    color: #d32f2f;
}

.btn-delete:hover {
    background: #d32f2f;
    color: #fff;
    transform: scale(1.05);
}

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

.empty-state i {
    font-size: 56px;
    color: #A04657;
    opacity: 0.3;
    margin-bottom: 16px;
    display: block;
}

.empty-state p {
    font-size: 15px;
    font-weight: 500;
    color: #666;
    margin-bottom: 5px;
}

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

/* Responsive */
@media (max-width: 1100px) {
    .content-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 768px) {
    .gp-received-container {
        padding: 0 12px;
    }
    
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 15px;
    }
    
    .party-info-banner {
        flex-direction: column;
        text-align: center;
    }
    
    .party-meta {
        justify-content: center;
    }
    
    .modern-table thead {
        display: none;
    }
    
    .modern-table td {
        display: block;
        text-align: right;
        padding-left: 50%;
        position: relative;
        border-bottom: none;
    }
    
    .modern-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 16px;
        width: 45%;
        text-align: left;
        font-weight: 700;
        color: #555;
        font-size: 11px;
    }
    
    .modern-table tr {
        display: block;
        margin-bottom: 12px;
        border: 1px solid #e8e8e8;
        border-radius: 12px;
        overflow: hidden;
    }
    
    .action-buttons-bar {
        justify-content: center;
    }
}

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

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

::-webkit-scrollbar-thumb {
    background: #A04657;
    border-radius: 10px;
}
</style>

<script>
// Toggle bank field based on payment method
function toggleBankField() {
    var paymentMethod = document.getElementById('payment_method').value;
    var bankDiv = document.getElementById('bank_div');
    var bankInfoBox = document.getElementById('bankInfoBox');
    var isBank = (paymentMethod === 'bank' || paymentMethod === 'bank_transfer');
    
    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() {
    var bankSelect = document.getElementById('bank_id');
    if(!bankSelect) return;
    
    var selectedOption = bankSelect.options[bankSelect.selectedIndex];
    var bankBalance = parseFloat(selectedOption.getAttribute('data-bank-balance')) || 0;
    var amount = parseFloat(document.getElementById('amount').value) || 0;
    
    document.getElementById('displayBankBalance').innerHTML = 'Rs ' + bankBalance.toFixed(2);
    
    var newBalance = bankBalance - amount;
    var newBalanceSpan = document.getElementById('displayNewBankBalance');
    newBalanceSpan.innerHTML = 'Rs ' + newBalance.toFixed(2);
    
    if(amount > bankBalance) {
        newBalanceSpan.style.color = '#dc3545';
        newBalanceSpan.innerHTML += ' (Insufficient Balance!)';
    } else {
        newBalanceSpan.style.color = '#dc3545';
    }
}

// Amount preview
var amountInput = document.getElementById('amount');
var amountPreview = document.getElementById('amountPreview');
var previewAmount = document.getElementById('previewAmount');
var previewNewBalance = document.getElementById('previewNewBalance');
var currentBalance = <?php echo $gp['current_balance']; ?>;

function updateAmountPreview() {
    var amount = parseFloat(amountInput?.value) || 0;
    
    if(amount > 0 && amountPreview) {
        amountPreview.style.display = 'block';
        previewAmount.innerHTML = 'Rs ' + amount.toFixed(2);
        var newBalance = currentBalance + amount;
        previewNewBalance.innerHTML = 'Rs ' + Math.abs(newBalance).toFixed(2);
        
        if(newBalance > 0) {
            previewNewBalance.style.color = '#dc3545';
            previewNewBalance.innerHTML += ' Dr';
        } else if(newBalance < 0) {
            previewNewBalance.style.color = '#28a745';
            previewNewBalance.innerHTML += ' Cr';
        } else {
            previewNewBalance.style.color = '#666';
        }
        
        // Update bank info if bank payment selected
        if(document.getElementById('payment_method').value === 'bank' || 
           document.getElementById('payment_method').value === 'bank_transfer') {
            updateBankInfo();
        }
    } else if(amountPreview) {
        amountPreview.style.display = 'none';
    }
}

// Add event listeners
if(amountInput) {
    amountInput.addEventListener('input', updateAmountPreview);
}

var bankId = document.getElementById('bank_id');
if(bankId) {
    bankId.addEventListener('change', updateBankInfo);
}

var paymentMethod = document.getElementById('payment_method');
if(paymentMethod) {
    paymentMethod.addEventListener('change', toggleBankField);
}

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

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

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