<?php
//Developer: CORE TECH WEB DESIGN
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once dirname(__DIR__) . '/include/config.php';

// Auth check
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true || !isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    header('Location: ' . $site_data['web_url'] . '/signin'); exit();
}

// Handle delete
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $pdo->prepare("DELETE FROM marketplace_accounts WHERE id = ? AND status = 'available'")->execute([$_GET['delete']]);
    header('Location: ' . $site_data['web_url'] . '/admin/marketplace?msg=deleted'); exit();
}

// Handle approve
if (isset($_GET['approve']) && is_numeric($_GET['approve'])) {
    $pdo->prepare("UPDATE marketplace_accounts SET approval_status = 'approved' WHERE id = ?")->execute([$_GET['approve']]);
    header('Location: ' . $site_data['web_url'] . '/admin/marketplace?msg=approved'); exit();
}

// Handle rejectn
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'reject') {
    $pdo->prepare("UPDATE marketplace_accounts SET approval_status = 'rejected', rejection_reason = ? WHERE id = ?")->execute([trim($_POST['reason'] ?? ''), intval($_POST['id'])]);
    header('Location: ' . $site_data['web_url'] . '/admin/marketplace?msg=rejected'); exit();
}

// Handle edit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit') {
    $platform = trim($_POST['custom_platform'] ?? '') ?: trim($_POST['platform']);
    $pdo->prepare("UPDATE marketplace_accounts SET platform=?, username=?, followers=?, price=?, login_email=?, login_password=?, extra_info=?, profile_url=? WHERE id=?")
        ->execute([$platform, trim($_POST['username']), intval($_POST['followers']), floatval($_POST['price']), trim($_POST['login_email']), trim($_POST['login_password']), trim($_POST['extra_info'] ?? ''), trim($_POST['profile_url'] ?? ''), intval($_POST['edit_id'])]);
    header('Location: ' . $site_data['web_url'] . '/admin/marketplace?msg=updated'); exit();
}

// Handle add
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
    $platform = trim($_POST['custom_platform'] ?? '') ?: trim($_POST['platform']);
    $stmt = $pdo->prepare("INSERT INTO marketplace_accounts (platform, username, followers, price, login_email, login_password, extra_info, profile_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $platform,
        trim($_POST['username']),
        intval($_POST['followers']),
        floatval($_POST['price']),
        trim($_POST['login_email']),
        trim($_POST['login_password']),
        trim($_POST['extra_info'] ?? ''),
        trim($_POST['profile_url'] ?? '')
    ]);
    header('Location: ' . $site_data['web_url'] . '/admin/marketplace?msg=added'); exit();
}

include('include/header.php');
$page_title = WEB_NAME . " | Marketplace - Social Media Accounts";

// Fetch all accounts (exclude rejected)
$accounts = $pdo->query("SELECT * FROM marketplace_accounts WHERE approval_status != 'rejected' ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
?>
<title><?php echo $page_title; ?></title>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800"><i class="fas fa-store mr-2"></i>Marketplace - Social Media Accounts</h1>

    <?php if (isset($_GET['msg'])): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <?php 
        $msgs = ['added'=>'Account added!','deleted'=>'Account deleted!','approved'=>'Account approved!','rejected'=>'Account rejected!'];
        echo $msgs[$_GET['msg']] ?? 'Done!'; 
        ?>
        <button type="button" class="close" data-dismiss="alert">&times;</button>
    </div>
    <?php endif; ?>

    <!-- Pending Approvals -->
    <?php 
    $pending = $pdo->query("SELECT ma.*, u.username as seller_name, u.email as seller_email FROM marketplace_accounts ma LEFT JOIN users u ON ma.seller_id = u.id WHERE ma.approval_status = 'pending' ORDER BY ma.created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
    if (!empty($pending)): ?>
    <div class="card shadow mb-4 border-left-warning">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-warning"><i class="fas fa-clock mr-1"></i>Pending Approvals (<?php echo count($pending); ?>)</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered" width="100%">
                    <thead class="thead-light">
                        <tr><th>Seller</th><th>Platform</th><th>Username</th><th>Followers</th><th>Price</th><th>Actions</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach ($pending as $pa): ?>
                        <tr>
                            <td><small><?php echo htmlspecialchars($pa['seller_name'] ?? 'Unknown'); ?><br><span class="text-muted"><?php echo htmlspecialchars($pa['seller_email'] ?? ''); ?></span></small></td>
                            <td><span class="badge badge-info"><?php echo htmlspecialchars($pa['platform']); ?></span></td>
                            <td><?php echo htmlspecialchars($pa['username']); ?></td>
                            <td><?php echo number_format($pa['followers']); ?></td>
                            <td>₦<?php echo number_format($pa['price'], 2); ?></td>
                            <td>
                                <a href="<?php echo $site_data['web_url']; ?>/admin/marketplace?approve=<?php echo $pa['id']; ?>" class="btn btn-sm btn-success" onclick="return confirm('Approve this listing?')"><i class="fas fa-check"></i> Approve</a>
                                <button class="btn btn-sm btn-danger" onclick="rejectAccount(<?php echo $pa['id']; ?>)"><i class="fas fa-times"></i> Reject</button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Add Account Form -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-plus-circle mr-1"></i>Add New Account</h6>
        </div>
        <div class="card-body">
            <form method="POST">
                <input type="hidden" name="action" value="add">
                <div class="row">
                    <div class="col-md-3 form-group">
                        <label><strong>Platform</strong></label>
                        <div class="input-group">
                            <select name="platform" id="platformSelect" class="form-control" onchange="if(this.value==='__custom__'){document.getElementById('customPlatform').style.display='block';this.style.display='none';}">
                                <option value="Instagram">Instagram</option>
                                <option value="TikTok">TikTok</option>
                                <option value="Facebook">Facebook</option>
                                <option value="Twitter/X">Twitter/X</option>
                                <option value="YouTube">YouTube</option>
                                <option value="Snapchat">Snapchat</option>
                                <option value="Telegram">Telegram</option>
                                <option value="WhatsApp">WhatsApp</option>
                                <option value="LinkedIn">LinkedIn</option>
                                <option value="Pinterest">Pinterest</option>
                                <option value="Reddit">Reddit</option>
                                <option value="Discord">Discord</option>
                                <option value="Threads">Threads</option>
                                <?php
                                // Show custom platforms already used
                                $custom_platforms = $pdo->query("SELECT DISTINCT platform FROM marketplace_accounts WHERE platform NOT IN ('Instagram','TikTok','Facebook','Twitter/X','YouTube','Snapchat','Telegram','WhatsApp','LinkedIn','Pinterest','Reddit','Discord','Threads') ORDER BY platform")->fetchAll(PDO::FETCH_COLUMN);
                                foreach ($custom_platforms as $cp): ?>
                                <option value="<?php echo htmlspecialchars($cp); ?>"><?php echo htmlspecialchars($cp); ?></option>
                                <?php endforeach; ?>
                                <option value="__custom__">➕ Add Custom Platform...</option>
                            </select>
                            <input type="text" id="customPlatform" name="custom_platform" class="form-control" placeholder="Enter platform name" style="display:none;" onkeyup="document.querySelector('[name=platform]').value=this.value">
                        </div>
                        <small class="form-text text-muted">Select or add a custom platform</small>
                    </div>
                    <div class="col-md-3 form-group">
                        <label><strong>Username/Handle</strong></label>
                        <input type="text" name="username" class="form-control" placeholder="@username" required>
                    </div>
                    <div class="col-md-2 form-group">
                        <label><strong>Followers</strong></label>
                        <input type="number" name="followers" class="form-control" placeholder="0" min="0" required>
                    </div>
                    <div class="col-md-2 form-group">
                        <label><strong>Price (₦)</strong></label>
                        <input type="number" name="price" class="form-control" placeholder="5000" min="0" step="0.01" required>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4 form-group">
                        <label><strong>Login Email/Phone</strong></label>
                        <input type="text" name="login_email" class="form-control" placeholder="Login email or phone" required>
                    </div>
                    <div class="col-md-4 form-group">
                        <label><strong>Login Password</strong></label>
                        <input type="text" name="login_password" class="form-control" placeholder="Password" required>
                    </div>
                    <div class="col-md-4 form-group">
                        <label><strong>Extra Info</strong> <small class="text-muted">(optional)</small></label>
                        <input type="text" name="extra_info" class="form-control" placeholder="e.g. 2FA backup codes, recovery email">
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 form-group">
                        <label><strong>Profile URL</strong> <small class="text-muted">(optional - for preview)</small></label>
                        <input type="url" name="profile_url" class="form-control" placeholder="https://instagram.com/username">
                    </div>
                </div>
                <button type="submit" class="btn btn-primary"><i class="fas fa-plus mr-1"></i>Add Account</button>
            </form>
        </div>
    </div>

    <!-- Accounts Table -->
    <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex justify-content-between align-items-center">
            <h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-list mr-1"></i>All Accounts (<?php echo count($accounts); ?>)</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover" width="100%">
                    <thead class="thead-light">
                        <tr>
                            <th>#</th>
                            <th>Platform</th>
                            <th>Username</th>
                            <th>Followers</th>
                            <th>Price</th>
                            <th>Login Info</th>
                            <th>Status</th>
                            <th>Seller/Buyer</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($accounts as $acc): ?>
                        <tr>
                            <td><?php echo $acc['id']; ?></td>
                            <td><span class="badge badge-info"><?php echo htmlspecialchars($acc['platform']); ?></span></td>
                            <td><?php echo htmlspecialchars($acc['username']); ?></td>
                            <td><?php echo number_format($acc['followers']); ?></td>
                            <td>₦<?php echo number_format($acc['price'], 2); ?></td>
                            <td>
                                <small>
                                    <strong>Email:</strong> <?php echo htmlspecialchars($acc['login_email']); ?><br>
                                    <strong>Pass:</strong> <?php echo htmlspecialchars($acc['login_password']); ?>
                                    <?php if (!empty($acc['extra_info'])): ?><br><strong>Extra:</strong> <?php echo htmlspecialchars($acc['extra_info']); ?><?php endif; ?>
                                </small>
                            </td>
                            <td>
                                <?php if ($acc['status'] === 'sold'): ?>
                                    <span class="badge badge-danger">Sold</span>
                                <?php else: ?>
                                    <span class="badge badge-success">Available</span>
                                <?php endif; ?>
                                <?php if (isset($acc['approval_status']) && $acc['approval_status'] === 'pending'): ?>
                                    <span class="badge badge-warning">Pending</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <small>
                                    <?php if ($acc['seller_id']): ?>Seller: #<?php echo $acc['seller_id']; ?><?php endif; ?>
                                    <?php if ($acc['buyer_id']): ?><br>Buyer: #<?php echo $acc['buyer_id']; ?><?php endif; ?>
                                </small>
                            </td>
                            <td>
                                <?php if ($acc['status'] === 'available'): ?>
                                <button class="btn btn-sm btn-primary mb-1" onclick='editAccount(<?php echo json_encode($acc); ?>)'><i class="fas fa-edit"></i></button>
                                <a href="<?php echo $site_data['web_url']; ?>/admin/marketplace?delete=<?php echo $acc['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete this account?')"><i class="fas fa-trash"></i></a>
                                <?php else: ?>
                                <small class="text-muted">Sold <?php echo $acc['purchased_at'] ? date('M d', strtotime($acc['purchased_at'])) : ''; ?></small>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($accounts)): ?>
                        <tr><td colspan="8" class="text-center text-muted py-4">No accounts added yet</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="edit">
                <input type="hidden" name="edit_id" id="edit_id">
                <div class="modal-header"><h5 class="modal-title">Edit Account</h5><button type="button" class="close" data-dismiss="modal">&times;</button></div>
                <div class="modal-body">
                    <div class="form-group"><label>Platform</label><input type="text" name="platform" id="edit_platform" class="form-control" required></div>
                    <div class="form-group"><label>Username</label><input type="text" name="username" id="edit_username" class="form-control" required></div>
                    <div class="row">
                        <div class="col-md-6 form-group"><label>Followers</label><input type="number" name="followers" id="edit_followers" class="form-control"></div>
                        <div class="col-md-6 form-group"><label>Price (₦)</label><input type="number" name="price" id="edit_price" class="form-control" step="0.01" required></div>
                    </div>
                    <div class="form-group"><label>Login Email/Phone</label><input type="text" name="login_email" id="edit_login_email" class="form-control" required></div>
                    <div class="form-group"><label>Password</label><input type="text" name="login_password" id="edit_login_password" class="form-control" required></div>
                    <div class="form-group"><label>Profile URL</label><input type="url" name="profile_url" id="edit_profile_url" class="form-control"></div>
                    <div class="form-group"><label>Extra Info</label><input type="text" name="extra_info" id="edit_extra_info" class="form-control"></div>
                </div>
                <div class="modal-footer"><button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button><button type="submit" class="btn btn-primary">Save Changes</button></div>
            </form>
        </div>
    </div>
</div>

<?php include('include/footer.php'); ?>

<!-- Reject Modal Script -->
<script>
function editAccount(acc) {
    document.getElementById('edit_id').value = acc.id;
    document.getElementById('edit_platform').value = acc.platform;
    document.getElementById('edit_username').value = acc.username;
    document.getElementById('edit_followers').value = acc.followers;
    document.getElementById('edit_price').value = acc.price;
    document.getElementById('edit_login_email').value = acc.login_email;
    document.getElementById('edit_login_password').value = acc.login_password;
    document.getElementById('edit_profile_url').value = acc.profile_url || '';
    document.getElementById('edit_extra_info').value = acc.extra_info || '';
    $('#editModal').modal('show');
}
function rejectAccount(id) {
    Swal.fire({
        title: 'Reject Listing',
        input: 'text',
        inputLabel: 'Reason for rejection (optional)',
        inputPlaceholder: 'e.g. Invalid credentials, suspicious account',
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        confirmButtonText: 'Reject'
    }).then(function(result) {
        if (result.isConfirmed) {
            var form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = '<input type="hidden" name="action" value="reject"><input type="hidden" name="id" value="' + id + '"><input type="hidden" name="reason" value="' + (result.value || '') + '">';
            document.body.appendChild(form);
            form.submit();
        }
    });
}
</script>
