<?php
require 'auth_check.php';
require '../config/db.php';

$msg = "";
$msgClass = "";

// 1. HANDLE ADD BUNDLE
if (isset($_POST['save_bundle'])) {
    $name = trim($_POST['name']);
    $price = $_POST['price'];
    // Convert array of product IDs to string "1,2,3"
    $items = isset($_POST['products']) ? implode(',', $_POST['products']) : ''; 
    
    if(!empty($name) && !empty($price) && !empty($items)) {
        $stmt = $pdo->prepare("INSERT INTO bundles (name, price, products_included, is_active) VALUES (?, ?, ?, 1)");
        if($stmt->execute([$name, $price, $items])) {
            $msg = "Bundle Created Successfully!";
            $msgClass = "success";
        } else {
            $msg = "Error creating bundle.";
            $msgClass = "error";
        }
    } else {
        $msg = "Please fill all fields and select products.";
        $msgClass = "error";
    }
}

// 2. HANDLE DELETE
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $pdo->prepare("DELETE FROM bundles WHERE id=?")->execute([$id]);
    header("Location: bundles.php?msg=deleted"); exit();
}

// 3. FETCH DATA
$products = $pdo->query("SELECT * FROM products WHERE is_active = 1")->fetchAll();
$bundles = $pdo->query("SELECT * FROM bundles ORDER BY id DESC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Manage Bundles</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>
        /* PAGE SPECIFIC CSS */
        
        /* Alert Box */
        .msg-box { padding: 12px; border-radius: 6px; margin-bottom: 25px; font-size: 14px; font-weight: 500; text-align: center; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }

        /* Grid Layout */
        .page-grid { display: grid; grid-template-columns: 350px 1fr; gap: 30px; }
        
        /* Form Card */
        .form-card { background: white; padding: 25px; border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); height: fit-content; border-top: 4px solid #8e44ad; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; font-weight: bold; margin-bottom: 8px; color: #333; font-size: 13px; }
        .form-control { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; box-sizing: border-box; font-size: 14px; }
        .form-control:focus { border-color: #8e44ad; outline: none; }
        
        /* Multi-Select Area */
        .multi-select { height: 180px; border: 1px solid #ddd; border-radius: 5px; padding: 5px; overflow-y: auto; }
        .multi-select option { padding: 8px; border-bottom: 1px solid #f9f9f9; cursor: pointer; }
        .multi-select option:checked { background: #8e44ad; color: white; }
        
        .btn-create { width: 100%; background: #8e44ad; color: white; border: none; padding: 12px; border-radius: 5px; font-weight: bold; cursor: pointer; margin-top: 10px; transition: 0.2s; }
        .btn-create:hover { background: #732d91; }

        /* Table Card */
        .table-card { background: white; padding: 25px; border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        .table-card h3 { margin-top: 0; color: #2c3e50; border-bottom: 2px solid #eee; padding-bottom: 15px; margin-bottom: 20px; }
        
        table { width: 100%; border-collapse: collapse; }
        th { text-align: left; padding: 12px 15px; background: #f8f9fa; color: #555; border-bottom: 2px solid #eee; font-size: 13px; text-transform: uppercase; }
        td { padding: 12px 15px; border-bottom: 1px solid #eee; color: #444; vertical-align: middle; }
        tr:last-child td { border-bottom: none; }
        
        .price-tag { font-weight: bold; color: #27ae60; background: #e8f5e9; padding: 4px 8px; border-radius: 4px; font-size: 13px; }
        .items-list { font-size: 12px; color: #666; line-height: 1.5; }
        
        .btn-del { color: #e74c3c; background: #ffebee; padding: 6px 12px; border-radius: 4px; text-decoration: none; font-size: 12px; font-weight: bold; transition: 0.2s; }
        .btn-del:hover { background: #e74c3c; color: white; }

        /* Mobile Responsive */
        @media (max-width: 900px) {
            .page-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>

    <div class="sidebar">
        <?php include 'sidebar.php'; ?>
    </div>

    <div class="content">
        <h1 style="margin-bottom: 30px;">Product Bundles</h1>

        <?php if($msg): ?>
            <div class="msg-box <?php echo $msgClass; ?>"><?php echo $msg; ?></div>
        <?php endif; ?>

        <div class="page-grid">
            
            <div class="form-card">
                <h3 style="margin-top:0; color:#8e44ad;"><i class="fas fa-box-open"></i> Create Bundle</h3>
                <form method="POST">
                    
                    <div class="form-group">
                        <label>Bundle Name</label>
                        <input type="text" name="name" placeholder="e.g. Designer Pack" class="form-control" required>
                    </div>

                    <div class="form-group">
                        <label>Total Price (₹)</label>
                        <input type="number" name="price" placeholder="e.g. 999" class="form-control" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Select Products to Include (Hold Ctrl to Select Multiple)</label>
                        <select name="products[]" multiple class="form-control multi-select" required>
                            <?php foreach($products as $p): ?>
                                <option value="<?php echo $p['id']; ?>"><?php echo htmlspecialchars($p['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <small style="color: #777; font-size: 11px; margin-top: 5px; display: block;">* Select at least 2 products</small>
                    </div>

                    <button type="submit" name="save_bundle" class="btn-create">Create Bundle</button>
                </form>
            </div>

            <div class="table-card">
                <h3><i class="fas fa-list"></i> Active Bundles</h3>
                
                <?php if(count($bundles) > 0): ?>
                <table>
                    <thead>
                        <tr>
                            <th>Bundle Name</th>
                            <th>Included Items</th>
                            <th>Price</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($bundles as $b): 
                            // Fetch names of products in this bundle
                            $ids = $b['products_included']; // String "1,5,9"
                            if($ids) {
                                $names = $pdo->query("SELECT name FROM products WHERE id IN ($ids)")->fetchAll(PDO::FETCH_COLUMN);
                                $items_text = implode(" + ", $names);
                            } else {
                                $items_text = "No items";
                            }
                        ?>
                        <tr>
                            <td><strong><?php echo htmlspecialchars($b['name']); ?></strong></td>
                            <td class="items-list">
                                <i class="fas fa-check-circle" style="color:#27ae60;"></i> 
                                <?php echo htmlspecialchars($items_text); ?>
                            </td>
                            <td><span class="price-tag">₹<?php echo number_format($b['price']); ?></span></td>
                            <td>
                                <a href="bundles.php?delete=<?php echo $b['id']; ?>" class="btn-del" onclick="return confirm('Delete this bundle?')">
                                    <i class="fas fa-trash"></i> Delete
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php else: ?>
                    <p style="text-align:center; color:#777; padding:20px;">No bundles created yet.</p>
                <?php endif; ?>
            </div>

        </div>
    </div>

</body>
</html>