<?php
require 'auth_check.php';
require '../config/db.php';

// 1. HANDLE STATUS CHANGE & SEND EMAIL
if (isset($_GET['status']) && isset($_GET['id'])) {
    $status = $_GET['status'];
    $id = $_GET['id'];
    
    // Update DB
    $pdo->prepare("UPDATE product_requests SET status = ? WHERE id = ?")->execute([$status, $id]);
    
    // IF MARKED AS "ADDED" -> SEND EMAIL
    if ($status == 'added') {
        // Fetch request details to get email & product name
        $req = $pdo->query("SELECT * FROM product_requests WHERE id = $id")->fetch();
        
        if ($req && !empty($req['user_email'])) {
            $to = $req['user_email'];
            $prod_name = htmlspecialchars($req['product_name']);
            $subject = "Good News! $prod_name is now available - Pro Subscription Offers";
            
            $emailContent = "
            <html>
            <body style='font-family: Arial, sans-serif; color: #333;'>
                <div style='background-color: #2ecc71; padding: 20px; color: white; text-align: center;'>
                    <h2>Request Fulfilled!</h2>
                </div>
                <div style='padding: 20px; border: 1px solid #ddd;'>
                    <p>Hi there,</p>
                    <p>Great news! You recently requested <strong>$prod_name</strong> on Pro Subscription Offers.</p>
                    <div style='background: #f9f9f9; padding: 15px; border-left: 5px solid #2ecc71; margin: 15px 0;'>
                        <strong>It is now in stock and available for purchase!</strong>
                    </div>
                    <p>Click the button below to check it out:</p>
                    <a href='https://prosubscriptionoffers.com/index.php?s=$prod_name' style='display: inline-block; background: #2c3e50; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; font-weight: bold;'>Buy Now</a>
                    <br><br>
                    <p>Thank you for helping us improve our inventory.</p>
                </div>
            </body>
            </html>
            ";

            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
            $headers .= "From: Pro Subscription Offers <support@prosubscriptionoffers.com>" . "\r\n";
            
            @mail($to, $subject, $emailContent, $headers);
        }
    }
    
    header("Location: requests.php?msg=updated");
    exit();
}

// 2. DELETE REQUEST
if (isset($_GET['delete'])) {
    $pdo->prepare("DELETE FROM product_requests WHERE id = ?")->execute([$_GET['delete']]);
    header("Location: requests.php?msg=deleted");
    exit();
}

// 3. FETCH REQUESTS
$requests = $pdo->query("SELECT * FROM product_requests ORDER BY created_at DESC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Product Requests</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>
        .badge { padding: 3px 8px; border-radius: 4px; font-size: 11px; font-weight: bold; text-transform: uppercase; }
        .b-pending { background: #f39c12; color: white; }
        .b-added { background: #27ae60; color: white; }
        .b-rejected { background: #c0392b; color: white; }
        
        .btn-view { text-decoration: none; padding: 4px 8px; border-radius: 4px; color: white; font-size: 11px; display: inline-block; }
    </style>
</head>
<body>

    <div class="sidebar">
        <?php include 'sidebar.php'; ?>
    </div>

    <div class="content">
        <h1>Customer Requests</h1>
        
        <?php if(isset($_GET['msg'])): ?>
            <div style="padding:10px; background:#d4edda; color:#155724; border-radius:5px; margin-bottom:20px;">
                <?php echo ($_GET['msg'] == 'updated') ? "Status updated & Email sent to user!" : "Request deleted."; ?>
            </div>
        <?php endif; ?>

        <table style="background: white; width: 100%;">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Product Name</th>
                    <th>Requested By</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if(count($requests) > 0): ?>
                    <?php foreach($requests as $r): ?>
                    <tr>
                        <td><?php echo date('d M', strtotime($r['created_at'])); ?></td>
                        <td>
                            <strong><?php echo htmlspecialchars($r['product_name']); ?></strong><br>
                            <small style="color:#777;"><?php echo htmlspecialchars($r['description']); ?></small>
                        </td>
                        <td>
                            <?php echo htmlspecialchars($r['user_email']); ?>
                            <?php if($r['user_id'] > 0) echo " <i class='fas fa-user-check' title='Registered User' style='color:blue;'></i>"; ?>
                        </td>
                        <td>
                            <span class="badge b-<?php echo $r['status']; ?>"><?php echo ucfirst($r['status']); ?></span>
                        </td>
                        <td>
                            <?php if($r['status'] == 'pending'): ?>
                                <a href="requests.php?status=added&id=<?php echo $r['id']; ?>" class="btn-view" style="background:green;">Mark Added</a>
                                <a href="requests.php?status=rejected&id=<?php echo $r['id']; ?>" class="btn-view" style="background:gray;">Reject</a>
                            <?php else: ?>
                                <span style="color:#ccc; font-size:12px;">Completed</span>
                            <?php endif; ?>
                            
                            <a href="requests.php?delete=<?php echo $r['id']; ?>" style="color:red; margin-left:5px;" onclick="return confirm('Delete?')"><i class="fas fa-trash"></i></a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr><td colspan="5" style="text-align:center; padding:20px;">No requests yet.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

</body>
</html>