<?php
require '../config.php';
session_start();

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

$user_id = $_SESSION['user_id'];

// Get transaction ID from URL parameter
$transaksi_id = isset($_GET['transaksi_id']) ? (int)$_GET['transaksi_id'] : 0;

// Get transaction details
$trx = mysqli_query($conn, "SELECT * FROM transaksi WHERE id = $transaksi_id AND pengguna_id = $user_id AND status = 'menunggu'");
$transaksi = mysqli_fetch_assoc($trx);

if (!$transaksi) {
    header("Location: riwayat.php?error=no_transaction");
    exit;
}

// Data bank untuk ditampilkan
$rekeningInfo = [
    'mandiri' => [
        'nama' => 'Bank Mandiri',
        'no' => '137-00-9876543-1',
        'an' => 'Toko ABC',
        'logo' => '../assets/mandiri.png'
    ],
    'bca' => [
        'nama' => 'Bank BCA',
        'no' => '7391516859',
        'an' => 'Albi Putra Mutdriansyah',
        'logo' => '../assets/bca.png'
    ],
    'bri' => [
        'nama' => 'Bank BRI',
        'no' => '0987654321',
        'an' => 'Toko ABC',
        'logo' => '../assets/bri.png'
    ],
    'gopay' => [
        'nama' => 'GoPay',
        'no' => '081314215856',
        'an' => 'Albi',
        'logo' => '../assets/gopay.png'
    ]
];

$bank = $rekeningInfo[$transaksi['metode_pembayaran']] ?? null;

// Proses upload bukti pembayaran
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['bukti_pembayaran']) && $_FILES['bukti_pembayaran']['error'] === UPLOAD_ERR_OK) {
        $allowed_types = ['image/jpeg', 'image/jpg', 'image/png'];
        $file_type = $_FILES['bukti_pembayaran']['type'];

        if (in_array($file_type, $allowed_types)) {
            $file_extension = pathinfo($_FILES['bukti_pembayaran']['name'], PATHINFO_EXTENSION);
            $new_filename = uniqid() . '_' . basename($_FILES['bukti_pembayaran']['name']);
            $upload_path = '../upload/' . $new_filename;

            if (move_uploaded_file($_FILES['bukti_pembayaran']['tmp_name'], $upload_path)) {
                // Update transaksi dengan bukti pembayaran
                $query = "UPDATE transaksi SET bukti_pembayaran = ?, status = 'dibayar' WHERE id = ?";
                $stmt = $conn->prepare($query);
                $stmt->bind_param("si", $new_filename, $transaksi['id']);

                if ($stmt->execute()) {
                    // Set session untuk menampilkan info rekening di riwayat
                    $_SESSION['payment_success'] = [
                        'bank_info' => $bank,
                        'transaction_id' => $transaksi['id'],
                        'total' => $transaksi['total_harga']
                    ];

                    header("Location: riwayat.php?payment_success=1");
                    exit;
                } else {
                    $error = "Gagal menyimpan bukti pembayaran. Silakan coba lagi.";
                }
            } else {
                $error = "Gagal mengupload file. Silakan coba lagi.";
            }
        } else {
            $error = "Format file tidak didukung. Gunakan JPG, JPEG, atau PNG.";
        }
    } else {
        $error = "Silakan pilih file bukti pembayaran.";
    }
}

// Get transaction details/items (after potential redirect)
$detail_query = "
    SELECT td.*, p.nama, p.gambar, up.ukuran 
    FROM transaksi_detail td
    JOIN produk p ON td.produk_id = p.id
    JOIN ukuran_produk up ON td.ukuran_id = up.id
    WHERE td.transaksi_id = $transaksi_id
";
$detail_result = mysqli_query($conn, $detail_query);
$detail_items = [];
while ($item = mysqli_fetch_assoc($detail_result)) {
    $detail_items[] = $item;
}

function formatKodeTransaksi($id, $tanggal)
{
    return 'TRX-' . date('Ymd', strtotime($tanggal)) . '-' . str_pad($id, 4, '0', STR_PAD_LEFT);
}

// Include navbar after all processing is complete
require '../pelanggan/navbar.php';
?>

<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Bukti Pembayaran - Day Apparel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f8f9fa;
        }

        .upload-container {
            background: rgba(255, 255, 255, 0.98);
            backdrop-filter: blur(20px);
            border-radius: 25px;
            box-shadow:
                0 25px 50px rgba(0, 0, 0, 0.1),
                inset 0 1px 0 rgba(255, 255, 255, 0.9);
            padding: 2.5rem;
            margin: 2rem auto;
            max-width: 1000px;
            border: 2px solid rgba(0, 0, 0, 0.05);
        }

        .page-title {
            background: linear-gradient(135deg, #000000 0%, #434343 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            font-size: 2.5rem;
            font-weight: 700;
            text-align: center;
            margin-bottom: 2rem;
            position: relative;
        }

        .page-title::after {
            content: '';
            position: absolute;
            bottom: -10px;
            left: 50%;
            transform: translateX(-50%);
            width: 80px;
            height: 3px;
            background: linear-gradient(135deg, #000000 0%, #666666 100%);
            border-radius: 2px;
        }

        .card {
            border: 2px solid #e0e0e0;
            border-radius: 20px;
            box-shadow:
                0 15px 35px rgba(0, 0, 0, 0.05),
                inset 0 1px 0 rgba(255, 255, 255, 0.8);
            background:
                linear-gradient(135deg, rgba(255, 255, 255, 0.98) 0%, rgba(250, 250, 250, 0.98) 100%);
            backdrop-filter: blur(15px);
            transition: all 0.3s ease;
            overflow: hidden;
        }

        .card:hover {
            transform: translateY(-2px);
            box-shadow:
                0 20px 40px rgba(0, 0, 0, 0.08),
                inset 0 1px 0 rgba(255, 255, 255, 0.9);
            border-color: #000000;
        }

        .card-header {
            background: linear-gradient(135deg, #000000 0%, #333333 100%);
            color: white;
            border: none;
            padding: 1.5rem;
            position: relative;
            overflow: hidden;
            border-bottom: 2px solid #000000;
        }

        .card-header h5 {
            margin: 0;
            font-weight: 600;
            position: relative;
            z-index: 1;
        }

        .table {
            background: transparent;
            border-radius: 15px;
            overflow: hidden;
        }

        .table thead th {
            background: linear-gradient(135deg, #000000 0%, #333333 100%);
            border: none;
            color: #ffffff;
            font-weight: 700;
            padding: 1rem 0.75rem;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .table tbody td {
            border: none;
            padding: 1rem 0.75rem;
            vertical-align: middle;
            background: rgba(255, 255, 255, 0.95);
            color: #000000;
            font-weight: 500;
        }

        .table tbody tr {
            border-bottom: 1px solid rgba(0, 0, 0, 0.08);
        }

        .table tbody tr:hover {
            background: rgba(0, 0, 0, 0.02);
        }

        .table tfoot th {
            background: linear-gradient(135deg, #000000 0%, #333333 100%);
            color: white;
            border: none;
            padding: 1rem 0.75rem;
            font-weight: 700;
        }

        .form-control {
            border: 2px solid #e0e0e0;
            border-radius: 12px;
            padding: 0.75rem 1rem;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.98);
            color: #000000;
        }

        .form-control:focus {
            border-color: #000000;
            box-shadow: 0 0 0 0.2rem rgba(0, 0, 0, 0.1);
            background: white;
        }

        .form-label {
            font-weight: 700;
            color: #000000;
            margin-bottom: 0.5rem;
            text-transform: uppercase;
            font-size: 0.85rem;
            letter-spacing: 0.5px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #000000 0%, #434343 100%);
            border: none;
            border-radius: 12px;
            padding: 1rem 2rem;
            font-weight: 700;
            font-size: 1.1rem;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
            background: linear-gradient(135deg, #2c2c2c 0%, #000000 100%);
        }

        .btn-light {
            background: white !important;
            color: #000000 !important;
            border: 2px solid #000000 !important;
            font-weight: 700 !important;
            text-transform: uppercase !important;
            letter-spacing: 0.5px !important;
            border-radius: 12px !important;
            padding: 0.75rem 1.5rem !important;
        }

        .btn-light:hover {
            background: #000000 !important;
            color: white !important;
        }

        .badge {
            background: #000000 !important;
            color: white !important;
            border-radius: 8px;
            padding: 0.5rem 1rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            width: 90%;
            text-align: center;
        }

        .bg-secondary {
            background: #333333 !important;
            color: white !important;
        }

        .bg-info {
            background: #000000 !important;
        }

        .bank-info {
            background: linear-gradient(135deg, #f0f0f0 0%, #e0e0e0 100%);
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            border-left: 4px solid #000000;
            border: 2px solid #e0e0e0;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
        }

        .alert-danger {
            background: linear-gradient(135deg, #f8d7da 0%, #f5c6cb 100%);
            border: 2px solid #dc3545;
            border-radius: 15px;
            color: #721c24;
        }

        .text-success {
            color: #000000 !important;
            font-weight: 700;
        }

        .text-primary {
            color: #000000 !important;
            font-weight: 700;
        }

        @media (max-width: 768px) {
            .upload-container {
                margin: 0.5rem;
                padding: 0.7rem;
            }

            .page-title {
                font-size: 2rem;
            }
        }

        .fade-in {
            animation: fadeIn 0.6s ease-in;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>

<body>
    <div class="container-fluid m-0">
        <div class="upload-container fade-in">
            <h1 class="page-title">
                <i class="fas fa-upload me-3"></i>Upload Bukti Pembayaran
            </h1>

            <?php if (isset($error)): ?>
                <div class="alert alert-danger" role="alert">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>

            <div class="row g-4">
                <!-- Detail Transaksi -->
                <div class="col-lg-8">
                    <div class="card">
                        <div class="card-header">
                            <h5><i class="fas fa-receipt me-2"></i>Detail Transaksi #<?= formatKodeTransaksi($transaksi['id'], $transaksi['dibuat_pada']) ?></h5>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table align-middle mb-0">
                                    <tbody>
                                        <?php foreach ($detail_items as $item): ?>
                                            <tr>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <i class="fas fa-tshirt text-primary me-2"></i>
                                                        <strong><?= htmlspecialchars($item['nama']) ?></strong>
                                                    </div>
                                                </td>
                                                <td>
                                                    <span class="badge bg-secondary mb-2"><?= htmlspecialchars($item['ukuran']) ?></span>
                                                    <span class="badge bg-info"><?= $item['jumlah'] ?></span>
                                                 </td>
                                                <td><span class="text-success fw-bold">Rp<?= number_format($item['subtotal']) ?></span></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <th colspan="2" class="text-end"><i class="fas fa-truck me-2"></i>Ongkos Kirim</th>
                                            <th><i class="fas fa-coins me-2"></i>Rp<?= number_format($transaksi['ongkos_kirim']) ?></th>
                                        </tr>
                                        <tr>
                                            <th colspan="2" class="text-end"><i class="fas fa-money-check-alt me-2"></i>Total Pembayaran</th>
                                            <th><i class="fas fa-money-check-alt me-2"></i>Rp<?= number_format($transaksi['total_harga']) ?></th>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Form Upload & Info Bank -->
                <div class="col-lg-4">
                    <!-- Info Bank -->
                    <?php if ($bank): ?>
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5><i class="fas fa-credit-card me-2"></i>Informasi Pembayaran</h5>
                            </div>
                            <div class="card-body">
                                <div class="bank-info">
                                    <div class="d-flex align-items-center mb-3">
                                        <img src="<?= $bank['logo'] ?>" alt="<?= $bank['nama'] ?>" style="width: 60px; height: 40px; object-fit: contain;" class="me-3">
                                        <div>
                                            <h6 class="mb-0 fw-bold"><?= $bank['nama'] ?></h6>
                                            <small class="text-muted">Metode Pembayaran</small>
                                        </div>
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Nomor Rekening</label>
                                        <div class="input-group">
                                            <input type="text" class="form-control" value="<?= $bank['no'] ?>" readonly>
                                            <button class="btn btn-light" type="button" onclick="copyToClipboard('<?= $bank['no'] ?>')">
                                                <i class="fas fa-copy"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Atas Nama</label>
                                        <input type="text" class="form-control" value="<?= $bank['an'] ?>" readonly>
                                    </div>
                                    <div class="mb-0">
                                        <label class="form-label">Total Transfer</label>
                                        <input type="text" class="form-control fw-bold" value="Rp<?= number_format($transaksi['total_harga']) ?>" readonly>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>

                    <!-- Form Upload -->
                    <div class="card">
                        <div class="card-header">
                            <h5><i class="fas fa-upload me-2"></i>Upload Bukti Transfer</h5>
                        </div>
                        <div class="card-body">
                            <form method="POST" enctype="multipart/form-data">
                                <div class="mb-3">
                                    <label for="bukti_pembayaran" class="form-label">
                                        <i class="fas fa-camera me-1"></i>Pilih File Bukti
                                    </label>
                                    <input type="file" class="form-control" id="bukti_pembayaran" name="bukti_pembayaran" accept="image/*" required>
                                    <div class="form-text">
                                        <small class="text-muted">
                                            <i class="fas fa-info-circle me-1"></i>
                                            Format: JPG, PNG, JPEG (Maks. 5MB)
                                        </small>
                                    </div>
                                </div>

                                <div class="d-grid gap-2">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-upload me-2"></i>Upload Bukti
                                    </button>
                                    <a href="riwayat.php" class="btn btn-light">
                                        <i class="fas fa-arrow-left me-2"></i>Kembali
                                    </a>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function copyToClipboard(text) {
            navigator.clipboard.writeText(text).then(function() {
                alert('Nomor rekening berhasil disalin!');
            }).catch(function(err) {
                console.error('Could not copy text: ', err);
            });
        }
    </script>
</body>

</html>