<?php
require_once(__DIR__ . '/../config/db_config.php');
require_once '../models/Order.php';

// Start session
session_start();

// Get database connection
$db = getDbConnection();

// Check if database connection is available
if ($db === null) {
    die("Koneksi database gagal. Silakan coba lagi nanti atau hubungi administrator.");
}

// Check if order_id is provided
if (!isset($_GET['order_id'])) {
    echo '<div style="color:red;text-align:center;margin-top:40px;">Order ID tidak ditemukan.</div>';
    exit;
}

$order_id = $_GET['order_id'];
$path_folder =  "uploads/payment_proofs/proof_".$order_id.".jpg";

// Get order details
$order = new Order();
$order_found = $order->getOrderByOrderCode($order_id);
if (!$order_found) {
    echo '<div style="color:red;text-align:center;margin-top:40px;">Order tidak ditemukan.</div>';
    exit;
}
$order_details = $order;

// Redirect jika status order sudah paid
if ($order_details->status === 'paid') {
    header('Location: cek_transaction.php?paid=1');
    exit;
}

if (!$order_details) {
    echo '<div style="color:red;text-align:center;margin-top:40px;">Order tidak valid.</div>';
    exit;
}

// Handle file upload
$upload_message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['payment_proof'])) {
    $file = $_FILES['payment_proof'];
    $allowed_types = ['image/jpeg', 'image/png', 'image/jpg'];
    $max_size = 5 * 1024 * 1024; // 5MB

    if ($file['error'] === 0) {
        if (in_array($file['type'], $allowed_types)) {
            if ($file['size'] <= $max_size) {
                // Create uploads directory if it doesn't exist
                $upload_dir = __DIR__ . '/../uploads/payment_proofs/';
                if (!file_exists($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }

                // Generate unique filename
                $file_extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                $new_filename = 'proof_' . $order_id . '_' . time() . '.' . $file_extension;
                $target_path = $upload_dir . $new_filename;
                $db_path = 'uploads/payment_proofs/' . $new_filename;

                // Cek apakah sudah ada payment proof pending untuk order ini
                $stmt_check = $db->prepare("SELECT COUNT(*) FROM payment_proofs WHERE order_id = :order_id AND status = 'pending'");
                $stmt_check->bindParam(':order_id', $order_details->order_id);
                $stmt_check->execute();
                $pending_count = $stmt_check->fetchColumn();

                if ($pending_count > 0) {
                    $upload_message = '<div class="alert alert-warning">Anda sudah mengupload bukti pembayaran dan sedang menunggu verifikasi.</div>';
                } else if (move_uploaded_file($file['tmp_name'], $target_path)) {
                    // Save to database
                    try {
                        $stmt = $db->prepare("INSERT INTO payment_proofs (order_id, file_path) VALUES (:order_id, :file_path)");
                        $stmt->bindParam(':order_id', $order_details->order_id);
                        $stmt->bindParam(':file_path', $db_path);
                        if ($stmt->execute()) {
                            // Redirect agar tidak double insert saat refresh
                            header('Location: payment_success.php?order_id=' . urlencode($order_id) . '&uploaded=1');
                            exit;
                        } else {
                            $upload_message = '<div class="alert alert-danger">Gagal menyimpan data bukti pembayaran.</div>';
                        }
                    } catch (PDOException $e) {
                        error_log("Payment success database error: " . $e->getMessage());
                        $upload_message = '<div class="alert alert-danger">Terjadi kesalahan sistem. Silakan coba lagi nanti.</div>';
                    }
                } else {
                    $upload_message = '<div class="alert alert-danger">Gagal mengunggah file.</div>';
                }
            } else {
                $upload_message = '<div class="alert alert-danger">Ukuran file terlalu besar. Maksimal 5MB.</div>';
            }
        } else {
            $upload_message = '<div class="alert alert-danger">Tipe file tidak didukung. Gunakan JPG, JPEG, atau PNG.</div>';
        }
    } else {
        $upload_message = '<div class="alert alert-danger">Error saat mengunggah file.</div>';
    }
}

// Setelah upload bukti pembayaran dan/atau pada awal halaman, sinkronkan status order dengan status order_items
if (isset($order_details->order_id)) {
    $stmt_items = $db->prepare("SELECT status FROM order_items WHERE order_id = :order_id");
    $stmt_items->bindParam(':order_id', $order_details->order_id);
    $stmt_items->execute();
    $item_statuses = $stmt_items->fetchAll(PDO::FETCH_COLUMN);
    if ($item_statuses) {
        if (count(array_unique($item_statuses)) === 1) {
            $all_status = $item_statuses[0];
            if ($all_status === 'verified' && $order_details->status !== 'paid') {
                $order->updateStatus('paid');
                $order_details->status = 'paid';
            } elseif ($all_status === 'rejected' && $order_details->status !== 'cancelled') {
                $order->updateStatus('cancelled');
                $order_details->status = 'cancelled';
            } elseif ($all_status === 'pending' && $order_details->status !== 'pending') {
                $order->updateStatus('pending');
                $order_details->status = 'pending';
            }
        } else {
            // Jika campuran, prioritas: pending > rejected > verified
            if (in_array('pending', $item_statuses)) {
                if ($order_details->status !== 'pending') {
                    $order->updateStatus('pending');
                    $order_details->status = 'pending';
                }
            } elseif (in_array('rejected', $item_statuses)) {
                if ($order_details->status !== 'cancelled') {
                    $order->updateStatus('cancelled');
                    $order_details->status = 'cancelled';
                }
            } elseif (in_array('verified', $item_statuses)) {
                if ($order_details->status !== 'paid') {
                    $order->updateStatus('paid');
                    $order_details->status = 'paid';
                }
            }
        }
    }
}

// Check if payment proof exists
$has_proof = false;
$proof_status = '';
try {
    $stmt = $db->prepare("SELECT status FROM payment_proofs WHERE order_id = :order_id ORDER BY uploaded_at DESC LIMIT 1");
    $stmt->bindParam(':order_id', $order_details->order_id);
    $stmt->execute();
    if ($proof = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $has_proof = true;
        $proof_status = $proof['status'];
    }
} catch (PDOException $e) {
    error_log("Payment proof check error: " . $e->getMessage());
    // Handle error silently
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pembayaran Sukses - Akses Konten</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/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>
        .success-icon {
            color: #28a745;
            font-size: 4rem;
            margin-bottom: 1rem;
        }
        .order-details {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
        }
        .access-button {
            background-color: #28a745;
            color: white;
            padding: 15px 30px;
            border-radius: 5px;
            text-decoration: none;
            display: inline-block;
            margin-top: 20px;
            transition: background-color 0.3s;
        }
        .access-button:hover {
            background-color: #218838;
            color: white;
        }
        .upload-section {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
        }
        .proof-status {
            font-weight: bold;
        }
        .proof-status.pending {
            color: #ffc107;
        }
        .proof-status.verified {
            color: #28a745;
        }
        .proof-status.rejected {
            color: #dc3545;
        }
    </style>
</head>
<body>
    <div class="container py-5">
        <div class="row justify-content-center">
            <div class="col-md-8 text-center">
                <i class="fas fa-check-circle success-icon"></i>
                <h1 class="mb-4">Pembayaran Berhasil!</h1>
                <p class="lead">Terima kasih telah melakukan pembelian. Berikut adalah rincian pesanan Anda:</p>
                
                <div class="order-details text-start">
                    <h4>Rincian Pesanan</h4>
                    <p><strong>Nomor Pesanan:</strong> <?php echo htmlspecialchars(
                        $order_details->order_code); ?></p>
                    <p><strong>Nama Pembeli:</strong> <?php echo htmlspecialchars($order_details->name); ?></p>
                    <p><strong>Email:</strong> <?php echo htmlspecialchars($order_details->email); ?></p>
                    <p><strong>Total Pembayaran:</strong> Rp <?php echo number_format($order_details->total_amount, 0, ',', '.'); ?></p>
                    <p><strong>Status:</strong> 
                        <span id="order-status">
                            <?php
                            if ($order_details->status === 'paid') {
                                echo '<span class="badge bg-success">Terverifikasi</span>';
                            } elseif ($order_details->status === 'pending') {
                                echo '<span class="badge bg-warning text-dark">Menunggu Verifikasi</span>';
                            } elseif ($order_details->status === 'cancelled') {
                                echo '<span class="badge bg-danger">Ditolak</span>';
                            } else {
                                echo '<span class="badge bg-secondary">' . htmlspecialchars($order_details->status) . '</span>';
                            }
                            ?>
                        </span>
                    </p>
                </div>

                <?php if ($upload_message): ?>
                    <?php echo $upload_message; ?>
                <?php endif; ?>

                <div class="upload-section">
                    <h4>Upload Bukti Pembayaran</h4>
                    <?php if ($order_details->status === 'paid'): ?>
                        <div class="alert alert-success">Pembayaran sudah diverifikasi. Anda tidak perlu upload bukti pembayaran lagi.</div>
                    <?php else: ?>
                        <?php if ($has_proof): ?>
                            <p>Status Bukti Pembayaran: 
                                <span id="proof-status" class="proof-status <?php echo $proof_status; ?>">
                                    <?php 
                                    switch($proof_status) {
                                        case 'pending':
                                            echo 'Menunggu Verifikasi';
                                            break;
                                        case 'verified':
                                            echo 'Terverifikasi';
                                            break;
                                        case 'rejected':
                                            echo 'Ditolak';
                                            break;
                                    }
                                    ?>
                                </span>
                            </p>
                        <?php else: ?>
                            <form action="" method="POST" enctype="multipart/form-data" class="mt-3">
                                <div class="mb-3">
                                    <label for="payment_proof" class="form-label">Pilih File Bukti Pembayaran (JPG, JPEG, atau PNG, maks. 5MB)</label>
                                    <input type="file" class="form-control" id="payment_proof" name="payment_proof" accept=".jpg,.jpeg,.png" required>
                                </div>
                                <button type="submit" class="btn btn-primary">Upload Bukti Pembayaran</button>
                            </form>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>

                <!-- Konten yang Dibeli -->
                <!-- Hapus tampilan konten yang dibeli, ganti dengan tombol ke cek transaction -->
                <div class="mt-4 text-center">
                    <a href="cek_transaction.php" class="btn btn-outline-primary">Cek Transaction</a>
                </div>

                <div class="mt-4">
                    <a href="dashboard.php" class="btn btn-outline-primary">Kembali ke Halaman Utama</a>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
function updatePaymentStatus() {
    fetch('get_payment_status.php?order_id=<?php echo urlencode($order_id); ?>')
        .then(response => response.json())
        .then(data => {
            let proofHtml = '';
            if (data.status === 'verified') {
                proofHtml = '<span id="proof-status" class="proof-status verified">Terverifikasi</span>';
            } else if (data.status === 'pending') {
                proofHtml = '<span id="proof-status" class="proof-status pending">Menunggu Verifikasi</span>';
            } else if (data.status === 'rejected') {
                proofHtml = '<span id="proof-status" class="proof-status rejected">Ditolak</span>';
            } else {
                proofHtml = '<span id="proof-status" class="proof-status">Belum Upload Bukti</span>';
            }
            if(document.getElementById('proof-status')) {
                document.getElementById('proof-status').outerHTML = proofHtml;
            }
        });
}
// Hapus interval otomatis
// setInterval(updatePaymentStatus, 5000);
</script>
<!-- Hapus produk yang sudah dibeli dari keranjang (localStorage) setelah checkout sukses -->
<script>
document.addEventListener('DOMContentLoaded', function() {
  try {
    const checkoutItems = JSON.parse(sessionStorage.getItem('checkoutItems') || '[]');
    const userId = <?php echo isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 'null'; ?>;
    const cartKey = userId ? `cartItems_user_${userId}` : 'cartItems_guest';
    let cartItems = JSON.parse(localStorage.getItem(cartKey) || '[]');
    // Hapus produk yang sudah dibeli dari cartItems
    checkoutItems.forEach(bought => {
      let qty = bought.quantity;
      cartItems = cartItems.filter(item => {
        if (item.product === bought.product && qty > 0) {
          qty--;
          return false; // hapus item ini
        }
        return true; // biarkan item lain
      });
    });
    // Simpan kembali cartItems yang sudah dikurangi
    localStorage.setItem(cartKey, JSON.stringify(cartItems));
    localStorage.setItem(
      userId ? `cartCount_user_${userId}` : 'cartCount_guest',
      cartItems.length.toString()
    );
  } catch (e) {
    // ignore error
  }
});
</script>
</body>
</html> 