<?php
/**
 * buyer/payments.php - Payment Management (CRUD)
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/BuyerSystem.php';

if (!isLoggedIn() || getUserType() !== 'buyer') {
    header('Location: ' . APP_URL . '/auth/login.php');
    exit();
}

use App\Database;
$database = Database::getInstance();
$db = $database->getConnection();
$currentUserId = getUserId();
$buyerSystem = new BuyerSystem($database, $currentUserId);

// Handle CRUD operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $db->beginTransaction();
        
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'add_method':
                    $sql = "INSERT INTO buyer_payment_methods 
                            (buyer_id, payment_type, account_name, account_number, 
                             bank_name, mobile_network, is_default, created_at)
                            VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
                    $stmt = $db->prepare($sql);
                    $stmt->execute([
                        $currentUserId,
                        $_POST['payment_type'],
                        $_POST['account_name'],
                        $_POST['account_number'],
                        $_POST['bank_name'] ?? null,
                        $_POST['mobile_network'] ?? null,
                        isset($_POST['is_default']) ? 1 : 0
                    ]);
                    
                    // If set as default, unset others
                    if (isset($_POST['is_default'])) {
                        $sql = "UPDATE buyer_payment_methods SET is_default = 0 
                                WHERE buyer_id = ? AND id != ?";
                        $stmt = $db->prepare($sql);
                        $stmt->execute([$currentUserId, $db->lastInsertId()]);
                    }
                    
                    $_SESSION['flash_message'] = 'Payment method added successfully';
                    $_SESSION['flash_type'] = 'success';
                    break;
                    
                case 'update_method':
                    $sql = "UPDATE buyer_payment_methods SET
                            payment_type = ?, account_name = ?, account_number = ?,
                            bank_name = ?, mobile_network = ?, is_default = ?
                            WHERE id = ? AND buyer_id = ?";
                    $stmt = $db->prepare($sql);
                    $stmt->execute([
                        $_POST['payment_type'],
                        $_POST['account_name'],
                        $_POST['account_number'],
                        $_POST['bank_name'] ?? null,
                        $_POST['mobile_network'] ?? null,
                        isset($_POST['is_default']) ? 1 : 0,
                        $_POST['method_id'],
                        $currentUserId
                    ]);
                    
                    if (isset($_POST['is_default'])) {
                        $sql = "UPDATE buyer_payment_methods SET is_default = 0 
                                WHERE buyer_id = ? AND id != ?";
                        $stmt = $db->prepare($sql);
                        $stmt->execute([$currentUserId, $_POST['method_id']]);
                    }
                    
                    $_SESSION['flash_message'] = 'Payment method updated successfully';
                    $_SESSION['flash_type'] = 'success';
                    break;
                    
                case 'delete_method':
                    $sql = "DELETE FROM buyer_payment_methods WHERE id = ? AND buyer_id = ?";
                    $stmt = $db->prepare($sql);
                    $stmt->execute([$_POST['method_id'], $currentUserId]);
                    
                    $_SESSION['flash_message'] = 'Payment method deleted successfully';
                    $_SESSION['flash_type'] = 'success';
                    break;
                    
                case 'set_default':
                    $sql = "UPDATE buyer_payment_methods SET is_default = 0 WHERE buyer_id = ?";
                    $stmt = $db->prepare($sql);
                    $stmt->execute([$currentUserId]);
                    
                    $sql = "UPDATE buyer_payment_methods SET is_default = 1 
                            WHERE id = ? AND buyer_id = ?";
                    $stmt = $db->prepare($sql);
                    $stmt->execute([$_POST['method_id'], $currentUserId]);
                    
                    $_SESSION['flash_message'] = 'Default payment method updated';
                    $_SESSION['flash_type'] = 'success';
                    break;
            }
        }
        
        $db->commit();
        header('Location: ' . APP_URL . '/buyer/payments.php');
        exit();
        
    } catch (Exception $e) {
        $db->rollBack();
        $_SESSION['flash_message'] = 'Error: ' . $e->getMessage();
        $_SESSION['flash_type'] = 'error';
    }
}

// Get payment methods
$sql = "SELECT * FROM buyer_payment_methods WHERE buyer_id = ? ORDER BY is_default DESC, created_at DESC";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId]);
$paymentMethods = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get payment history
$sql = "SELECT o.id, o.order_number, o.total_amount, o.payment_status, 
               o.payment_method, o.created_at, p.product_name
        FROM orders o
        INNER JOIN products p ON o.product_id = p.id
        WHERE o.buyer_id = ? AND o.payment_status != 'unpaid'
        ORDER BY o.created_at DESC
        LIMIT 20";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId]);
$paymentHistory = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get payment statistics
$sql = "SELECT 
            SUM(CASE WHEN payment_status = 'paid' THEN total_amount ELSE 0 END) as total_paid,
            SUM(CASE WHEN payment_status = 'unpaid' THEN total_amount ELSE 0 END) as total_unpaid,
            SUM(CASE WHEN payment_status = 'partial' THEN total_amount ELSE 0 END) as total_partial,
            COUNT(CASE WHEN payment_status = 'paid' THEN 1 END) as paid_count,
            COUNT(CASE WHEN payment_status = 'unpaid' THEN 1 END) as unpaid_count
        FROM orders WHERE buyer_id = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId]);
$stats = $stmt->fetch(PDO::FETCH_ASSOC);

$pageTitle = 'Payment Management';
$breadcrumbs = [['title' => 'Payments', 'url' => '']];

require_once __DIR__ . '/includes/base.php';
require_once __DIR__ . '/includes/helpers.php';
renderBuyerHeader($pageTitle, $breadcrumbs);
?>

<!-- Payment Statistics -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h6 class="text-muted mb-2">Total Paid</h6>
                <h3 class="mb-0 text-success"><?php echo formatCurrency($stats['total_paid'] ?? 0); ?></h3>
                <small class="text-muted"><?php echo $stats['paid_count']; ?> payments</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h6 class="text-muted mb-2">Pending</h6>
                <h3 class="mb-0 text-warning"><?php echo formatCurrency($stats['total_unpaid'] ?? 0); ?></h3>
                <small class="text-muted"><?php echo $stats['unpaid_count']; ?> pending</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h6 class="text-muted mb-2">Partial</h6>
                <h3 class="mb-0 text-info"><?php echo formatCurrency($stats['total_partial'] ?? 0); ?></h3>
                <small class="text-muted">Partial payments</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h6 class="text-muted mb-2">Payment Methods</h6>
                <h3 class="mb-0 text-primary"><?php echo count($paymentMethods); ?></h3>
                <small class="text-muted">Saved methods</small>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Payment Methods -->
    <div class="col-lg-5">
        <div class="card shadow-sm">
            <div class="card-header bg-white py-3">
                <div class="row align-items-center">
                    <div class="col">
                        <h5 class="mb-0"><i class="bi bi-wallet2 me-2"></i>Payment Methods</h5>
                    </div>
                    <div class="col-auto">
                        <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addMethodModal">
                            <i class="bi bi-plus-circle me-1"></i>Add Method
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <?php if (empty($paymentMethods)): ?>
                    <div class="text-center py-5">
                        <i class="bi bi-wallet" style="font-size: 4rem; color: #d1d5db;"></i>
                        <h6 class="mt-3 text-muted">No payment methods</h6>
                        <p class="text-muted small">Add a payment method to get started</p>
                    </div>
                <?php else: ?>
                    <div class="list-group list-group-flush">
                        <?php foreach ($paymentMethods as $method): ?>
                        <div class="list-group-item">
                            <div class="d-flex justify-content-between align-items-start">
                                <div class="flex-grow-1">
                                    <div class="d-flex align-items-center mb-2">
                                        <i class="bi bi-<?php echo getPaymentIcon($method['payment_type']); ?> me-2 fs-4"></i>
                                        <div>
                                            <h6 class="mb-0"><?php echo ucfirst(str_replace('_', ' ', $method['payment_type'])); ?></h6>
                                            <small class="text-muted"><?php echo htmlspecialchars($method['account_name']); ?></small>
                                        </div>
                                    </div>
                                    <p class="mb-1 small">
                                        <?php if ($method['payment_type'] === 'mobile_money'): ?>
                                            <strong><?php echo htmlspecialchars($method['mobile_network']); ?>:</strong> 
                                            <?php echo htmlspecialchars($method['account_number']); ?>
                                        <?php elseif ($method['payment_type'] === 'bank_transfer'): ?>
                                            <strong><?php echo htmlspecialchars($method['bank_name']); ?>:</strong> 
                                            <?php echo htmlspecialchars($method['account_number']); ?>
                                        <?php else: ?>
                                            <?php echo htmlspecialchars($method['account_number']); ?>
                                        <?php endif; ?>
                                    </p>
                                    <?php if ($method['is_default']): ?>
                                    <span class="badge bg-success">Default</span>
                                    <?php endif; ?>
                                    <?php if ($method['is_verified']): ?>
                                    <span class="badge bg-primary">Verified</span>
                                    <?php endif; ?>
                                </div>
                                <div class="dropdown">
                                    <button class="btn btn-sm btn-outline-secondary" data-bs-toggle="dropdown">
                                        <i class="bi bi-three-dots-vertical"></i>
                                    </button>
                                    <ul class="dropdown-menu dropdown-menu-end">
                                        <?php if (!$method['is_default']): ?>
                                        <li>
                                            <form method="POST" class="dropdown-item-form">
                                                <input type="hidden" name="action" value="set_default">
                                                <input type="hidden" name="method_id" value="<?php echo $method['id']; ?>">
                                                <button type="submit" class="dropdown-item">
                                                    <i class="bi bi-star me-2"></i>Set as Default
                                                </button>
                                            </form>
                                        </li>
                                        <?php endif; ?>
                                        <li>
                                            <a class="dropdown-item" href="#" onclick="editMethod(<?php echo htmlspecialchars(json_encode($method)); ?>)">
                                                <i class="bi bi-pencil me-2"></i>Edit
                                            </a>
                                        </li>
                                        <li><hr class="dropdown-divider"></li>
                                        <li>
                                            <form method="POST" onsubmit="return confirm('Delete this payment method?')">
                                                <input type="hidden" name="action" value="delete_method">
                                                <input type="hidden" name="method_id" value="<?php echo $method['id']; ?>">
                                                <button type="submit" class="dropdown-item text-danger">
                                                    <i class="bi bi-trash me-2"></i>Delete
                                                </button>
                                            </form>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- Payment History -->
    <div class="col-lg-7">
        <div class="card shadow-sm">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0"><i class="bi bi-clock-history me-2"></i>Payment History</h5>
            </div>
            <div class="card-body">
                <?php if (empty($paymentHistory)): ?>
                    <div class="text-center py-5">
                        <i class="bi bi-receipt" style="font-size: 4rem; color: #d1d5db;"></i>
                        <h6 class="mt-3 text-muted">No payment history</h6>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead class="table-light">
                                <tr>
                                    <th>Order #</th>
                                    <th>Product</th>
                                    <th>Amount</th>
                                    <th>Method</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($paymentHistory as $payment): ?>
                                <tr>
                                    <td>
                                        <a href="<?php echo APP_URL; ?>/buyer/order-details.php?id=<?php echo $payment['id']; ?>">
                                            <?php echo htmlspecialchars($payment['order_number']); ?>
                                        </a>
                                    </td>
                                    <td><?php echo htmlspecialchars($payment['product_name']); ?></td>
                                    <td><strong><?php echo formatCurrency($payment['total_amount']); ?></strong></td>
                                    <td>
                                        <small><?php echo ucfirst(str_replace('_', ' ', $payment['payment_method'] ?? 'N/A')); ?></small>
                                    </td>
                                    <td><?php echo getPaymentStatusBadge($payment['payment_status']); ?></td>
                                    <td><small><?php echo date('M j, Y', strtotime($payment['created_at'])); ?></small></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Add Payment Method Modal -->
<div class="modal fade" id="addMethodModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Payment Method</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" id="addMethodForm">
                <input type="hidden" name="action" value="add_method">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Payment Type</label>
                        <select name="payment_type" class="form-select" required onchange="togglePaymentFields(this.value, 'add')">
                            <option value="">Select type...</option>
                            <option value="mobile_money">Mobile Money</option>
                            <option value="bank_transfer">Bank Transfer</option>
                            <option value="cash">Cash</option>
                            <option value="credit">Credit</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Account Name</label>
                        <input type="text" name="account_name" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Account Number</label>
                        <input type="text" name="account_number" class="form-control" required>
                    </div>
                    
                    <div class="mb-3 mobile-money-fields" style="display:none;">
                        <label class="form-label">Mobile Network</label>
                        <select name="mobile_network" class="form-select">
                            <option value="">Select network...</option>
                            <option value="MTN">MTN Mobile Money</option>
                            <option value="Airtel">Airtel Money</option>
                        </select>
                    </div>
                    
                    <div class="mb-3 bank-transfer-fields" style="display:none;">
                        <label class="form-label">Bank Name</label>
                        <input type="text" name="bank_name" class="form-control">
                    </div>
                    
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_default" id="isDefault">
                        <label class="form-check-label" for="isDefault">
                            Set as default payment method
                        </label>
                    </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">Add Method</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Payment Method Modal -->
<div class="modal fade" id="editMethodModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Payment Method</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" id="editMethodForm">
                <input type="hidden" name="action" value="update_method">
                <input type="hidden" name="method_id" id="editMethodId">
                <div class="modal-body">
                    <!-- Same fields as add, populated with data -->
                    <div class="mb-3">
                        <label class="form-label">Payment Type</label>
                        <select name="payment_type" id="editPaymentType" class="form-select" required onchange="togglePaymentFields(this.value, 'edit')">
                            <option value="mobile_money">Mobile Money</option>
                            <option value="bank_transfer">Bank Transfer</option>
                            <option value="cash">Cash</option>
                            <option value="credit">Credit</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Account Name</label>
                        <input type="text" name="account_name" id="editAccountName" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Account Number</label>
                        <input type="text" name="account_number" id="editAccountNumber" class="form-control" required>
                    </div>
                    
                    <div class="mb-3 edit-mobile-money-fields" style="display:none;">
                        <label class="form-label">Mobile Network</label>
                        <select name="mobile_network" id="editMobileNetwork" class="form-select">
                            <option value="MTN">MTN Mobile Money</option>
                            <option value="Airtel">Airtel Money</option>
                        </select>
                    </div>
                    
                    <div class="mb-3 edit-bank-transfer-fields" style="display:none;">
                        <label class="form-label">Bank Name</label>
                        <input type="text" name="bank_name" id="editBankName" class="form-control">
                    </div>
                    
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_default" id="editIsDefault">
                        <label class="form-check-label" for="editIsDefault">
                            Set as default payment method
                        </label>
                    </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">Update Method</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function togglePaymentFields(type, mode) {
    const prefix = mode === 'edit' ? 'edit-' : '';
    document.querySelectorAll(`.${prefix}mobile-money-fields`).forEach(el => el.style.display = 'none');
    document.querySelectorAll(`.${prefix}bank-transfer-fields`).forEach(el => el.style.display = 'none');
    
    if (type === 'mobile_money') {
        document.querySelectorAll(`.${prefix}mobile-money-fields`).forEach(el => el.style.display = 'block');
    } else if (type === 'bank_transfer') {
        document.querySelectorAll(`.${prefix}bank-transfer-fields`).forEach(el => el.style.display = 'block');
    }
}

function editMethod(method) {
    document.getElementById('editMethodId').value = method.id;
    document.getElementById('editPaymentType').value = method.payment_type;
    document.getElementById('editAccountName').value = method.account_name;
    document.getElementById('editAccountNumber').value = method.account_number;
    document.getElementById('editMobileNetwork').value = method.mobile_network || '';
    document.getElementById('editBankName').value = method.bank_name || '';
    document.getElementById('editIsDefault').checked = method.is_default == 1;
    
    togglePaymentFields(method.payment_type, 'edit');
    
    new bootstrap.Modal(document.getElementById('editMethodModal')).show();
}

function getPaymentIcon(type) {
    const icons = {
        'mobile_money': 'phone',
        'bank_transfer': 'bank',
        'cash': 'cash-coin',
        'credit': 'credit-card'
    };
    return icons[type] || 'wallet';
}
</script>

<style>
.dropdown-item-form {
    padding: 0;
    margin: 0;
}
.dropdown-item-form button {
    width: 100%;
    text-align: left;
    border: none;
    background: none;
}
</style>

<?php renderBuyerFooter(); ?>