<?php
require_once '../init.php';

$paymentId = $_GET['payment_id'] ?? null;

if (!$paymentId) {
    Helper::redirect('payments.php');
}

$payment = $subscription->getPaymentDetails($paymentId);

if (!$payment || $payment['user_id'] != $_SESSION['user_id']) {
    Helper::redirect('payments.php');
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $payment['status'] === PAYMENT_PENDING) {
    if (empty($_FILES['payment_proof']['name'])) {
        $error = 'Silakan pilih file bukti transfer';
    } else {
        $allowed = ['jpg', 'jpeg', 'png', 'pdf'];
        $ext     = strtolower(pathinfo($_FILES['payment_proof']['name'], PATHINFO_EXTENSION));

        if (!in_array($ext, $allowed)) {
            $error = 'Format file harus JPG, PNG, atau PDF';
        } elseif ($_FILES['payment_proof']['size'] > 2 * 1024 * 1024) {
            $error = 'Ukuran file maksimal 2MB';
        } else {
            $uploadDir = __DIR__ . '/../uploads/payment_proof/';
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

            $filename = 'proof_' . $paymentId . '_' . time() . '.' . $ext;
            if (move_uploaded_file($_FILES['payment_proof']['tmp_name'], $uploadDir . $filename)) {
                $result = $subscription->submitPaymentProof($paymentId, $filename);
                if ($result['success']) {
                    $payment['status'] = PAYMENT_REVIEWING;

                    // Get user data for email notification
                    $user = $auth->getCurrentUser();

                    // Send email notification to admin
                    $subscription->sendPaymentNotification(
                        $paymentId,
                        $user['email'],
                        $user['name'],
                        $payment['invoice_number'],
                        $payment['amount']
                    );

                    $success = 'Bukti transfer berhasil dikirim. Menunggu verifikasi admin.';
                } else {
                    $error = $result['message'];
                }
            } else {
                $error = 'Gagal mengupload file';
            }
        }
    }
}

$pageTitle = 'Detail Pembayaran - KasirMurah.biz.id';
?>
<?php include '../layout/header.php'; ?>
    <?php include '../layout/navbar.php'; ?>
    
    <div class="container mt-4">
        <h1>Detail Pembayaran</h1>
        
        <?php if ($error): ?>
        <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <?php if ($success): ?>
        <div class="alert alert-success"><?php echo $success; ?></div>
        <?php endif; ?>
        
        <div class="row mt-4">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h5>Informasi Invoice</h5>
                    </div>
                    <div class="card-body">
                        <div class="row mb-3">
                            <div class="col-4"><strong>Nomor Invoice</strong></div>
                            <div class="col-8"><?php echo $payment['invoice_number']; ?></div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-4"><strong>Jumlah</strong></div>
                            <div class="col-8" style="font-size: 20px; font-weight: bold; color: #28a745;">
                                <?php echo Helper::formatCurrency($payment['amount']); ?>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-4"><strong>Tanggal Invoice</strong></div>
                            <div class="col-8"><?php echo Helper::formatDate($payment['created_at']); ?></div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-4"><strong>Jatuh Tempo</strong></div>
                            <div class="col-8"><?php echo Helper::formatDate($payment['due_date']); ?></div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-4"><strong>Status</strong></div>
                            <div class="col-8">
                                <?php echo Helper::getStatusBadge($payment['status']); ?>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-4"><strong>Paket</strong></div>
                            <div class="col-8"><?php echo ucfirst($payment['plan_type']); ?></div>
                        </div>
                        
                        <?php if ($payment['status'] === PAYMENT_PAID): ?>
                        <div class="row mb-3">
                            <div class="col-4"><strong>Tanggal Pembayaran</strong></div>
                            <div class="col-8"><?php echo Helper::formatDateTime($payment['paid_date']); ?></div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <?php if ($payment['status'] === PAYMENT_REVIEWING): ?>
                <div class="card mt-3 border-info">
                    <div class="card-body text-center py-4">
                        <i class="fas fa-clock fa-3x text-info mb-3"></i>
                        <h5 class="text-info">Bukti Transfer Sudah Dikirim</h5>
                        <p class="text-muted">Pembayaran Anda sedang diverifikasi oleh admin.<br>
                        Langganan akan aktif setelah verifikasi selesai.</p>
                    </div>
                </div>
                <?php endif; ?>

                <?php if ($payment['status'] === PAYMENT_PENDING): ?>
                <div class="card mt-3">
                    <div class="card-header">
                        <h5>Instruksi Pembayaran</h5>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <strong>Transfer ke rekening berikut:</strong><br>
                            Bank: BCA<br>
                            Nomor Rekening: 1070481550<br>
                            Atas Nama: Annuh Liwan Nahar
                        </div>
                        
                        <div class="alert alert-warning">
                            <strong>Catatan:</strong><br>
                            Silakan cantumkan nomor invoice (<?php echo $payment['invoice_number']; ?>) 
                            sebagai keterangan pembayaran.
                        </div>
                        
                        <h6>Setelah melakukan pembayaran, upload bukti transfer:</h6>
                        <form method="POST" enctype="multipart/form-data">
                            <div class="mb-3">
                                <label class="form-label">Bukti Transfer <span class="text-danger">*</span></label>
                                <input type="file" class="form-control" name="payment_proof"
                                    accept=".jpg,.jpeg,.png,.pdf" required>
                                <div class="form-text">Format: JPG, PNG, atau PDF. Maks 2MB.</div>
                            </div>
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-upload"></i> Kirim Bukti Transfer
                            </button>
                        </form>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h5>Ringkasan</h5>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <td>Paket</td>
                                <td class="text-end text-uppercase"><?php echo $payment['plan_type']; ?></td>
                            </tr>
                            <tr>
                                <td>Harga</td>
                                <td class="text-end"><?php echo Helper::formatCurrency($payment['amount']); ?></td>
                            </tr>
                            <tr class="table-active font-weight-bold">
                                <td><strong>Total</strong></td>
                                <td class="text-end"><strong><?php echo Helper::formatCurrency($payment['amount']); ?></strong></td>
                            </tr>
                        </table>
                        
                        <hr>
                        
                        <div class="alert alert-sm <?php echo $payment['status'] === PAYMENT_PAID ? 'alert-success' : 'alert-warning'; ?>">
                            Status: <?php echo ucfirst($payment['status']); ?>
                        </div>
                        
                        <a href="payments.php" class="btn btn-secondary w-100">Kembali</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <?php include '../layout/footer.php'; ?>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
