<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../includes/payments.php';
require_once __DIR__ . '/../includes/notifications.php';
require_customer();

$pdo = require __DIR__ . '/../config/database.php';
$userId = (int)$_SESSION['user']['id'];

// Get payment and application details
$paymentId = isset($_GET['payment_id']) ? (int)$_GET['payment_id'] : 0;
$applicationId = isset($_GET['application_id']) ? (int)$_GET['application_id'] : 0;

if (!$paymentId || !$applicationId) {
    $_SESSION['error'] = 'Invalid payment request';
    header('Location: /customer/dashboard.php');
    exit;
}

// Fetch payment record
$stmt = $pdo->prepare("
    SELECT * FROM payments 
    WHERE id = ? AND user_id = ?
");
$stmt->execute([$paymentId, $userId]);
$payment = $stmt->fetch();

if (!$payment) {
    $_SESSION['error'] = 'Payment not found';
    header('Location: /customer/dashboard.php');
    exit;
}

// Fetch application details
$appStmt = $pdo->prepare("
    SELECT * FROM service_applications 
    WHERE id = ? AND user_id = ?
");
$appStmt->execute([$applicationId, $userId]);
$application = $appStmt->fetch();

if (!$application) {
    $_SESSION['error'] = 'Application not found';
    header('Location: /customer/dashboard.php');
    exit;
}

// Handle payment submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $method = $_POST['payment_method'] ?? 'bank_transfer';
    
    // Update payment method
    $updateStmt = $pdo->prepare("
        UPDATE payments 
        SET payment_method = ?, status = 'pending', updated_at = datetime('now')
        WHERE id = ?
    ");
    $updateStmt->execute([$method, $paymentId]);
    
    // Create notification
    try {
        $notifyStmt = $pdo->prepare("
            INSERT INTO notifications (user_id, type, title, message, is_read, created_at)
            VALUES (?, 'payment', ?, ?, 0, datetime('now'))
        ");
        $notifyStmt->execute([
            $userId,
            'Payment Initiated',
            'Your payment of ₦' . number_format($payment['amount'], 2) . ' has been initiated. Please complete the transfer.'
        ]);
    } catch (Exception $e) {
        // Silently fail notification
    }
    
    $_SESSION['success'] = 'Payment instructions have been sent to your email. Please complete the bank transfer to finalize your application.';
    header('Location: /customer/payments.php');
    exit;
}

// Decode application data
$serviceType = $application['service_type'];
$universalInfo = json_decode($application['universal_info'], true);

// Get service title
$titles = [
    'business_name' => 'Business Name Registration',
    'limited_company' => 'Limited Company Registration',
    'ngo' => 'NGO / Incorporated Trustee',
    'trademark' => 'Trademark Registration',
    'scuml' => 'SCUML Registration',
    'tin' => 'Tax Identification Number (TIN)',
    'post_incorporation' => 'Post-Incorporation Services'
];
$serviceTitle = $titles[$serviceType] ?? 'Service Application';

require_once __DIR__ . '/../includes/header.php';
?>

<style>
.payment-container {
    max-width: 800px;
    margin: 40px auto;
    padding: 0 20px;
}

.payment-header {
    text-align: center;
    margin-bottom: 40px;
}

.payment-header h1 {
    font-size: 28px;
    color: #1f2937;
    margin-bottom: 8px;
}

.payment-header p {
    color: #6b7280;
    font-size: 16px;
}

.payment-card {
    background: white;
    border-radius: 16px;
    padding: 32px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    margin-bottom: 24px;
}

.payment-summary {
    background: linear-gradient(135deg, #f0fdf4, #dcfce7);
    border: 1px solid #86efac;
    border-radius: 12px;
    padding: 24px;
    margin-bottom: 32px;
}

.payment-summary h3 {
    color: #166534;
    font-size: 14px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 16px;
}

.amount-display {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 0;
    border-bottom: 1px dashed #86efac;
}

.amount-display:last-child {
    border-bottom: none;
}

.amount-display .label {
    color: #166534;
    font-size: 14px;
}

.amount-display .value {
    color: #166534;
    font-weight: 600;
}

.total-amount {
    font-size: 24px;
    font-weight: 700;
    color: #059669;
}

.payment-methods {
    margin-bottom: 32px;
}

.payment-methods h3 {
    font-size: 18px;
    color: #1f2937;
    margin-bottom: 16px;
}

.method-option {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 20px;
    border: 2px solid #e5e7eb;
    border-radius: 12px;
    margin-bottom: 12px;
    cursor: pointer;
    transition: all 0.2s ease;
}

.method-option:hover {
    border-color: #10b981;
    background: rgba(16, 185, 129, 0.02);
}

.method-option.selected {
    border-color: #10b981;
    background: rgba(16, 185, 129, 0.05);
}

.method-option input {
    width: 20px;
    height: 20px;
    accent-color: #10b981;
}

.method-icon {
    font-size: 24px;
}

.method-details {
    flex: 1;
}

.method-details strong {
    display: block;
    color: #1f2937;
    margin-bottom: 4px;
}

.method-details span {
    color: #6b7280;
    font-size: 13px;
}

.bank-details {
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    padding: 24px;
    margin-top: 24px;
}

.bank-details h4 {
    color: #1f2937;
    margin-bottom: 16px;
    font-size: 16px;
}

.bank-row {
    display: flex;
    justify-content: space-between;
    padding: 12px 0;
    border-bottom: 1px solid #e2e8f0;
}

.bank-row:last-child {
    border-bottom: none;
}

.bank-row .label {
    color: #64748b;
    font-size: 14px;
}

.bank-row .value {
    color: #1f2937;
    font-weight: 600;
    font-family: monospace;
    font-size: 14px;
}

.btn-primary {
    background: #10b981;
    color: white;
    padding: 16px 32px;
    border: none;
    border-radius: 10px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    width: 100%;
    transition: all 0.2s ease;
}

.btn-primary:hover {
    background: #059669;
    transform: translateY(-1px);
}

.security-notice {
    display: flex;
    align-items: center;
    gap: 12px;
    color: #6b7280;
    font-size: 13px;
    margin-top: 24px;
    padding: 16px;
    background: #f8fafc;
    border-radius: 8px;
}

@media (max-width: 640px) {
    .payment-card {
        padding: 24px;
    }
    
    .amount-display {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }
}
</style>

<div class="payment-container">
    <div class="payment-header">
        <h1>Complete Your Payment</h1>
        <p>Review your order and select a payment method</p>
    </div>
    
    <div class="payment-card">
        <div class="payment-summary">
            <h3>Order Summary</h3>
            <div class="amount-display">
                <span class="label">Service</span>
                <span class="value"><?= htmlspecialchars($serviceTitle) ?></span>
            </div>
            <?php if (!empty($universalInfo['full_name'])): ?>
            <div class="amount-display">
                <span class="label">Client</span>
                <span class="value"><?= htmlspecialchars($universalInfo['full_name']) ?></span>
            </div>
            <?php endif; ?>
            <div class="amount-display">
                <span class="label">Application ID</span>
                <span class="value"><?= htmlspecialchars($application['application_id']) ?></span>
            </div>
            <div class="amount-display">
                <span class="label total-amount">Total Amount</span>
                <span class="value total-amount">₦<?= number_format($payment['amount'], 2) ?></span>
            </div>
        </div>
        
        <form method="POST">
            <div class="payment-methods">
                <h3>Select Payment Method</h3>
                
                <label class="method-option selected">
                    <input type="radio" name="payment_method" value="bank_transfer" checked>
                    <span class="method-icon">🏦</span>
                    <div class="method-details">
                        <strong>Bank Transfer</strong>
                        <span>Transfer directly to our corporate account</span>
                    </div>
                </label>
            </div>
            
            <div class="bank-details">
                <h4>Bank Transfer Details</h4>
                <div class="bank-row">
                    <span class="label">Bank Name</span>
                    <span class="value">Zenith Bank PLC</span>
                </div>
                <div class="bank-row">
                    <span class="label">Account Name</span>
                    <span class="value">Go Legal Services Ltd</span>
                </div>
                <div class="bank-row">
                    <span class="label">Account Number</span>
                    <span class="value">1012345678</span>
                </div>
                <div class="bank-row">
                    <span class="label">Payment Reference</span>
                    <span class="value"><?= htmlspecialchars($application['application_id']) ?></span>
                </div>
            </div>
            
            <button type="submit" class="btn-primary" style="margin-top: 32px;">
                I Have Made the Payment
            </button>
        </form>
        
        <div class="security-notice">
            <span>🔒</span>
            <span>Your payment information is secure. Please include your Application ID as reference when making the transfer.</span>
        </div>
    </div>
</div>

<script>
document.querySelectorAll('.method-option').forEach(option => {
    option.addEventListener('click', function() {
        document.querySelectorAll('.method-option').forEach(o => o.classList.remove('selected'));
        this.classList.add('selected');
        this.querySelector('input').checked = true;
    });
});
</script>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
