<?php
// admin/accounts/po-payments.php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!isAdmin()) {
    header('Location: ../login.php');
    exit;
}

// Handle Add PO Payment
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_po_payment'])) {
    $po_id = intval($_POST['po_id'] ?? 0);
    $vendor_id = intval($_POST['vendor_id'] ?? 0);
    $amount = floatval($_POST['amount'] ?? 0);
    $payment_method = sanitize($_POST['payment_method'] ?? 'cash');
    $reference_no = sanitize($_POST['reference_no'] ?? '');
    $payment_date = $_POST['payment_date'] ?? date('Y-m-d');
    $note = sanitize($_POST['note'] ?? '');
    
    // Validate
    if ($po_id <= 0) {
        $_SESSION['error_msg'] = 'Please select a Purchase Order';
    } elseif ($vendor_id <= 0) {
        $_SESSION['error_msg'] = 'Please select a Vendor';
    } elseif ($amount <= 0) {
        $_SESSION['error_msg'] = 'Amount must be greater than 0';
    } else {
        try {
            // Check if PO exists
            $stmt = $pdo->prepare("SELECT total, paid_amount, due_amount FROM purchase_orders WHERE id = ?");
            $stmt->execute([$po_id]);
            $po = $stmt->fetch();
            
            if (!$po) {
                $_SESSION['error_msg'] = 'Purchase Order not found';
            } elseif ($amount > $po['due_amount']) {
                $_SESSION['error_msg'] = 'Amount cannot exceed due amount (' . number_format($po['due_amount']) . ' TK)';
            } else {
                // Generate payment number
                $payment_no = 'PPMT-' . date('Ymd') . '-' . rand(1000, 9999);
                
                // Insert payment
                $stmt = $pdo->prepare("INSERT INTO po_payments 
                    (payment_no, po_id, vendor_id, amount, payment_method, reference_no, payment_date, note, created_by) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                
                $result = $stmt->execute([
                    $payment_no, 
                    $po_id, 
                    $vendor_id, 
                    $amount, 
                    $payment_method, 
                    $reference_no, 
                    $payment_date, 
                    $note, 
                    $_SESSION['admin_id']
                ]);
                
                if ($result) {
                    // Update PO paid amount
                    $new_paid = $po['paid_amount'] + $amount;
                    $new_due = $po['total'] - $new_paid;
                    
                    $stmt = $pdo->prepare("UPDATE purchase_orders SET paid_amount = ?, due_amount = ? WHERE id = ?");
                    $stmt->execute([$new_paid, $new_due, $po_id]);
                    
                    // Update PO status
                    if ($new_paid >= $po['total']) {
                        $stmt = $pdo->prepare("UPDATE purchase_orders SET status = 'paid' WHERE id = ?");
                        $stmt->execute([$po_id]);
                    } elseif ($new_paid > 0) {
                        $stmt = $pdo->prepare("UPDATE purchase_orders SET status = 'partial' WHERE id = ?");
                        $stmt->execute([$po_id]);
                    }
                    
                    $_SESSION['success_msg'] = 'PO Payment added successfully!';
                } else {
                    $_SESSION['error_msg'] = 'Failed to insert payment record';
                }
            }
        } catch (Exception $e) {
            $_SESSION['error_msg'] = 'Error: ' . $e->getMessage();
        }
    }
    
    header('Location: po-payments.php');
    exit;
}

// Handle Delete via AJAX
if (isset($_POST['delete_id'])) {
    $delete_id = intval($_POST['delete_id']);
    
    // Get payment details
    $stmt = $pdo->prepare("SELECT po_id, amount FROM po_payments WHERE id = ?");
    $stmt->execute([$delete_id]);
    $payment = $stmt->fetch();
    
    if ($payment) {
        $stmt = $pdo->prepare("DELETE FROM po_payments WHERE id = ?");
        $stmt->execute([$delete_id]);
        
        // Update PO paid amount
        $stmt = $pdo->prepare("SELECT total, paid_amount FROM purchase_orders WHERE id = ?");
        $stmt->execute([$payment['po_id']]);
        $po = $stmt->fetch();
        
        if ($po) {
            $new_paid = $po['paid_amount'] - $payment['amount'];
            $new_due = $po['total'] - $new_paid;
            
            $stmt = $pdo->prepare("UPDATE purchase_orders SET paid_amount = ?, due_amount = ? WHERE id = ?");
            $stmt->execute([$new_paid, $new_due, $payment['po_id']]);
            
            // Update PO status
            if ($new_paid <= 0) {
                $stmt = $pdo->prepare("UPDATE purchase_orders SET status = 'pending' WHERE id = ?");
                $stmt->execute([$payment['po_id']]);
            } elseif ($new_paid < $po['total']) {
                $stmt = $pdo->prepare("UPDATE purchase_orders SET status = 'partial' WHERE id = ?");
                $stmt->execute([$payment['po_id']]);
            } else {
                $stmt = $pdo->prepare("UPDATE purchase_orders SET status = 'paid' WHERE id = ?");
                $stmt->execute([$payment['po_id']]);
            }
        }
    }
    
    echo json_encode(['success' => true]);
    exit;
}

// Get PO Payments
$stmt = $pdo->query("
    SELECT pp.*, v.name as vendor_name, po.po_no 
    FROM po_payments pp 
    LEFT JOIN vendors v ON pp.vendor_id = v.id 
    LEFT JOIN purchase_orders po ON pp.po_id = po.id 
    ORDER BY pp.created_at DESC
");
$payments = $stmt->fetchAll();

// Get POs for dropdown
$pos = $pdo->query("
    SELECT id, po_no, vendor_id, total, paid_amount, due_amount 
    FROM purchase_orders 
    WHERE status NOT IN ('paid', 'cancelled') 
    ORDER BY po_no
")->fetchAll();

// Get vendors for dropdown
$vendors = $pdo->query("SELECT id, name FROM vendors WHERE status = 1 ORDER BY name")->fetchAll();

// Get totals
$stmt = $pdo->query("SELECT COALESCE(SUM(amount), 0) as total FROM po_payments");
$total_payments = $stmt->fetch()['total'];

$stmt = $pdo->query("SELECT COALESCE(SUM(amount), 0) as total FROM po_payments WHERE MONTH(payment_date) = MONTH(CURDATE()) AND YEAR(payment_date) = YEAR(CURDATE())");
$monthly_payments = $stmt->fetch()['total'];

$success_msg = $_SESSION['success_msg'] ?? '';
$error_msg = $_SESSION['error_msg'] ?? '';
unset($_SESSION['success_msg']);
unset($_SESSION['error_msg']);

include '../header.php';
?>

<style>
.account-nav {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 20px;
    padding: 15px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.account-nav a {
    padding: 8px 20px;
    border-radius: 8px;
    color: #64748b;
    text-decoration: none;
    transition: all 0.3s ease;
}

.account-nav a:hover,
.account-nav a.active {
    background: #047dc3;
    color: #fff;
}

.stat-card {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    text-align: center;
}

.stat-card .stat-number {
    font-size: 28px;
    font-weight: 700;
}

.stat-card .stat-label {
    font-size: 14px;
    color: #64748b;
}

.stat-card .stat-icon {
    font-size: 32px;
    margin-bottom: 10px;
}

.stat-card.text-warning .stat-number { color: #f59e0b; }
.stat-card.text-success .stat-number { color: #22c55e; }
.stat-card.text-primary .stat-number { color: #3b82f6; }

.payment-table td {
    vertical-align: middle;
}

.alert-container {
    margin-bottom: 20px;
}

/* Modal Styles */
.modal-lg {
    max-width: 800px;
}

.form-control:focus {
    border-color: #047dc3;
    box-shadow: 0 0 0 3px rgba(4,125,195,0.1);
}

.due-amount {
    font-size: 12px;
    color: #94a3b8;
    margin-top: 4px;
    display: block;
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-hand-holding-dollar text-warning me-2"></i> PO Payments</h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#poPaymentModal">
            <i class="fa-solid fa-plus"></i> Add Payment
        </button>
    </div>
    
    <!-- Navigation -->
    <div class="account-nav">
        <a href="dashboard.php"><i class="fa-solid fa-chart-pie"></i> Dashboard</a>
        <a href="income.php"><i class="fa-solid fa-arrow-down"></i> Income</a>
        <a href="expenses.php"><i class="fa-solid fa-arrow-up"></i> Expenses</a>
        <a href="invoices.php"><i class="fa-solid fa-file-invoice"></i> Invoices</a>
        <a href="purchase-orders.php"><i class="fa-solid fa-file-purchase"></i> Purchase Orders</a>
        <a href="vendors.php"><i class="fa-solid fa-building"></i> Vendors</a>
        <a href="po-payments.php" class="active"><i class="fa-solid fa-hand-holding-dollar"></i> PO Payments</a>
        <a href="reports.php"><i class="fa-solid fa-chart-bar"></i> Reports</a>
    </div>
    
    <!-- Stats -->
    <div class="row g-4 mb-4">
        <div class="col-lg-4 col-md-6">
            <div class="stat-card text-warning">
                <div class="stat-icon"><i class="fa-solid fa-coins"></i></div>
                <div class="stat-number"><?php echo number_format($total_payments); ?> TK</div>
                <div class="stat-label">Total Payments</div>
            </div>
        </div>
        <div class="col-lg-4 col-md-6">
            <div class="stat-card text-success">
                <div class="stat-icon"><i class="fa-solid fa-calendar"></i></div>
                <div class="stat-number"><?php echo number_format($monthly_payments); ?> TK</div>
                <div class="stat-label">This Month</div>
            </div>
        </div>
        <div class="col-lg-4 col-md-6">
            <div class="stat-card text-primary">
                <div class="stat-icon"><i class="fa-solid fa-list"></i></div>
                <div class="stat-number"><?php echo count($payments); ?></div>
                <div class="stat-label">Total Records</div>
            </div>
        </div>
    </div>
    
    <!-- Alert Container -->
    <div id="alertContainer" class="alert-container"></div>
    
    <?php if ($success_msg): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fa-solid fa-check-circle me-2"></i> <?php echo htmlspecialchars($success_msg); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    
    <?php if ($error_msg): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fa-solid fa-exclamation-circle me-2"></i> <?php echo htmlspecialchars($error_msg); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    
    <!-- Payment List -->
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0">All PO Payments (<?php echo count($payments); ?>)</h5>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover payment-table mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Payment No</th>
                            <th>PO No</th>
                            <th>Vendor</th>
                            <th>Amount</th>
                            <th>Method</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="paymentsTableBody">
                        <?php if (empty($payments)): ?>
                        <tr>
                            <td colspan="7" class="text-center py-4">
                                <i class="fa-solid fa-inbox fa-2x text-muted d-block mb-2"></i>
                                No PO payments found
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($payments as $payment): ?>
                        <tr id="paymentRow_<?php echo $payment['id']; ?>">
                            <td><code><?php echo $payment['payment_no']; ?></code></td>
                            <td><?php echo $payment['po_no'] ?? 'N/A'; ?></td>
                            <td><?php echo $payment['vendor_name'] ?? 'N/A'; ?></td>
                            <td class="text-warning fw-bold"><?php echo number_format($payment['amount']); ?> TK</td>
                            <td><span class="badge bg-secondary"><?php echo ucfirst($payment['payment_method']); ?></span></td>
                            <td><?php echo date('d M Y', strtotime($payment['payment_date'])); ?></td>
                            <td>
                                <button onclick="deletePayment(<?php echo $payment['id']; ?>)" class="btn btn-sm btn-danger">
                                    <i class="fa-solid fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add PO Payment Modal -->
<div class="modal fade" id="poPaymentModal" tabindex="-1" aria-labelledby="poPaymentModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="poPaymentModalLabel">
                    <i class="fa-solid fa-plus-circle me-2"></i> Add PO Payment
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" id="poPaymentForm" action="po-payments.php">
                <input type="hidden" name="add_po_payment" value="1">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Purchase Order <span class="text-danger">*</span></label>
                                <select name="po_id" id="po_id" class="form-control" required>
                                    <option value="">Select PO</option>
                                    <?php foreach ($pos as $po): ?>
                                    <option value="<?php echo $po['id']; ?>" data-vendor="<?php echo $po['vendor_id']; ?>" data-due="<?php echo $po['due_amount']; ?>">
                                        <?php echo $po['po_no']; ?> (Due: <?php echo number_format($po['due_amount']); ?> TK)
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Vendor <span class="text-danger">*</span></label>
                                <select name="vendor_id" id="vendor_id" class="form-control" required>
                                    <option value="">Select Vendor</option>
                                    <?php foreach ($vendors as $vendor): ?>
                                    <option value="<?php echo $vendor['id']; ?>"><?php echo htmlspecialchars($vendor['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Amount <span class="text-danger">*</span></label>
                                <input type="number" name="amount" id="payment_amount" class="form-control" step="0.01" placeholder="0.00" required>
                                <small class="due-amount" id="dueAmountDisplay"></small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Payment Method</label>
                                <select name="payment_method" class="form-control">
                                    <option value="cash">Cash</option>
                                    <option value="bank">Bank Transfer</option>
                                    <option value="bkash">Bkash</option>
                                    <option value="nagad">Nagad</option>
                                    <option value="rocket">Rocket</option>
                                    <option value="card">Card</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Payment Date</label>
                                <input type="date" name="payment_date" class="form-control" value="<?php echo date('Y-m-d'); ?>">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Reference No</label>
                                <input type="text" name="reference_no" class="form-control" placeholder="Reference number">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Note</label>
                                <textarea name="note" class="form-control" rows="2" placeholder="Additional notes"></textarea>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="submitPaymentBtn">
                        <i class="fa-solid fa-save"></i> Save Payment
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// ========================================
// UPDATE VENDOR AND DUE ON PO SELECT
// ========================================
document.getElementById('po_id').addEventListener('change', function() {
    var selectedOption = this.options[this.selectedIndex];
    var vendorId = selectedOption.getAttribute('data-vendor');
    var dueAmount = selectedOption.getAttribute('data-due');
    
    var vendorSelect = document.getElementById('vendor_id');
    var dueDisplay = document.getElementById('dueAmountDisplay');
    
    if (vendorId) {
        vendorSelect.value = vendorId;
        if (dueAmount !== null) {
            dueDisplay.textContent = 'Due amount: ' + parseFloat(dueAmount).toFixed(2) + ' TK';
        } else {
            dueDisplay.textContent = '';
        }
    } else {
        vendorSelect.value = '';
        dueDisplay.textContent = '';
    }
});

// ========================================
// DELETE PAYMENT
// ========================================
function deletePayment(id) {
    if (!confirm('Are you sure you want to delete this payment?')) return;
    
    var formData = new FormData();
    formData.append('delete_id', id);
    
    fetch('po-payments.php', {
        method: 'POST',
        body: formData
    })
    .then(function(response) {
        return response.json();
    })
    .then(function(data) {
        if (data.success) {
            var row = document.getElementById('paymentRow_' + id);
            if (row) {
                row.style.transition = 'all 0.5s ease';
                row.style.opacity = '0';
                setTimeout(function() {
                    row.remove();
                    var count = document.querySelectorAll('#paymentsTableBody tr').length - 1;
                    if (count === 0) {
                        document.getElementById('paymentsTableBody').innerHTML = `
                            <tr><td colspan="7" class="text-center py-4">
                                <i class="fa-solid fa-inbox fa-2x text-muted d-block mb-2"></i>
                                No PO payments found
                            </td></tr>
                        `;
                    }
                }, 500);
            }
            showToast('Payment deleted successfully!', 'success');
        } else {
            showToast('Failed to delete payment', 'error');
        }
    })
    .catch(function(error) {
        showToast('Something went wrong', 'error');
    });
}

// ========================================
// SHOW TOAST
// ========================================
function showToast(message, type) {
    var colors = {
        success: '#22c55e',
        error: '#ef4444',
        warning: '#f59e0b'
    };
    
    var toast = document.createElement('div');
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 24px;
        background: ${colors[type] || '#3b82f6'};
        color: #fff;
        border-radius: 8px;
        z-index: 9999;
        box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        animation: slideIn 0.3s ease;
        max-width: 400px;
        font-size: 14px;
    `;
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(function() {
        toast.style.opacity = '0';
        toast.style.transition = 'opacity 0.3s ease';
        setTimeout(function() { toast.remove(); }, 300);
    }, 3000);
}

// ========================================
= MESSAGE DISPLAY ON PAGE LOAD
// ========================================
document.addEventListener('DOMContentLoaded', function() {
    // Auto hide alerts after 5 seconds
    var alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        setTimeout(function() {
            if (alert) {
                alert.style.transition = 'opacity 0.5s ease';
                alert.style.opacity = '0';
                setTimeout(function() { alert.remove(); }, 500);
            }
        }, 5000);
    });
    
    // Show success message if exists
    var successMsg = document.querySelector('.alert-success');
    if (successMsg) {
        showToast(successMsg.textContent.trim(), 'success');
    }
    
    // Show error message if exists
    var errorMsg = document.querySelector('.alert-danger');
    if (errorMsg) {
        showToast(errorMsg.textContent.trim(), 'error');
    }
});

// ========================================
// ADD CSS ANIMATION
// ========================================
var style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0%); opacity: 1; }
    }
`;
document.head.appendChild(style);
</script>

<?php include '../footer.php'; ?>