<?php
require 'auth_check.php';
require '../config/db.php';

$msg = "";
$msgClass = "";

// 1. HANDLE APPROVE
if (isset($_GET['approve'])) {
    $req_id = $_GET['approve'];
    
    // Fetch the request details
    $stmt = $pdo->prepare("SELECT * FROM reseller_requests WHERE id = ?");
    $stmt->execute([$req_id]);
    $request = $stmt->fetch();

    if ($request) {
        $email = $request['email'];
        $company = $request['business_name'];

        // Check if user has an account
        $uCheck = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $uCheck->execute([$email]);
        $user = $uCheck->fetch();

        if ($user) {
            // Upgrade existing user
            $pdo->prepare("UPDATE users SET reseller_status = 'approved', company_name = ? WHERE id = ?")
                ->execute([$company, $user['id']]);
            
            // Mark request as approved
            $pdo->prepare("UPDATE reseller_requests SET status = 'approved' WHERE id = ?")->execute([$req_id]);
            
            $msg = "User upgraded to Reseller successfully!";
            $msgClass = "success";
        } else {
            // User doesn't exist yet
            $msg = "Application marked Approved, but user has no account yet. They must register with email: $email";
            $msgClass = "warning";
            $pdo->prepare("UPDATE reseller_requests SET status = 'approved' WHERE id = ?")->execute([$req_id]);
        }
    }
}

// 2. HANDLE REJECT
if (isset($_GET['reject'])) {
    $id = $_GET['reject'];
    $pdo->prepare("UPDATE reseller_requests SET status = 'rejected' WHERE id = ?")->execute([$id]);
    header("Location: resellers.php?msg=rejected"); exit();
}

// 3. FETCH REQUESTS
try {
    $new_requests = $pdo->query("SELECT * FROM reseller_requests WHERE status = 'new' ORDER BY created_at DESC")->fetchAll();
    $history = $pdo->query("SELECT * FROM reseller_requests WHERE status != 'new' ORDER BY created_at DESC LIMIT 50")->fetchAll();
} catch (Exception $e) {
    $new_requests = [];
    $history = [];
    $msg = "Error: Table 'reseller_requests' missing. Please run the SQL command below.";
    $msgClass = "error";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Manage Resellers</title>
    <link rel="stylesheet" href="admin_style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .msg-box { padding: 10px; border-radius: 5px; margin-bottom: 20px; text-align: center; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .warning { background: #fff3cd; color: #856404; border: 1px solid #ffeeba; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        
        .req-card { background: white; border: 1px solid #eee; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); border-left: 5px solid #3498db; }
        .req-header { display: flex; justify-content: space-between; align-items: flex-start; }
        .req-details { margin-top: 15px; font-size: 14px; color: #555; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
        .badge { padding: 3px 8px; border-radius: 4px; font-size: 11px; font-weight: bold; text-transform: uppercase; }
        .b-new { background: #3498db; color: white; }
        .b-approved { background: #27ae60; color: white; }
        .b-rejected { background: #e74c3c; color: white; }
    </style>
</head>
<body>

    <div class="sidebar">
        <h2>Pro Subscription Offers</h2>
        <a href="index.php"><i class="fas fa-home"></i> Dashboard</a>
        <a href="orders.php"><i class="fas fa-shopping-bag"></i> Orders</a>
        <a href="products.php"><i class="fas fa-box"></i> Products</a>
        <a href="categories.php"><i class="fas fa-layer-group"></i> Categories</a>
        <a href="keys.php"><i class="fas fa-key"></i> Keys Pool</a>
        <a href="users.php"><i class="fas fa-users"></i> Users</a>
        <a href="resellers.php" class="active"><i class="fas fa-handshake"></i> Resellers</a>
        <a href="coupons.php"><i class="fas fa-tags"></i> Coupons</a>
        <a href="reviews.php"><i class="fas fa-star"></i> Reviews</a>
        <a href="blog.php"><i class="fas fa-newspaper"></i> Blog</a>
        <a href="marketing.php"><i class="fas fa-bullhorn"></i> Marketing</a>
        <a href="support.php"><i class="fas fa-headset"></i> Support</a>
        <a href="settings.php"><i class="fas fa-cogs"></i> Settings</a>
        <a href="../logout.php" style="margin-top:20px; color:#e74c3c;"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>

    <div class="content">
        <h1>Reseller Applications</h1>
        
        <?php if($msg): ?>
            <div class="msg-box <?php echo $msgClass; ?>"><?php echo $msg; ?></div>
        <?php endif; ?>

        <h3 style="margin-top: 30px; border-bottom: 2px solid #eee; padding-bottom: 10px;">New Requests (<?php echo count($new_requests); ?>)</h3>
        
        <?php if(count($new_requests) > 0): ?>
            <?php foreach($new_requests as $r): ?>
            <div class="req-card">
                <div class="req-header">
                    <div>
                        <h3 style="margin:0;"><?php echo htmlspecialchars($r['full_name']); ?> <span class="badge b-new">New</span></h3>
                        <small style="color:#777;"><?php echo htmlspecialchars($r['email']); ?> • <?php echo htmlspecialchars($r['phone']); ?></small>
                    </div>
                    <div>
                        <a href="resellers.php?approve=<?php echo $r['id']; ?>" class="btn btn-primary" style="background:#27ae60; font-size:13px; padding:5px 10px; text-decoration:none; color:white; border-radius:3px;">Approve</a>
                        <a href="resellers.php?reject=<?php echo $r['id']; ?>" class="btn btn-primary" style="background:#e74c3c; font-size:13px; padding:5px 10px; text-decoration:none; color:white; border-radius:3px;" onclick="return confirm('Reject this application?')">Reject</a>
                    </div>
                </div>
                
                <div class="req-details">
                    <div><strong>Business:</strong> <?php echo htmlspecialchars($r['business_name'] ?: 'N/A'); ?></div>
                    <div><strong>Country:</strong> <?php echo htmlspecialchars($r['country']); ?></div>
                    <div><strong>Expected Sales:</strong> <?php echo htmlspecialchars($r['expected_monthly_sales']); ?></div>
                    <div><strong>Platforms:</strong> <?php echo htmlspecialchars($r['preferred_platforms']); ?></div>
                    <div style="grid-column: span 2;">
                        <strong>Notes:</strong><br>
                        <?php echo nl2br(htmlspecialchars($r['additional_notes'] ?: 'None')); ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        <?php else: ?>
            <p style="color:#777; padding:20px; background:#fff; border-radius:5px;">No new applications.</p>
        <?php endif; ?>

        <h3 style="margin-top: 50px; border-bottom: 2px solid #eee; padding-bottom: 10px;">History</h3>
        <table style="width: 100%; background: white; border-collapse: collapse;">
            <thead>
                <tr style="background:#f9f9f9;">
                    <th style="padding:10px;">Date</th>
                    <th>Name</th>
                    <th>Business</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($history as $h): ?>
                <tr style="border-bottom:1px solid #eee;">
                    <td style="padding:10px;"><?php echo date('d M Y', strtotime($h['created_at'])); ?></td>
                    <td><?php echo htmlspecialchars($h['full_name']); ?><br><small style="color:#777;"><?php echo $h['email']; ?></small></td>
                    <td><?php echo htmlspecialchars($h['business_name']); ?></td>
                    <td>
                        <span class="badge b-<?php echo $h['status']; ?>"><?php echo ucfirst($h['status']); ?></span>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

    </div>
</body>
</html>