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

if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}
global $pdo;
$message = '';

// ==================================================
// AUTO-FIX: Create Tables if they don't exist
// ==================================================
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `payment_methods` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `name` varchar(50) NOT NULL,
        `type` varchar(20) NOT NULL,
        `bonus_text` varchar(20) DEFAULT NULL,
        `status` int(1) DEFAULT 1,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    $pdo->exec("CREATE TABLE IF NOT EXISTS `payment_channels` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `method_id` int(11) NOT NULL,
        `channel_name` varchar(50) NOT NULL,
        `min_amount` decimal(10,2) NOT NULL DEFAULT 100.00,
        `max_amount` decimal(10,2) NOT NULL DEFAULT 50000.00,
        `pay_address` varchar(255) NOT NULL,
        `status` int(1) DEFAULT 1,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    // Insert default methods if empty
    if($pdo->query("SELECT COUNT(*) FROM payment_methods")->fetchColumn() == 0) {
        $pdo->exec("INSERT INTO `payment_methods` (`name`, `type`, `bonus_text`) VALUES ('UPI-QR', 'upi', NULL), ('USDT', 'usdt', '+2%')");
    }
} catch (PDOException $e) {}

// ==================================================
// 1. AJAX IMAGE UPLOAD LOGIC (For QR Codes)
// ==================================================
if (isset($_POST['ajax_upload'])) {
    $targetDir = '../assets/png/'; 
    if (!is_dir($targetDir)) { mkdir($targetDir, 0777, true); }

    $channelId = (int)$_POST['channel_id'];
    $filename = "qr_channel_{$channelId}.webp"; // Auto naming QR based on ID
    $file = $_FILES['qr_image'];

    if ($file['error'] === 0) {
        $targetPath = $targetDir . $filename;
        if (move_uploaded_file($file['tmp_name'], $targetPath)) {
            echo json_encode(['success' => true, 'url' => $targetPath . '?v=' . time()]);
        } else {
            echo json_encode(['success' => false, 'msg' => 'Upload failed. Check permissions.']);
        }
    } else {
        echo json_encode(['success' => false, 'msg' => 'Invalid file.']);
    }
    exit; 
}

// ==================================================
// 2. CHANNEL MANAGEMENT (Form Submit)
// ==================================================
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_channel'])) {
    $channel_id = (int)($_POST['channel_id'] ?? 0);
    $method_id = (int)$_POST['method_id'];
    $channel_name = $_POST['channel_name'];
    $min_amount = (float)$_POST['min_amount'];
    $max_amount = (float)$_POST['max_amount'];
    $pay_address = $_POST['pay_address'];

    try {
        if ($channel_id > 0) {
            // Update
            $upd = $pdo->prepare("UPDATE payment_channels SET method_id=?, channel_name=?, min_amount=?, max_amount=?, pay_address=? WHERE id=?");
            $upd->execute([$method_id, $channel_name, $min_amount, $max_amount, $pay_address, $channel_id]);
            $message = "<div class='p-4 mb-4 text-green-700 bg-green-100 rounded-lg'>✅ Channel Updated!</div>";
        } else {
            // Insert
            $ins = $pdo->prepare("INSERT INTO payment_channels (method_id, channel_name, min_amount, max_amount, pay_address) VALUES (?, ?, ?, ?, ?)");
            $ins->execute([$method_id, $channel_name, $min_amount, $max_amount, $pay_address]);
            $message = "<div class='p-4 mb-4 text-green-700 bg-green-100 rounded-lg'>✅ New Channel Added!</div>";
        }
    } catch (Exception $e) {
        $message = "<div class='p-4 mb-4 text-red-700 bg-red-100 rounded-lg'>❌ Error: " . $e->getMessage() . "</div>";
    }
}

if (isset($_GET['delete'])) {
    $del = (int)$_GET['delete'];
    $pdo->prepare("DELETE FROM payment_channels WHERE id = ?")->execute([$del]);
    header("Location: depositmanage.php");
    exit;
}

// Fetch Data
$methods = $pdo->query("SELECT * FROM payment_methods ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
$channels = $pdo->query("SELECT c.*, m.name as method_name, m.type FROM payment_channels c JOIN payment_methods m ON c.method_id = m.id ORDER BY c.id ASC")->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Deposit Channels';
require_once 'includes/header.php';
?>
<style>
.img-upload-box { position: relative; cursor: pointer; display: flex; align-items:center; justify-content:center; border: 2px dashed #ddd; border-radius:12px; overflow:hidden; transition: 0.3s; width: 100px; height: 100px; background:#f8f9fa;}
.img-upload-box:hover { border-color: #009ef7; }
.img-upload-box .overlay { position: absolute; inset:0; background: rgba(0,0,0,0.6); color: #fff; display: flex; align-items: center; justify-content: center; font-size: 11px; font-weight: bold; opacity: 0; transition: 0.3s; }
.img-upload-box:hover .overlay { opacity: 1; }
.uploading::after { content: 'Wait...'; position: absolute; inset: 0; background: rgba(0,158,247,0.9); color: white; display: flex; align-items: center; justify-content: center; font-size: 11px; font-weight: bold;}
</style>
<div class="custom-card">
    <div class="custom-card-header"><i class="fas fa-qrcode me-2"></i> Deposit & QR Manager</div>
    <div class="p-4">
        <p class="text-muted mb-4">Manage UPI IDs, USDT Addresses, limits and QR codes.</p>
        <?= $message ?>

        <div class="bg-light rounded-3 p-4 mb-4 rounded-3" style="background:#f8f9fa;">
            <h6 class="fw-bold mb-3"><i class="fas fa-plus-circle me-2"></i> Add / Edit Channel</h6>
            <form method="POST" class="row g-3 align-items-end">
                <input type="hidden" name="channel_id" id="edit_channel_id" value="0">
                <div class="col-md-2"><label class="form-label small fw-bold">Method</label>
                    <select name="method_id" id="edit_method_id" class="form-select" required>
                        <?php foreach($methods as $m): ?><option value="<?= $m['id'] ?>"><?= $m['name'] ?> (<?= strtoupper($m['type']) ?>)</option><?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2"><label class="form-label small fw-bold">Channel Name</label>
                    <input type="text" name="channel_name" id="edit_channel_name" required class="form-control" placeholder="e.g. PhonePe">
                </div>
                <div class="col-md-2"><label class="form-label small fw-bold">UPI / Address</label>
                    <input type="text" name="pay_address" id="edit_pay_address" required class="form-control">
                </div>
                <div class="col-md-1"><label class="form-label small fw-bold">Min</label>
                    <input type="number" step="0.01" name="min_amount" id="edit_min" value="100" required class="form-control">
                </div>
                <div class="col-md-1"><label class="form-label small fw-bold">Max</label>
                    <input type="number" step="0.01" name="max_amount" id="edit_max" value="50000" required class="form-control">
                </div>
                <div class="col-md-2">
                    <button type="submit" name="save_channel" class="btn btn-primary w-100 fw-bold">Save</button>
                    <button type="button" onclick="resetForm()" class="btn btn-outline-secondary btn-sm w-100 mt-1">Reset</button>
                </div>
            </form>
        </div>

        <div class="row g-4">
            <?php foreach($channels as $c): 
                $qrPath = "../assets/png/qr_channel_{$c['id']}.webp";
            ?>
            <div class="col-md-6 col-lg-4">
                <div class="custom-card p-4 d-flex gap-3 align-items-center">
                    <label class="img-upload-box flex-shrink-0">
                        <img id="qr_img_<?= $c['id'] ?>" src="<?= $qrPath ?>?v=<?= time() ?>" onerror="this.src='https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=Upload+QR'" class="w-full h-full object-contain" style="width:100px;height:100px;">
                        <div class="overlay">Upload QR</div>
                        <input type="file" accept="image/*" hidden onchange="uploadQR(this, <?= $c['id'] ?>)">
                    </label>
                    <div class="flex-grow-1 min-w-0">
                        <span class="badge bg-danger me-1"><?= strtoupper($c['type']) ?></span>
                        <div class="mt-1">
                            <button type="button" onclick="editChannel(<?= htmlspecialchars(json_encode($c), ENT_QUOTES, 'UTF-8') ?>)" class="btn btn-sm btn-outline-primary">Edit</button>
                            <a href="?delete=<?= $c['id'] ?>" onclick="return confirm('Delete this channel?')" class="btn btn-sm btn-outline-danger">Delete</a>
                        </div>
                        <h6 class="fw-bold mt-2 mb-1"><?= htmlspecialchars($c['channel_name']) ?></h6>
                        <p class="small text-muted mb-0 truncate" title="<?= htmlspecialchars($c['pay_address']) ?>"><?= htmlspecialchars($c['pay_address']) ?></p>
                        <p class="small text-success fw-bold mb-0">₹<?= $c['min_amount'] ?> - ₹<?= $c['max_amount'] ?></p>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<script>
        function editChannel(data) {
            document.getElementById('edit_channel_id').value = data.id;
            document.getElementById('edit_method_id').value = data.method_id;
            document.getElementById('edit_channel_name').value = data.channel_name;
            document.getElementById('edit_pay_address').value = data.pay_address;
            document.getElementById('edit_min').value = data.min_amount;
            document.getElementById('edit_max').value = data.max_amount;
            window.scrollTo(0,0);
        }

        function resetForm() {
            document.getElementById('edit_channel_id').value = 0;
            document.getElementById('edit_channel_name').value = '';
            document.getElementById('edit_pay_address').value = '';
        }

        function uploadQR(input, channelId) {
            if (input.files && input.files[0]) {
                let file = input.files[0];
                let label = input.closest('.img-upload-box');
                label.classList.add('uploading');

                let formData = new FormData();
                formData.append('ajax_upload', '1');
                formData.append('channel_id', channelId);
                formData.append('qr_image', file);

                fetch('', { method: 'POST', body: formData })
                .then(res => res.json())
                .then(data => {
                    label.classList.remove('uploading');
                    if (data.success) {
                        document.getElementById('qr_img_' + channelId).src = data.url;
                        alert('QR Code updated successfully!');
                    } else {
                        alert(data.msg);
                    }
                }).catch(err => {
                    label.classList.remove('uploading');
                    alert('Network error!');
                });
            }
        }
</script>
<?php require_once 'includes/footer.php'; ?>