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

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

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

// Get all general parties
$parties_sql = "SELECT * FROM general_parties ORDER BY gp_name";
$parties_result = mysqli_query($conn, $parties_sql);

// Get party details if ID exists
if($gp_id > 0) {
    $party_sql = "SELECT * FROM general_parties WHERE id = '$gp_id'";
    $party_result = mysqli_query($conn, $party_sql);
    $general_party = mysqli_fetch_assoc($party_result);
}

// Add Payable (Create new payable entry)
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_payable'])) {
    $gp_id = mysqli_real_escape_string($conn, $_POST['gp_id']);
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    $user_name = $_SESSION['username'];
    $date_time = date('Y-m-d');
    $date_created = date('Y-m-d H:i:s');
    
    if(empty($gp_id)) {
        $error_message = "Please select a general party!";
    } elseif($amount <= 0) {
        $error_message = "Amount must be greater than 0!";
    } else {
        mysqli_begin_transaction($conn);
        
        try {
            // Get GP name
            $gp_name_sql = "SELECT gp_name FROM general_parties WHERE id = '$gp_id'";
            $gp_name_result = mysqli_query($conn, $gp_name_sql);
            $gp_name_data = mysqli_fetch_assoc($gp_name_result);
            $gp_name = $gp_name_data['gp_name'];
            
            // 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', '$user_name', '$date_created')";
            
            if(!mysqli_query($conn, $sql)) {
                throw new Exception("Failed to insert payable record: " . mysqli_error($conn));
            }
            
            // Update general party balance
            $update_party = "UPDATE general_parties SET current_balance = current_balance + $amount WHERE id = '$gp_id'";
            if(!mysqli_query($conn, $update_party)) {
                throw new Exception("Failed to update party balance");
            }
            
            mysqli_commit($conn);
            $success_message = "Payable of Rs " . number_format($amount, 2) . " recorded successfully!";
            
            // Refresh party data
            $party_sql = "SELECT * FROM general_parties WHERE id = '$gp_id'";
            $party_result = mysqli_query($conn, $party_sql);
            $general_party = mysqli_fetch_assoc($party_result);
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    }
}

// Delete Payable
if(isset($_GET['delete_payable'])) {
    $delete_id = mysqli_real_escape_string($conn, $_GET['delete_payable']);
    
    // Get payable details to reverse balance
    $get_sql = "SELECT * FROM gp_payable WHERE id = '$delete_id'";
    $get_result = mysqli_query($conn, $get_sql);
    $payable_data = mysqli_fetch_assoc($get_result);
    
    if($payable_data) {
        mysqli_begin_transaction($conn);
        
        try {
            // Reverse party balance
            $reverse_party = "UPDATE general_parties SET current_balance = current_balance - " . $payable_data['amount'] . " WHERE id = '" . $payable_data['gp_id'] . "'";
            mysqli_query($conn, $reverse_party);
            
            // Delete payable record
            $sql = "DELETE FROM gp_payable WHERE id = '$delete_id'";
            if(!mysqli_query($conn, $sql)) {
                throw new Exception("Error deleting payable record");
            }
            
            mysqli_commit($conn);
            $success_message = "Payable record deleted successfully!";
            
            // Refresh party data
            $party_sql = "SELECT * FROM general_parties WHERE id = '" . $payable_data['gp_id'] . "'";
            $party_result = mysqli_query($conn, $party_sql);
            $general_party = mysqli_fetch_assoc($party_result);
            
            // Refresh gp_id
            $gp_id = $payable_data['gp_id'];
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    }
}

// Get payable records for selected party
$payable_records = [];
$total_payable = 0;

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

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>General Party Ledger - Add Payable</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap');
        
        * {
            font-family: 'Poppins', sans-serif;
        }
        
        h1, h2, h3, h4, h5, h6 {
            font-family: 'Times New Roman', serif;
        }
        
        body {
            background: #f5f5f5;
        }
        
        .page-header {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            border-radius: 15px;
            padding: 25px 30px;
            margin-bottom: 30px;
            color: #fff;
        }
        
        .page-header h2 {
            margin: 0 0 8px 0;
            font-size: 28px;
            color: #fff;
        }
        
        .page-header p {
            margin: 0;
            opacity: 0.95;
            font-weight: 500;
        }
        
        .form-card, .table-card {
            background: #fff;
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            overflow: hidden;
            margin-bottom: 30px;
        }
        
        .card-header-custom {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            padding: 15px 20px;
            color: #fff;
        }
        
        .card-header-custom h4 {
            margin: 0;
            font-size: 18px;
        }
        
        .card-header-custom i {
            margin-right: 10px;
        }
        
        .card-body-custom {
            padding: 25px;
        }
        
        .form-label {
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
        }
        
        .form-label i {
            color: #A04657;
            margin-right: 8px;
        }
        
        .form-control, .form-select {
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 12px 15px;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #A04657;
            box-shadow: 0 0 0 3px rgba(160,70,87,0.1);
        }
        
        .btn-submit {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            color: #fff;
            border: none;
            padding: 12px 30px;
            border-radius: 10px;
            font-weight: 600;
            font-size: 16px;
            cursor: pointer;
            width: 100%;
        }
        
        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(160,70,87,0.3);
            color: #fff;
        }
        
        .btn-back {
            background: #6c757d;
            color: #fff;
            padding: 8px 20px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
        }
        
        .btn-back:hover {
            background: #5a6268;
            color: #fff;
        }
        
        .alert-custom {
            padding: 15px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: 500;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border-left: 4px solid #28a745;
        }
        
        .alert-danger {
            background: #f8d7da;
            color: #721c24;
            border-left: 4px solid #dc3545;
        }
        
        .party-info-card {
            background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 20px;
            border-left: 4px solid #28a745;
        }
        
        .info-row {
            display: flex;
            justify-content: space-between;
            padding: 6px 0;
        }
        
        .info-row span {
            font-size: 13px;
            color: #2e7d32;
            font-weight: 500;
        }
        
        .info-row strong {
            font-size: 14px;
            color: #1b5e20;
            font-weight: 600;
        }
        
        .balance-card {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 20px;
            border-left: 4px solid #A04657;
        }
        
        .balance-row {
            display: flex;
            justify-content: space-between;
            padding: 6px 0;
        }
        
        .text-danger {
            color: #dc3545 !important;
        }
        
        .text-success {
            color: #28a745 !important;
        }
        
        .table th {
            background: #f8f9fa;
            font-weight: 700;
            color: #444;
            border-bottom: 2px solid #dee2e6;
        }
        
        .table td {
            vertical-align: middle;
            font-weight: 500;
        }
        
        .amount-negative {
            color: #dc3545;
            font-weight: 700;
        }
        
        .btn-action {
            padding: 5px 12px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 12px;
            font-weight: 600;
            display: inline-block;
        }
        
        .btn-delete {
            background: #fee;
            color: #dc3545;
        }
        
        .btn-delete:hover {
            background: #dc3545;
            color: #fff;
        }
        
        .required {
            color: #dc3545;
        }
        
        .section-divider {
            margin-top: 20px;
            margin-bottom: 15px;
        }
        
        @media (max-width: 768px) {
            .page-header {
                padding: 20px;
            }
            
            .page-header h2 {
                font-size: 22px;
            }
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="page-header">
        <div>
            <h2><i class="fas fa-address-book"></i> General Party Ledger</h2>
            <p>Add and manage payables for general parties</p>
        </div>
        <div>
            <a href="general_parties.php" class="btn-back">
                <i class="fas fa-arrow-left"></i> Back to Parties
            </a>
        </div>
    </div>
    
    <?php if($success_message): ?>
        <div class="alert-custom alert-success">
            <i class="fas fa-check-circle fa-lg"></i> <?php echo $success_message; ?>
        </div>
    <?php endif; ?>
    
    <?php if($error_message): ?>
        <div class="alert-custom alert-danger">
            <i class="fas fa-exclamation-triangle fa-lg"></i> <?php echo $error_message; ?>
        </div>
    <?php endif; ?>
    
    <div class="row">
        <!-- Left Column - Party Selection & Add Payable Form -->
        <div class="col-lg-5">
            <div class="form-card">
                <div class="card-header-custom">
                    <h4><i class="fas fa-building"></i> Select General Party</h4>
                </div>
                <div class="card-body-custom">
                    <form method="GET" action="">
                        <div class="mb-3">
                            <label class="form-label"><i class="fas fa-users"></i> Select Party</label>
                            <select name="gp_id" id="gp_id" class="form-select" onchange="this.form.submit()">
                                <option value="">-- Select General Party --</option>
                                <?php 
                                mysqli_data_seek($parties_result, 0);
                                while($party = mysqli_fetch_assoc($parties_result)): 
                                    $selected = ($gp_id == $party['id']) ? 'selected' : '';
                                ?>
                                    <option value="<?php echo $party['id']; ?>" <?php echo $selected; ?>>
                                        <?php echo htmlspecialchars($party['gp_name']); ?> (ID: <?php echo $party['gp_id']; ?>)
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                    </form>
                    
                    <?php if($general_party && $gp_id > 0): ?>
                        <div class="party-info-card">
                            <div class="info-row">
                                <span><i class="fas fa-id-card"></i> Party ID:</span>
                                <strong><?php echo htmlspecialchars($general_party['gp_id']); ?></strong>
                            </div>
                            <div class="info-row">
                                <span><i class="fas fa-building"></i> Party Name:</span>
                                <strong><?php echo htmlspecialchars($general_party['gp_name']); ?></strong>
                            </div>
                            <div class="info-row">
                                <span><i class="fas fa-map-marker-alt"></i> Address:</span>
                                <strong><?php echo htmlspecialchars($general_party['gp_address'] ?: 'N/A'); ?></strong>
                            </div>
                            <div class="info-row">
                                <span><i class="fas fa-phone"></i> Phone:</span>
                                <strong><?php echo htmlspecialchars($general_party['gp_phone'] ?: 'N/A'); ?></strong>
                            </div>
                        </div>
                        
                        <div class="balance-card">
                            <div class="balance-row">
                                <span>Opening Balance:</span>
                                <strong>Rs <?php echo number_format($general_party['opening_balance'] ?? 0, 2); ?></strong>
                            </div>
                            <div class="balance-row">
                                <span>Total Payable Added:</span>
                                <strong class="text-danger">Rs <?php echo number_format($total_payable, 2); ?></strong>
                            </div>
                            <div class="balance-row">
                                <span>Current Balance:</span>
                                <strong class="<?php echo $general_party['current_balance'] > 0 ? 'text-danger' : 'text-success'; ?>">
                                    Rs <?php echo number_format($general_party['current_balance'], 2); ?>
                                </strong>
                            </div>
                        </div>
                        
                        <!-- Add Payable Form Only -->
                        <div class="card-header-custom section-divider" style="border-radius: 10px;">
                            <h4><i class="fas fa-plus-circle"></i> Add Payable</h4>
                        </div>
                        <form method="POST" action="" class="mt-2">
                            <input type="hidden" name="gp_id" value="<?php echo $gp_id; ?>">
                            <div class="mb-3">
                                <label class="form-label"><i class="fas fa-rupee-sign"></i> Amount <span class="required">*</span></label>
                                <input type="number" step="0.01" name="amount" class="form-control" placeholder="Enter amount" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label"><i class="fas fa-file-alt"></i> Description</label>
                                <textarea name="description" class="form-control" rows="2" placeholder="Reason for payable (e.g., Rent, Salary, Purchase)"></textarea>
                            </div>
                            <button type="submit" name="add_payable" class="btn-submit">
                                <i class="fas fa-save"></i> Add Payable
                            </button>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Right Column - Payable Records List -->
        <div class="col-lg-7">
            <?php if($general_party && $gp_id > 0): ?>
                <!-- Payable Records -->
                <div class="table-card">
                    <div class="card-header-custom">
                        <h4><i class="fas fa-list"></i> Payable Records</h4>
                    </div>
                    <div class="card-body-custom">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th width="5%">#</th>
                                        <th width="15%">Date</th>
                                        <th width="15%">Amount</th>
                                        <th width="40%">Description</th>
                                        <th width="15%">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if(count($payable_records) > 0): ?>
                                        <?php $sn = 1; foreach($payable_records as $record): ?>
                                            <tr>
                                                <td><?php echo $sn++; ?></td>
                                                <td><?php echo date('d-m-Y', strtotime($record['date_time'])); ?></td>
                                                <td class="amount-negative">Rs <?php echo number_format($record['amount'], 2); ?> </div>
                                                <td><?php echo htmlspecialchars($record['description'] ?: '—'); ?> </div>
                                                <td>
                                                    <a href="?gp_id=<?php echo $gp_id; ?>&delete_payable=<?php echo $record['id']; ?>" 
                                                       class="btn-action btn-delete" 
                                                       onclick="return confirm('Delete this payable record? This will affect the balance!')">
                                                        <i class="fas fa-trash"></i> Delete
                                                    </a>
                                                </div>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="5" class="text-center py-4">
                                                <i class="fas fa-arrow-up" style="font-size: 48px; color: #ccc;"></i>
                                                <p class="mt-3 mb-0">No payable records found</p>
                                                <small class="text-muted">Click "Add Payable" to create a new payable entry</small>
                                            </div>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                                <?php if(count($payable_records) > 0): ?>
                                <tfoot>
                                    <tr class="table-active">
                                        <td colspan="2"><strong>Total Payable</strong></td>
                                        <td class="amount-negative"><strong>Rs <?php echo number_format($total_payable, 2); ?></strong></td>
                                        <td colspan="2"></td>
                                    </tr>
                                </tfoot>
                                <?php endif; ?>
                            </table>
                        </div>
                    </div>
                </div>
            <?php else: ?>
                <div class="form-card">
                    <div class="card-body-custom text-center py-5">
                        <i class="fas fa-building" style="font-size: 64px; color: #ccc;"></i>
                        <h4 class="mt-3">Select a General Party</h4>
                        <p class="text-muted">Please select a general party from the dropdown to view and manage their payables</p>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

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

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