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

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

$gp_id = isset($_GET['id']) ? intval($_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');

// 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();
}

$gp_name = $gp['gp_name'];
$success_message = "";
$error_message = "";

// ============================================
// ADD OPENING BALANCE
// ============================================
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_opening'])) {
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $notes = mysqli_real_escape_string($conn, $_POST['notes']);
    $date_time = mysqli_real_escape_string($conn, $_POST['date_time']);
    $date_created = date('Y-m-d H:i:s');
    
    if($amount <= 0) {
        $error_message = "Amount must be greater than 0!";
    } else {
        mysqli_begin_transaction($conn);
        try {
            // Insert opening record
            $sql = "INSERT INTO gp_openings (gp_id, gp_name, amount, date_time, notes, user_name, date_created) 
                    VALUES ($gp_id, '$gp_name', $amount, '$date_time', '$notes', '{$_SESSION['username']}', '$date_created')";
            mysqli_query($conn, $sql);
            
            // Update GP current balance
            $update = "UPDATE general_parties SET current_balance = current_balance + $amount WHERE id = $gp_id";
            mysqli_query($conn, $update);
            
            mysqli_commit($conn);
            $success_message = "Opening balance of Rs " . number_format($amount, 2) . " added successfully!";
            
            // Refresh GP data
            $gp_result = mysqli_query($conn, "SELECT * FROM general_parties WHERE id = $gp_id");
            $gp = mysqli_fetch_assoc($gp_result);
        } catch(Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    }
}

// ============================================
// ADD PAYABLE (Expense/Credit)
// ============================================
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_payable'])) {
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    $date_time = mysqli_real_escape_string($conn, $_POST['date_time']);
    $date_created = date('Y-m-d H:i:s');
    
    if($amount <= 0) {
        $error_message = "Amount must be greater than 0!";
    } else {
        mysqli_begin_transaction($conn);
        try {
            // Insert payable record
            $sql = "INSERT INTO gp_payable (gp_id, gp_name, amount, description, date_time, user_name, date_created) 
                    VALUES ($gp_id, '$gp_name', $amount, '$description', '$date_time', '{$_SESSION['username']}', '$date_created')";
            mysqli_query($conn, $sql);
            
            // Update GP current balance (Increase - Party owes more)
            $update = "UPDATE general_parties SET current_balance = current_balance + $amount WHERE id = $gp_id";
            mysqli_query($conn, $update);
            
            mysqli_commit($conn);
            $success_message = "Payable of Rs " . number_format($amount, 2) . " added successfully!";
            
            // Refresh GP data
            $gp_result = mysqli_query($conn, "SELECT * FROM general_parties WHERE id = $gp_id");
            $gp = mysqli_fetch_assoc($gp_result);
        } catch(Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    }
}

// ============================================
// ADD PAID (Party paid to company - Decreases balance)
// ============================================
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_paid'])) {
    $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']);
    $date_time = mysqli_real_escape_string($conn, $_POST['date_time']);
    $date_created = date('Y-m-d H:i:s');
    
    if($amount <= 0) {
        $error_message = "Amount must be greater than 0!";
    } elseif($amount > $gp['current_balance']) {
        $error_message = "Amount cannot exceed current balance! Max payable: Rs " . number_format($gp['current_balance'], 2);
    } else {
        mysqli_begin_transaction($conn);
        try {
            // Insert paid record
            $sql = "INSERT INTO gp_paid (gp_id, gp_name, amount, description, payment_method, date_time, user_name, date_created) 
                    VALUES ($gp_id, '$gp_name', $amount, '$description', '$payment_method', '$date_time', '{$_SESSION['username']}', '$date_created')";
            mysqli_query($conn, $sql);
            
            // Update GP current balance (Decrease)
            $update = "UPDATE general_parties SET current_balance = current_balance - $amount WHERE id = $gp_id";
            mysqli_query($conn, $update);
            
            mysqli_commit($conn);
            $success_message = "Payment of Rs " . number_format($amount, 2) . " received successfully!";
            
            // Refresh GP data
            $gp_result = mysqli_query($conn, "SELECT * FROM general_parties WHERE id = $gp_id");
            $gp = mysqli_fetch_assoc($gp_result);
        } catch(Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    }
}

// ============================================
// ADD RECEIVED (Company paid to party - Increases balance)
// ============================================
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']);
    $date_time = mysqli_real_escape_string($conn, $_POST['date_time']);
    $date_created = date('Y-m-d H:i:s');
    
    if($amount <= 0) {
        $error_message = "Amount must be greater than 0!";
    } else {
        mysqli_begin_transaction($conn);
        try {
            // 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_name', $amount, '$description', '$payment_method', '$date_time', '{$_SESSION['username']}', '$date_created')";
            mysqli_query($conn, $sql);
            
            // Update GP current balance (Increase)
            $update = "UPDATE general_parties SET current_balance = current_balance + $amount WHERE id = $gp_id";
            mysqli_query($conn, $update);
            
            mysqli_commit($conn);
            $success_message = "Received payment of Rs " . number_format($amount, 2) . " recorded successfully!";
            
            // Refresh GP data
            $gp_result = mysqli_query($conn, "SELECT * FROM general_parties WHERE id = $gp_id");
            $gp = mysqli_fetch_assoc($gp_result);
        } catch(Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    }
}

// ============================================
// DELETE RECORDS
// ============================================
if(isset($_GET['del_open'])) {
    $del_id = intval($_GET['del_open']);
    $del_sql = "DELETE FROM gp_openings WHERE id = $del_id AND gp_id = $gp_id";
    if(mysqli_query($conn, $del_sql)) {
        // Recalculate balance
        $total_open = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM gp_openings WHERE gp_id = $gp_id"))['total'] ?? 0;
        $total_payable = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM gp_payable WHERE gp_id = $gp_id"))['total'] ?? 0;
        $total_paid = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM gp_paid WHERE gp_id = $gp_id"))['total'] ?? 0;
        $total_received = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM gp_received WHERE gp_id = $gp_id"))['total'] ?? 0;
        $new_balance = $total_open + $total_payable - $total_paid + $total_received;
        mysqli_query($conn, "UPDATE general_parties SET current_balance = $new_balance WHERE id = $gp_id");
        
        $success_message = "Record deleted successfully!";
        header("Location: gp_ledger.php?id=$gp_id");
        exit();
    }
}

if(isset($_GET['del_payable'])) {
    $del_id = intval($_GET['del_payable']);
    $del_sql = "DELETE FROM gp_payable WHERE id = $del_id AND gp_id = $gp_id";
    if(mysqli_query($conn, $del_sql)) {
        $total_open = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM gp_openings WHERE gp_id = $gp_id"))['total'] ?? 0;
        $total_payable = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM gp_payable WHERE gp_id = $gp_id"))['total'] ?? 0;
        $total_paid = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM gp_paid WHERE gp_id = $gp_id"))['total'] ?? 0;
        $total_received = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM gp_received WHERE gp_id = $gp_id"))['total'] ?? 0;
        $new_balance = $total_open + $total_payable - $total_paid + $total_received;
        mysqli_query($conn, "UPDATE general_parties SET current_balance = $new_balance WHERE id = $gp_id");
        
        $success_message = "Record deleted successfully!";
        header("Location: gp_ledger.php?id=$gp_id");
        exit();
    }
}

if(isset($_GET['del_paid'])) {
    $del_id = intval($_GET['del_paid']);
    $del_sql = "DELETE FROM gp_paid WHERE id = $del_id AND gp_id = $gp_id";
    if(mysqli_query($conn, $del_sql)) {
        $total_open = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM gp_openings WHERE gp_id = $gp_id"))['total'] ?? 0;
        $total_payable = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM gp_payable WHERE gp_id = $gp_id"))['total'] ?? 0;
        $total_paid = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM gp_paid WHERE gp_id = $gp_id"))['total'] ?? 0;
        $total_received = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM gp_received WHERE gp_id = $gp_id"))['total'] ?? 0;
        $new_balance = $total_open + $total_payable - $total_paid + $total_received;
        mysqli_query($conn, "UPDATE general_parties SET current_balance = $new_balance WHERE id = $gp_id");
        
        $success_message = "Record deleted successfully!";
        header("Location: gp_ledger.php?id=$gp_id");
        exit();
    }
}

if(isset($_GET['del_received'])) {
    $del_id = intval($_GET['del_received']);
    $del_sql = "DELETE FROM gp_received WHERE id = $del_id AND gp_id = $gp_id";
    if(mysqli_query($conn, $del_sql)) {
        $total_open = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM gp_openings WHERE gp_id = $gp_id"))['total'] ?? 0;
        $total_payable = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM gp_payable WHERE gp_id = $gp_id"))['total'] ?? 0;
        $total_paid = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM gp_paid WHERE gp_id = $gp_id"))['total'] ?? 0;
        $total_received = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM gp_received WHERE gp_id = $gp_id"))['total'] ?? 0;
        $new_balance = $total_open + $total_payable - $total_paid + $total_received;
        mysqli_query($conn, "UPDATE general_parties SET current_balance = $new_balance WHERE id = $gp_id");
        
        $success_message = "Record deleted successfully!";
        header("Location: gp_ledger.php?id=$gp_id");
        exit();
    }
}

// Get all records for calculations
$total_open = 0;
$open_result = mysqli_query($conn, "SELECT * FROM gp_openings WHERE gp_id = $gp_id ORDER BY id DESC");
while($row = mysqli_fetch_assoc($open_result)) { $total_open += $row['amount']; }
mysqli_data_seek($open_result, 0);

$total_payable = 0;
$payable_result = mysqli_query($conn, "SELECT * FROM gp_payable WHERE gp_id = $gp_id ORDER BY id DESC");
while($row = mysqli_fetch_assoc($payable_result)) { $total_payable += $row['amount']; }
mysqli_data_seek($payable_result, 0);

$total_paid = 0;
$paid_result = mysqli_query($conn, "SELECT * FROM gp_paid WHERE gp_id = $gp_id ORDER BY id DESC");
while($row = mysqli_fetch_assoc($paid_result)) { $total_paid += $row['amount']; }
mysqli_data_seek($paid_result, 0);

$total_received = 0;
$received_result = mysqli_query($conn, "SELECT * FROM gp_received WHERE gp_id = $gp_id ORDER BY id DESC");
while($row = mysqli_fetch_assoc($received_result)) { $total_received += $row['amount']; }
mysqli_data_seek($received_result, 0);

$closing_balance = $total_open + $total_payable - $total_paid + $total_received;
?>

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

<div class="gp-ledger-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-file-invoice-dollar"></i> General Party Ledger</h2>
            <p>Complete transaction history for <?php echo htmlspecialchars($gp['gp_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>

    <!-- 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 $closing_balance > 0 ? 'debit' : ($closing_balance < 0 ? 'credit' : ''); ?>">
                Rs <?php echo number_format(abs($closing_balance), 2); ?>
                <?php echo $closing_balance > 0 ? 'Dr' : ($closing_balance < 0 ? 'Cr' : ''); ?>
            </span>
        </div>
    </div>

    <!-- Action Buttons -->
    <div class="action-buttons-bar">
        <button class="btn-action-modal btn-open" data-toggle="modal" data-target="#openModal">
            <i class="fas fa-plus-circle"></i> Add Opening
        </button>
        <button class="btn-action-modal btn-payable" data-toggle="modal" data-target="#payableModal">
            <i class="fas fa-arrow-up"></i> Add Payable
        </button>
        <button class="btn-action-modal btn-paid" data-toggle="modal" data-target="#paidModal">
            <i class="fas fa-check-circle"></i> Add Paid
        </button>
        <button class="btn-action-modal btn-received" data-toggle="modal" data-target="#receivedModal">
            <i class="fas fa-hand-holding-usd"></i> Add Received
        </button>
        <a href="general_parties.php" class="btn-action-modal btn-back">
            <i class="fas fa-arrow-left"></i> Back to Parties
        </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; ?>

    <!-- Summary Cards -->
    <div class="summary-cards">
        <div class="summary-card">
            <div class="summary-icon open-icon">
                <i class="fas fa-play-circle"></i>
            </div>
            <div class="summary-content">
                <h4>Rs <?php echo number_format($total_open, 2); ?></h4>
                <p>Opening Balance</p>
                <small>Initial amount</small>
            </div>
        </div>
        <div class="summary-card">
            <div class="summary-icon payable-icon">
                <i class="fas fa-arrow-up"></i>
            </div>
            <div class="summary-content">
                <h4>Rs <?php echo number_format($total_payable, 2); ?></h4>
                <p>Total Payable</p>
                <small>Expenses/Credits</small>
            </div>
        </div>
        <div class="summary-card">
            <div class="summary-icon paid-icon">
                <i class="fas fa-arrow-down"></i>
            </div>
            <div class="summary-content">
                <h4>Rs <?php echo number_format($total_paid, 2); ?></h4>
                <p>Total Paid</p>
                <small>Payments received</small>
            </div>
        </div>
        <div class="summary-card">
            <div class="summary-icon received-icon">
                <i class="fas fa-hand-holding-usd"></i>
            </div>
            <div class="summary-content">
                <h4>Rs <?php echo number_format($total_received, 2); ?></h4>
                <p>Total Received</p>
                <small>Payments made to party</small>
            </div>
        </div>
    </div>

    <!-- Tab Navigation -->
    <div class="tab-navigation">
        <div class="tab-btn active" data-tab="tab-openings">
            <i class="fas fa-play-circle"></i> Opening Balance
        </div>
        <div class="tab-btn" data-tab="tab-payable">
            <i class="fas fa-arrow-up"></i> Payable
        </div>
        <div class="tab-btn" data-tab="tab-paid">
            <i class="fas fa-arrow-down"></i> Paid
        </div>
        <div class="tab-btn" data-tab="tab-received">
            <i class="fas fa-hand-holding-usd"></i> Received
        </div>
    </div>

    <!-- Tab Content: Openings -->
    <div id="tab-openings" class="tab-content active">
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info">
                    <i class="fas fa-play-circle"></i>
                    <h4>Opening Balance Records</h4>
                </div>
                <div class="table-stats">Total: Rs <?php echo number_format($total_open, 2); ?></div>
            </div>
            <div class="table-card-body">
                <div class="table-responsive">
                    <table class="modern-table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Date</th>
                                <th>Amount (Rs)</th>
                                <th>Notes</th>
                                <th>Added By</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $sr = 1;
                            mysqli_data_seek($open_result, 0);
                            if(mysqli_num_rows($open_result) > 0):
                                while($row = mysqli_fetch_assoc($open_result)): 
                            ?>
                                <tr>
                                    <td><?php echo $sr++; ?></td>
                                    <td><?php echo date('d-m-Y', strtotime($row['date_time'])); ?></td>
                                    <td class="debit-amount">Rs <?php echo number_format($row['amount'], 2); ?></td>
                                    <td><?php echo htmlspecialchars($row['notes'] ?: '—'); ?></td>
                                    <td><?php echo htmlspecialchars($row['user_name']); ?></td>
                                    <td>
                                        <a href="?id=<?php echo $gp_id; ?>&del_open=<?php echo $row['id']; ?>" 
                                           class="btn-action btn-delete" 
                                           onclick="return confirm('Delete this record?')">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php 
                                endwhile;
                            else:
                            ?>
                                <tr><td colspan="6" class="empty-state">No opening balance records found</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Tab Content: Payable -->
    <div id="tab-payable" class="tab-content">
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info">
                    <i class="fas fa-arrow-up"></i>
                    <h4>Payable Records (Party owes us)</h4>
                </div>
                <div class="table-stats">Total: Rs <?php echo number_format($total_payable, 2); ?></div>
            </div>
            <div class="table-card-body">
                <div class="table-responsive">
                    <table class="modern-table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Date</th>
                                <th>Description</th>
                                <th>Amount (Rs)</th>
                                <th>Added By</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $sr = 1;
                            mysqli_data_seek($payable_result, 0);
                            if(mysqli_num_rows($payable_result) > 0):
                                while($row = mysqli_fetch_assoc($payable_result)): 
                            ?>
                                <tr>
                                    <td><?php echo $sr++; ?></td>
                                    <td><?php echo date('d-m-Y', strtotime($row['date_time'])); ?></td>
                                    <td><?php echo htmlspecialchars($row['description'] ?: '—'); ?></td>
                                    <td class="debit-amount">Rs <?php echo number_format($row['amount'], 2); ?></td>
                                    <td><?php echo htmlspecialchars($row['user_name']); ?></td>
                                    <td>
                                        <a href="?id=<?php echo $gp_id; ?>&del_payable=<?php echo $row['id']; ?>" 
                                           class="btn-action btn-delete" 
                                           onclick="return confirm('Delete this record?')">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php 
                                endwhile;
                            else:
                            ?>
                                <tr><td colspan="6" class="empty-state">No payable records found</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Tab Content: Paid -->
    <div id="tab-paid" class="tab-content">
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info">
                    <i class="fas fa-arrow-down"></i>
                    <h4>Paid Records (Party paid to us)</h4>
                </div>
                <div class="table-stats">Total: Rs <?php echo number_format($total_paid, 2); ?></div>
            </div>
            <div class="table-card-body">
                <div class="table-responsive">
                    <table class="modern-table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Date</th>
                                <th>Description</th>
                                <th>Amount (Rs)</th>
                                <th>Payment Method</th>
                                <th>Added By</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $sr = 1;
                            mysqli_data_seek($paid_result, 0);
                            if(mysqli_num_rows($paid_result) > 0):
                                while($row = mysqli_fetch_assoc($paid_result)): 
                            ?>
                                <tr>
                                    <td><?php echo $sr++; ?></td>
                                    <td><?php echo date('d-m-Y', strtotime($row['date_time'])); ?></td>
                                    <td><?php echo htmlspecialchars($row['description'] ?: '—'); ?></td>
                                    <td class="credit-amount">Rs <?php echo number_format($row['amount'], 2); ?></td>
                                    <td><span class="method-badge"><?php echo ucfirst($row['payment_method']); ?></span></td>
                                    <td><?php echo htmlspecialchars($row['user_name']); ?></td>
                                    <td>
                                        <a href="?id=<?php echo $gp_id; ?>&del_paid=<?php echo $row['id']; ?>" 
                                           class="btn-action btn-delete" 
                                           onclick="return confirm('Delete this record?')">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php 
                                endwhile;
                            else:
                            ?>
                                <tr><td colspan="7" class="empty-state">No paid records found</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Tab Content: Received -->
    <div id="tab-received" class="tab-content">
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info">
                    <i class="fas fa-hand-holding-usd"></i>
                    <h4>Received Records (We paid to party)</h4>
                </div>
                <div class="table-stats">Total: Rs <?php echo number_format($total_received, 2); ?></div>
            </div>
            <div class="table-card-body">
                <div class="table-responsive">
                    <table class="modern-table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Date</th>
                                <th>Description</th>
                                <th>Amount (Rs)</th>
                                <th>Payment Method</th>
                                <th>Added By</th>
                                <th>Action</th>
                            </table>
                        </thead>
                        <tbody>
                            <?php 
                            $sr = 1;
                            mysqli_data_seek($received_result, 0);
                            if(mysqli_num_rows($received_result) > 0):
                                while($row = mysqli_fetch_assoc($received_result)): 
                            ?>
                                <tr>
                                    <td><?php echo $sr++; ?></td>
                                    <td><?php echo date('d-m-Y', strtotime($row['date_time'])); ?></td>
                                    <td><?php echo htmlspecialchars($row['description'] ?: '—'); ?></td>
                                    <td class="debit-amount">Rs <?php echo number_format($row['amount'], 2); ?></td>
                                    <td><span class="method-badge"><?php echo ucfirst($row['payment_method']); ?></span></td>
                                    <td><?php echo htmlspecialchars($row['user_name']); ?></td>
                                    <td>
                                        <a href="?id=<?php echo $gp_id; ?>&del_received=<?php echo $row['id']; ?>" 
                                           class="btn-action btn-delete" 
                                           onclick="return confirm('Delete this record?')">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php 
                                endwhile;
                            else:
                            ?>
                                <tr><td colspan="7" class="empty-state">No received records found</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- MODALS -->

<!-- Opening Modal -->
<div class="modal fade" id="openModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-play-circle"></i> Add Opening Balance</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <div class="form-group">
                        <label>Amount (Rs) *</label>
                        <input type="number" step="0.01" name="amount" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Date *</label>
                        <input type="date" name="date_time" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Notes</label>
                        <textarea name="notes" class="form-control" rows="2" placeholder="Optional notes"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_opening" class="btn btn-primary" style="background:#A04657;">Add Opening</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Payable Modal -->
<div class="modal fade" id="payableModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-arrow-up"></i> Add Payable</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <div class="form-group">
                        <label>Amount (Rs) *</label>
                        <input type="number" step="0.01" name="amount" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Date *</label>
                        <input type="date" name="date_time" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Description</label>
                        <textarea name="description" class="form-control" rows="2" placeholder="What is this payable for?"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_payable" class="btn btn-primary" style="background:#A04657;">Add Payable</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Paid Modal -->
<div class="modal fade" id="paidModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-check-circle"></i> Add Paid (Party gave us money)</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <div class="form-group">
                        <label>Amount (Rs) *</label>
                        <input type="number" step="0.01" name="amount" class="form-control" required>
                        <small>Max payable: Rs <?php echo number_format($closing_balance, 2); ?></small>
                    </div>
                    <div class="form-group">
                        <label>Date *</label>
                        <input type="date" name="date_time" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Payment Method</label>
                        <select name="payment_method" class="form-control">
                            <option value="cash">Cash</option>
                            <option value="bank">Bank Transfer</option>
                            <option value="cheque">Cheque</option>
                            <option value="online">Online</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Description</label>
                        <textarea name="description" class="form-control" rows="2" placeholder="Reference/notes"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_paid" class="btn btn-primary" style="background:#A04657;">Add Paid</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Received Modal -->
<div class="modal fade" id="receivedModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-hand-holding-usd"></i> Add Received (We gave money to party)</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <div class="form-group">
                        <label>Amount (Rs) *</label>
                        <input type="number" step="0.01" name="amount" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Date *</label>
                        <input type="date" name="date_time" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Payment Method</label>
                        <select name="payment_method" class="form-control">
                            <option value="cash">Cash</option>
                            <option value="bank">Bank Transfer</option>
                            <option value="cheque">Cheque</option>
                            <option value="online">Online</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Description</label>
                        <textarea name="description" class="form-control" rows="2" placeholder="Reference/notes"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_received" class="btn btn-primary" style="background:#A04657;">Add Received</button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
/* GP 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;
    --debit: #dc3545;
    --credit: #28a745;
    --payable: #ff9800;
    --gray-100: #f8f9fc;
    --gray-200: #e9ecef;
    --gray-800: #343a40;
}

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

body {
    background: #f0f2f5;
}

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

.gp-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 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;
}

/* Party Info Banner */
.party-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);
}

.party-icon i {
    font-size: 48px;
    color: var(--primary);
    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;
}

.info-tag i {
    color: var(--primary);
    margin-right: 5px;
}

.party-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: #666;
    display: block;
}

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

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

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

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

.btn-open { background: #6c5ce7; color: white; }
.btn-payable { background: #ff9800; color: white; }
.btn-paid { background: #28a745; color: white; }
.btn-received { background: #17a2b8; color: white; }
.btn-back { background: var(--gray-200); color: var(--gray-800); }

.btn-action-modal:hover {
    transform: translateY(-2px);
    filter: brightness(0.95);
    text-decoration: none;
    color: white;
}

.btn-back:hover { color: var(--gray-800); }

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

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

.summary-card:hover {
    transform: translateY(-3px);
}

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

.summary-icon i { font-size: 24px; }
.open-icon { background: rgba(108,92,231,0.1); }
.open-icon i { color: #6c5ce7; }
.payable-icon { background: rgba(255,152,0,0.1); }
.payable-icon i { color: #ff9800; }
.paid-icon { background: rgba(40,167,69,0.1); }
.paid-icon i { color: #28a745; }
.received-icon { background: rgba(23,162,184,0.1); }
.received-icon i { color: #17a2b8; }

.summary-content h4 {
    margin: 0;
    font-size: 20px;
    font-weight: 800;
}

.summary-content p {
    margin: 3px 0 0;
    font-size: 12px;
    color: #666;
}

.summary-content small {
    font-size: 10px;
    color: #999;
}

/* Tab Navigation */
.tab-navigation {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 24px;
    background: white;
    padding: 12px 20px;
    border-radius: 60px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.tab-btn {
    padding: 8px 24px;
    border-radius: 40px;
    font-weight: 600;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.2s;
    background: var(--gray-100);
    color: #666;
}

.tab-btn i { margin-right: 8px; }
.tab-btn:hover { background: var(--gray-200); }
.tab-btn.active {
    background: var(--primary);
    color: white;
}

/* Tab Content */
.tab-content { display: none; }
.tab-content.active { display: block; }

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

.table-card-header {
    padding: 16px 24px;
    border-bottom: 1px solid var(--gray-200);
    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: 20px;
    color: var(--primary);
}

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

.table-stats {
    font-size: 13px;
    font-weight: 600;
    color: var(--primary);
}

.modern-table {
    width: 100%;
    border-collapse: collapse;
}

.modern-table th {
    padding: 12px 16px;
    background: var(--gray-100);
    font-weight: 700;
    color: #555;
    font-size: 12px;
    text-transform: uppercase;
    border-bottom: 1px solid var(--gray-200);
}

.modern-table td {
    padding: 12px 16px;
    border-bottom: 1px solid var(--gray-200);
    font-size: 13px;
}

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

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

.btn-action {
    width: 32px;
    height: 32px;
    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: white;
    transform: scale(1.05);
}

/* Alert Styles */
.alert-custom {
    padding: 14px 22px;
    border-radius: 16px;
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.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;
}

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

/* Modal Styles */
.modal-content {
    border-radius: 20px;
    overflow: hidden;
}

.modal-header {
    background: var(--primary);
    color: white;
    border-bottom: none;
}

.modal-header .close {
    color: white;
    opacity: 0.8;
}

.form-group {
    margin-bottom: 16px;
}

.form-group label {
    font-weight: 600;
    font-size: 13px;
    margin-bottom: 6px;
    display: block;
}

.form-control {
    border: 1.5px solid var(--gray-200);
    border-radius: 12px;
    padding: 10px 14px;
}

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

/* Responsive */
@media (max-width: 768px) {
    .gp-ledger-container { padding: 0 12px; }
    .party-info-banner { flex-direction: column; text-align: center; }
    .party-meta { justify-content: center; }
    .action-buttons-bar { justify-content: center; }
    .summary-cards { grid-template-columns: repeat(2, 1fr); }
    .tab-navigation { border-radius: 20px; justify-content: center; }
    .modern-table th { display: none; }
    .modern-table td {
        display: block;
        text-align: right;
        padding-left: 50%;
        position: relative;
    }
    .modern-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 16px;
        width: 45%;
        text-align: left;
        font-weight: 700;
        font-size: 11px;
    }
    .modern-table tr {
        display: block;
        margin-bottom: 12px;
        border: 1px solid var(--gray-200);
        border-radius: 12px;
        overflow: hidden;
    }
}
</style>

<script>
// Tab switching
document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
        this.classList.add('active');
        document.getElementById(this.dataset.tab).classList.add('active');
    });
});

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

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