<?php 
session_start();
if(isset($_SESSION['SESS_ADMINLOGGEDIN']) == FALSE) {
    header("Location: " . $config_basedir."../admin/adminlogin.php");
}
require_once("header.php");

// ================== DELETE ==================
if (isset($_GET['del']) && is_numeric($_GET['del'])) {
    $delId = (int) $_GET['del']; 
    $stmt = $pdo->prepare("DELETE FROM payment_methods WHERE id = ?");
    $stmt->execute([$delId]);
    if ($stmt->rowCount() > 0) {
        echo "<script>
            alert('Payment method deleted successfully!');
            window.location.href = 'payment_method.php';
        </script>";
    }
}

// ================== ADD ==================
if (isset($_POST['add_method'])) {
    try {
        $name = htmlspecialchars($_POST['name']);
        $wallet_address = htmlspecialchars($_POST['wallet_address']);
        $rate_in_usd = htmlspecialchars($_POST['rate_in_usd']);
        $status = htmlspecialchars($_POST['status']);
        $created_at = date('Y-m-d H:i:s');

        // Upload logo
        $maxsize = 10485760; // 10MB
        $target_dir = "accounts/upload/payment/";
        if (!file_exists("../$target_dir")) { mkdir("../$target_dir", 0777, true); }
        $target_file = $target_dir . basename($_FILES["logo"]["name"]);
        $extension = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        $extensions_arr = ["jpg", "png", "jpeg", "gif"];

        if (in_array($extension, $extensions_arr) && $_FILES['logo']['size'] < $maxsize) {
            $sourcepath = $_FILES["logo"]["tmp_name"];
            $targetpath = "../" . $target_file;
            if (move_uploaded_file($sourcepath, $targetpath)) {
                $logo = $target_file;

                $stmt = $pdo->prepare("INSERT INTO payment_methods (name, logo, wallet_address, rate_in_usd, status, created_at)
                                       VALUES (?, ?, ?, ?, ?, ?)");
                $stmt->execute([$name, $logo, $wallet_address, $rate_in_usd, $status, $created_at]);

                echo "<script>alert('Payment method added successfully!'); window.location.href='payment_method.php';</script>";
            } else {
                throw new Exception("File upload failed.");
            }
        } else {
            throw new Exception("Invalid file or too large. Max 10MB.");
        }
    } catch (Exception $e) {
        echo "<div class='alert alert-danger'>".$e->getMessage()."</div>";
    }
}

// ================== UPDATE ==================
if (isset($_POST['update_method'])) {
    $id = $_POST['id'];
    $name = htmlspecialchars($_POST['name']);
    $wallet_address = htmlspecialchars($_POST['wallet_address']);
    $rate_in_usd = htmlspecialchars($_POST['rate_in_usd']);
    $status = htmlspecialchars($_POST['status']);

    $stmt = $pdo->prepare("UPDATE payment_methods 
                           SET name=?, wallet_address=?, rate_in_usd=?, status=? 
                           WHERE id=?");
    $stmt->execute([$name, $wallet_address, $rate_in_usd, $status, $id]);

    echo "<script>alert('Payment method updated successfully!'); window.location.href='payment_method.php';</script>";
}

// ================== UPDATE LOGO ==================
if (isset($_POST['update_logo'])) {
    try {
        $id = $_POST['id'];

        $maxsize = 10485760; 
        $target_dir = "accounts/upload/payment/";
        if (!file_exists("../$target_dir")) { mkdir("../$target_dir", 0777, true); }
        $target_file = $target_dir . basename($_FILES["logo"]["name"]);
        $extension = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        $extensions_arr = ["jpg", "png", "jpeg", "gif"];

        if (in_array($extension, $extensions_arr) && $_FILES['logo']['size'] < $maxsize) {
            $sourcepath = $_FILES["logo"]["tmp_name"];
            $targetpath = "../" . $target_file;
            if (move_uploaded_file($sourcepath, $targetpath)) {
                $logo = $target_file;

                $stmt = $pdo->prepare("UPDATE payment_methods SET logo=? WHERE id=?");
                $stmt->execute([$logo, $id]);

                echo "<script>alert('Logo updated successfully!'); window.location.href='payment_method.php';</script>";
            } else {
                throw new Exception("File upload failed.");
            }
        } else {
            throw new Exception("Invalid file or too large.");
        }
    } catch (Exception $e) {
        echo "<div class='alert alert-danger'>".$e->getMessage()."</div>";
    }
}

// ================== FETCH ==================
$stmt = $pdo->query("SELECT * FROM payment_methods ORDER BY id ASC");
$methods = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
    /* Labels black */
    label {
        color: #000 !important;
        font-weight: 600;
        margin-top: 8px;
    }

    .message {
        background:#fff;
        padding:15px;
        border-radius:12px;
        margin-bottom:15px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        transition: transform 0.2s, box-shadow 0.2s;
    }
    .message:hover {
        transform: scale(1.02);
        box-shadow: 0 4px 16px rgba(0,0,0,0.1);
    }

    /* Uniform logo box */
    .logo-box {
        width: 64px;
        height: 64px;
        min-width: 64px;
        min-height: 64px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f3f3f3;
        border-radius: 12px;
        overflow: hidden;
    }
    .logo-box img {
        width: 100%;
        height: 100%;
        object-fit: contain; /* Prevent stretching */
    }

    .hidden-text { display:none; }
    .view-more { cursor:pointer; }
</style>

<div class="main-panel">
<div class="content bg-light">
<div class="page-inner">
    <h2 class="mb-4">Payment Methods</h2>

    <?php foreach ($methods as $row): ?>
        <div class="message">
            <span class="visible-text d-flex align-items-center gap-3">
                <div class="logo-box">
                    <img src="../<?= htmlspecialchars($row['logo']); ?>" alt="<?= htmlspecialchars($row['name']); ?>">
                </div>
                <strong><?= htmlspecialchars($row['name']); ?></strong>  
                - <?= htmlspecialchars($row['wallet_address']); ?>
            </span>
            <span class="hidden-text">
                <form method="POST">
                    <input type="hidden" name="id" value="<?= $row['id']; ?>">
                    <label>Name</label>
                    <input type="text" name="name" value="<?= $row['name']; ?>" class="form-control"><br>
                    <label>Wallet Address</label>
                    <input type="text" name="wallet_address" value="<?= $row['wallet_address']; ?>" class="form-control"><br>
                    <label>Rate in USD</label>
                    <input type="text" name="rate_in_usd" value="<?= $row['rate_in_usd']; ?>" class="form-control"><br>
                    <label>Status</label>
                    <select name="status" class="form-control">
                        <option value="1" <?= $row['status']==1?'selected':''; ?>>Active</option>
                        <option value="0" <?= $row['status']==0?'selected':''; ?>>Inactive</option>
                    </select><br>
                    <button type="submit" name="update_method" class="btn btn-success">Update</button>
                    <a href="payment_method.php?del=<?= $row['id']; ?>" class="btn btn-danger">Delete</a>
                </form>

                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="id" value="<?= $row['id']; ?>">
                    <label>Update Logo</label>
                    <input type="file" name="logo" class="form-control"><br>
                    <button type="submit" name="update_logo" class="btn btn-info">Change Logo</button>
                    <div class="logo-box mt-2">
                        <img src="../<?= htmlspecialchars($row['logo']); ?>" alt="<?= htmlspecialchars($row['name']); ?>">
                    </div>
                </form>
            </span>
            <span class="btn btn-primary view-more" onclick="toggleViewMore(this)">View More</span>
        </div>
    <?php endforeach; ?>

    <hr>
    <h3>Add New Payment Method</h3>
    <form method="POST" enctype="multipart/form-data" class="bg-warning p-4 rounded-lg shadow">
        
        <label>Name</label>
        <input type="text" name="name" class="form-control" required><br>
       
        <label>Wallet Address</label>
        <input type="text" name="wallet_address" class="form-control" required><br>
       
        <label>Rate in USD</label>
        <input type="text" name="rate_in_usd" class="form-control" required><br>
      
        <label>Status</label>
        <select name="status" class="form-control" required>
            <option value="1">Active</option>
            <option value="0">Inactive</option>
        </select><br>
       
        <label>Upload Logo</label>
        <input type="file" name="logo" class="form-control" required><br>
        <button type="submit" name="add_method" class="btn btn-success">Add Payment Method</button>
    </form>
</div>
</div>
</div>

<script>
function toggleViewMore(el) {
    let parent = el.closest('.message');
    let hidden = parent.querySelector('.hidden-text');
    let visible = parent.querySelector('.visible-text');
    if (hidden.style.display === "none" || hidden.style.display === "") {
        hidden.style.display = "block";
        visible.style.display = "none";
        el.textContent = "View Less";
    } else {
        hidden.style.display = "none";
        visible.style.display = "block";
        el.textContent = "View More";
    }
}
</script>

<?php require("footer.php"); ?>
