<?php
require_once '../config/db_config.php';
session_start();

// Check if user is logged in and is admin
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: login.php');
    exit;
}

$db = getDbConnection();

// Handle verification
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['proof_id'])) {
    $proof_id = $_POST['proof_id'];
    $status = $_POST['status'];
    $notes = $_POST['notes'] ?? '';
    
    try {
        $stmt = $db->prepare("UPDATE payment_proofs SET status = :status, notes = :notes WHERE proof_id = :proof_id");
        $stmt->bindParam(':status', $status);
        $stmt->bindParam(':notes', $notes);
        $stmt->bindParam(':proof_id', $proof_id);
        
        if ($stmt->execute()) {
            // Ambil order_id dari payment_proofs
            $stmt2 = $db->prepare("SELECT order_id FROM payment_proofs WHERE proof_id = :proof_id");
            $stmt2->bindParam(':proof_id', $proof_id);
            $stmt2->execute();
            $row = $stmt2->fetch(PDO::FETCH_ASSOC);
            if ($row && isset($row['order_id'])) {
                $order_id = $row['order_id'];
                // Update status pada order_items
                $item_status = ($status === 'verified') ? 'verified' : (($status === 'rejected') ? 'rejected' : 'pending');
                $stmt_items = $db->prepare("UPDATE order_items SET status = :item_status WHERE order_id = :order_id");
                $stmt_items->bindParam(':item_status', $item_status);
                $stmt_items->bindParam(':order_id', $order_id);
                $stmt_items->execute();
                // Tambahan: update status orders jika diverifikasi
                if ($status === 'verified') {
                    $stmt_order = $db->prepare("UPDATE orders SET status = 'processing' WHERE order_id = :order_id");
                    $stmt_order->bindParam(':order_id', $order_id);
                    $stmt_order->execute();
                }
                // Tambahan: jika status ditolak, set status order menjadi expired
                if ($status === 'rejected') {
                    $stmt_order = $db->prepare("UPDATE orders SET status = 'expired' WHERE order_id = :order_id");
                    $stmt_order->bindParam(':order_id', $order_id);
                    $stmt_order->execute();
                }
            }
            $success_message = "Status bukti pembayaran & pesanan berhasil diperbarui";
        } else {
            $error_message = "Gagal memperbarui status bukti pembayaran";
        }
    } catch (PDOException $e) {
        $error_message = "Database error: " . $e->getMessage();
    }
}

// Get all payment proofs with order details
try {
    $stmt = $db->query("
        SELECT pp.*, o.order_code, o.name as customer_name, o.email, o.total_amount 
        FROM payment_proofs pp 
        JOIN orders o ON pp.order_id = o.order_id 
        ORDER BY pp.uploaded_at DESC
    ");
    $payment_proofs = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error_message = "Error mengambil data: " . $e->getMessage();
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verifikasi Bukti Pembayaran - Admin</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>
        .proof-image {
            max-width: 300px;
            max-height: 300px;
            object-fit: contain;
        }
        .status-badge {
            font-size: 0.9em;
            padding: 0.5em 1em;
        }
        .status-pending {
            background-color: #ffc107;
            color: #000;
        }
        .status-verified {
            background-color: #28a745;
            color: #fff;
        }
        .status-rejected {
            background-color: #dc3545;
            color: #fff;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-2 p-0">
                <?php include 'admin_sidebar.php'; ?>
            </div>
            <div class="col-lg-10 p-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1>Verifikasi Bukti Pembayaran</h1>
                    <a href="dashboard.php" class="btn btn-outline-primary">Kembali ke Dashboard</a>
                </div>

                <?php if (isset($success_message)): ?>
                    <div class="alert alert-success"><?php echo $success_message; ?></div>
                <?php endif; ?>

                <?php if (isset($error_message)): ?>
                    <div class="alert alert-danger"><?php echo $error_message; ?></div>
                <?php endif; ?>

                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Kode Pesanan</th>
                                <th>Pelanggan</th>
                                <th>Total</th>
                                <th>Bukti Pembayaran</th>
                                <th>Status</th>
                                <th>Tanggal Upload</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($payment_proofs as $proof): ?>
                                <tr>
                                    <td><?php echo $proof['proof_id']; ?></td>
                                    <td><?php echo htmlspecialchars($proof['order_code']); ?></td>
                                    <td>
                                        <?php echo htmlspecialchars($proof['customer_name']); ?><br>
                                        <small class="text-muted"><?php echo htmlspecialchars($proof['email']); ?></small>
                                    </td>
                                    <td>Rp <?php echo number_format($proof['total_amount'], 0, ',', '.'); ?></td>
                                    <td>
                                        <img src="/web-baso/<?php echo htmlspecialchars($proof['file_path']); ?>" 
                                             alt="Bukti Pembayaran" 
                                             class="proof-image img-thumbnail"
                                             onclick="window.open('../<?php echo htmlspecialchars($proof['file_path']); ?>', '_blank')"
                                             style="cursor: pointer;">
                                    </td>
                                    <td>
                                        <span class="badge status-badge 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>
                                    </td>
                                    <td><?php echo date('d/m/Y H:i', strtotime($proof['uploaded_at'])); ?></td>
                                    <td>
                                        <button type="button" 
                                                class="btn btn-sm btn-primary" 
                                                data-bs-toggle="modal" 
                                                data-bs-target="#verifyModal<?php echo $proof['proof_id']; ?>">
                                            Verifikasi
                                        </button>
                                    </td>
                                </tr>

                                <!-- Verification Modal -->
                                <div class="modal fade" id="verifyModal<?php echo $proof['proof_id']; ?>" tabindex="-1">
                                    <div class="modal-dialog">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title">Verifikasi Bukti Pembayaran</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                            </div>
                                            <form method="POST">
                                                <div class="modal-body">
                                                    <input type="hidden" name="proof_id" value="<?php echo $proof['proof_id']; ?>">
                                                    
                                                    <div class="mb-3">
                                                        <label class="form-label">Status</label>
                                                        <select name="status" class="form-select" required>
                                                            <option value="pending" <?php echo $proof['status'] === 'pending' ? 'selected' : ''; ?>>Menunggu Verifikasi</option>
                                                            <option value="verified" <?php echo $proof['status'] === 'verified' ? 'selected' : ''; ?>>Terverifikasi</option>
                                                            <option value="rejected" <?php echo $proof['status'] === 'rejected' ? 'selected' : ''; ?>>Ditolak</option>
                                                        </select>
                                                    </div>
                                                    
                                                    <div class="mb-3">
                                                        <label class="form-label">Catatan</label>
                                                        <textarea name="notes" class="form-control" rows="3"><?php echo htmlspecialchars($proof['notes'] ?? ''); ?></textarea>
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                                                    <button type="submit" class="btn btn-primary">Simpan</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html> 