<?php
require_once '../config/database.php';

if(!isset($_SESSION['is_admin_logged_in']) || $_SESSION['is_admin_logged_in'] !== true) {
    header("Location: index.php");
    exit();
}

$success_msg = '';
$error_msg = '';
$table_missing = false;

// ১. অটোমেটিক টেবিল তৈরি করার অপশন
if(isset($_GET['create_table'])) {
    try {
        $db->exec("CREATE TABLE IF NOT EXISTS `hosting_packages` (
            `id` INT AUTO_INCREMENT PRIMARY KEY,
            `category_id` INT NOT NULL,
            `name` VARCHAR(150) NOT NULL,
            `is_popular` TINYINT(1) DEFAULT 0,
            `regular_price` DECIMAL(10,2) NULL,
            `actual_price` DECIMAL(10,2) NOT NULL,
            `renewal_price` DECIMAL(10,2) NOT NULL,
            `whm_package` VARCHAR(100) NOT NULL,
            `color_theme` VARCHAR(50) DEFAULT 'primary',
            `features` TEXT NULL,
            `status` ENUM('active', 'inactive') DEFAULT 'active',
            `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )");
        $success_msg = "Packages table created successfully!";
        header("Location: packages.php");
        exit();
    } catch(PDOException $e) {
        $error_msg = "Table creation failed: " . $e->getMessage();
    }
}

// ২. নতুন প্যাকেজ যুক্ত করার কোড
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_package'])) {
    $category_id   = $_POST['category_id'];
    $name          = $_POST['name'];
    $is_popular    = isset($_POST['is_popular']) ? 1 : 0;
    $regular_price = !empty($_POST['regular_price']) ? $_POST['regular_price'] : null;
    $actual_price  = $_POST['actual_price'];
    $renewal_price = $_POST['renewal_price'];
    $whm_package   = $_POST['whm_package'];
    $color_theme   = $_POST['color_theme'];
    $status        = $_POST['status'];

    // কমা (,) দিয়ে আলাদা করা ফিচারগুলোকে ডাটাবেসের জন্য রেডি করা
    $features = [];
    if(!empty($_POST['features'])) {
        $feat_array = explode(',', $_POST['features']); // কমা দিয়ে ভাগ করা
        foreach($feat_array as $f) {
            $trimmed_f = trim($f); // আশেপাশের স্পেস রিমুভ করা
            if(!empty($trimmed_f)) {
                $features[] = [
                    'icon' => 'fas fa-check-circle', // ডিফল্ট টিকমার্ক আইকন
                    'text' => $trimmed_f
                ];
            }
        }
    }
    $features_json = json_encode($features);

    try {
        $stmt = $db->prepare("INSERT INTO hosting_packages 
            (category_id, name, is_popular, regular_price, actual_price, renewal_price, whm_package, color_theme, features, status) 
            VALUES (:cat_id, :name, :pop, :reg_p, :act_p, :ren_p, :whm, :color, :feat, :status)");
        
        $stmt->execute([
            'cat_id' => $category_id, 'name' => $name, 'pop' => $is_popular,
            'reg_p' => $regular_price, 'act_p' => $actual_price, 'ren_p' => $renewal_price,
            'whm' => $whm_package, 'color' => $color_theme, 'feat' => $features_json, 'status' => $status
        ]);
        $success_msg = "Package added successfully!";
    } catch(PDOException $e) {
        $error_msg = "Failed to add package. Error: " . $e->getMessage();
    }
}

// ৩. ডাটাবেস থেকে ডেটা আনা
$categories = [];
$packages = [];
try {
    // ক্যাটাগরিগুলো ড্রপডাউনের জন্য
    $cat_stmt = $db->query("SELECT id, name FROM hosting_categories WHERE status='active'");
    $categories = $cat_stmt->fetchAll();

    // প্যাকেজগুলো দেখানোর জন্য
    $pkg_stmt = $db->query("SELECT p.*, c.name as category_name FROM hosting_packages p LEFT JOIN hosting_categories c ON p.category_id = c.id ORDER BY p.id DESC");
    $packages = $pkg_stmt->fetchAll();
} catch(PDOException $e) {
    $table_missing = true;
}

require_once '../includes/admin_header.php';
require_once '../includes/admin_sidebar.php';
?>

<style>
    .glass-card {
        background: rgba(255, 255, 255, 0.9);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.5);
        border-radius: 12px;
        box-shadow: 0 8px 30px rgba(0,0,0,0.04);
    }
    
    /* Package Card Styling */
    .package-card {
        transition: all 0.3s;
        border: 1px solid #f0f0f0;
        position: relative;
        overflow: hidden;
    }
    .package-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 15px 30px rgba(0, 0, 0, 0.08) !important;
    }
    .popular-badge {
        position: absolute;
        top: 15px;
        right: -30px;
        background: #ffc107;
        color: #000;
        padding: 5px 30px;
        font-weight: bold;
        font-size: 11px;
        transform: rotate(45deg);
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
</style>

<div id="content">
    
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold" style="color: #2c3e50;"><i class="fas fa-box-open me-2 text-primary"></i>Hosting Packages</h3>
        <button type="button" class="btn btn-primary px-4 fw-semibold" data-bs-toggle="modal" data-bs-target="#addPackageModal">
            <i class="fas fa-plus-circle me-2"></i>Add New Package
        </button>
    </div>

    <?php if($success_msg): ?>
        <div class="alert alert-success shadow-sm"><i class="fas fa-check-circle me-2"></i> <?= $success_msg ?></div>
    <?php endif; ?>
    <?php if($error_msg): ?>
        <div class="alert alert-danger shadow-sm"><i class="fas fa-exclamation-circle me-2"></i> <?= $error_msg ?></div>
    <?php endif; ?>

    <?php if($table_missing): ?>
        <div class="glass-card p-5 text-center mb-4">
            <h4 class="text-danger mb-3"><i class="fas fa-database fa-2x mb-3"></i><br>Database Table Missing!</h4>
            <p class="text-muted">You need to create the `hosting_packages` table to manage packages.</p>
            <a href="?create_table=true" class="btn btn-success px-4 mt-2"><i class="fas fa-tools me-2"></i>Click Here to Auto-Create Table</a>
        </div>
    <?php else: ?>

        <!-- Packages Grid -->
        <div class="row">
            <?php if(empty($packages)): ?>
                <div class="col-12 text-center py-5">
                    <img src="https://cdn-icons-png.flaticon.com/512/1055/1055644.png" width="100" style="opacity: 0.3;" class="mb-3">
                    <h5 class="text-muted">No packages found.</h5>
                    <p class="text-muted small">Create your first hosting package to start selling.</p>
                </div>
            <?php else: ?>
                <?php foreach($packages as $pkg): ?>
                    <div class="col-xl-4 col-md-6 mb-4">
                        <div class="card package-card glass-card h-100 border-top-0" style="border-top: 5px solid var(--bs-<?= $pkg['color_theme'] ?>) !important;">
                            <?php if($pkg['is_popular']): ?>
                                <div class="popular-badge">POPULAR</div>
                            <?php endif; ?>
                            
                            <div class="card-body p-4">
                                <span class="badge bg-light text-dark border mb-2 px-3 py-1"><?= htmlspecialchars($pkg['category_name'] ?: 'Uncategorized') ?></span>
                                <h4 class="fw-bold mb-3"><?= htmlspecialchars($pkg['name']) ?></h4>
                                
                                <div class="price-box mb-3 bg-light p-3 rounded text-center">
                                    <?php if($pkg['regular_price'] > 0): ?>
                                        <small class="text-muted text-decoration-line-through d-block">৳<?= number_format($pkg['regular_price'], 2) ?></small>
                                    <?php endif; ?>
                                    <h2 class="text-<?= $pkg['color_theme'] ?> fw-bold mb-0">৳<?= number_format($pkg['actual_price'], 2) ?> <span style="font-size: 14px;" class="text-muted">/mo</span></h2>
                                    <small class="text-muted">Renewal: ৳<?= number_format($pkg['renewal_price'], 2) ?></small>
                                </div>

                                <div class="mb-3">
                                    <small class="text-muted fw-bold d-block mb-1">WHM Package:</small>
                                    <span class="badge bg-secondary"><i class="fas fa-cogs me-1"></i> <?= htmlspecialchars($pkg['whm_package']) ?></span>
                                </div>

                                <hr>
                                
                                <!-- Features List -->
                                <ul class="list-unstyled mb-4">
                                    <?php 
                                    $feats = json_decode($pkg['features'], true);
                                    if(is_array($feats)): 
                                        $limit = min(count($feats), 4);
                                        for($i=0; $i<$limit; $i++):
                                    ?>
                                        <li class="mb-2 text-muted" style="font-size: 14px;">
                                            <i class="<?= htmlspecialchars($feats[$i]['icon']) ?> text-<?= $pkg['color_theme'] ?> me-2"></i> 
                                            <?= htmlspecialchars($feats[$i]['text']) ?>
                                        </li>
                                    <?php 
                                        endfor; 
                                        if(count($feats) > 4):
                                    ?>
                                        <li class="text-muted" style="font-size: 13px;"><em>+ <?= count($feats)-4 ?> more features...</em></li>
                                    <?php 
                                        endif;
                                    endif; 
                                    ?>
                                </ul>
                                
                            </div>
                            <div class="card-footer bg-transparent border-top p-3 d-flex justify-content-between">
                                <span class="badge bg-<?= $pkg['status'] == 'active' ? 'success' : 'danger' ?> mt-1">
                                    <?= ucfirst($pkg['status']) ?>
                                </span>
                                <div>
                                    <button class="btn btn-sm btn-outline-primary"><i class="fas fa-edit"></i></button>
                                    <button class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

    <?php endif; ?>
</div>

<!-- Add Package Modal -->
<div class="modal fade" id="addPackageModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 15px;">
            <div class="modal-header bg-light border-bottom-0">
                <h5 class="modal-title fw-bold" style="color: var(--primary-blue);"><i class="fas fa-plus-circle me-2"></i>Create Hosting Package</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                
                <?php if(empty($categories)): ?>
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i> Please create a <b>Hosting Category</b> first before adding a package!
                    </div>
                <?php else: ?>
                    <form action="" method="POST">
                        
                        <div class="row">
                            <!-- Category Select -->
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold text-muted">Category</label>
                                <select name="category_id" class="form-select" required>
                                    <option value="" disabled selected>Select Category...</option>
                                    <?php foreach($categories as $cat): ?>
                                        <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <!-- Display Name -->
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold text-muted">Package Name</label>
                                <input type="text" name="name" class="form-control" placeholder="e.g. Starter Pack, Premium VPS" required>
                            </div>
                        </div>

                        <div class="row">
                            <!-- Regular Price -->
                            <div class="col-md-4 mb-3">
                                <label class="form-label fw-semibold text-muted">Regular Price (Fake)</label>
                                <div class="input-group">
                                    <span class="input-group-text">৳</span>
                                    <input type="number" step="0.01" name="regular_price" class="form-control" placeholder="e.g. 500">
                                </div>
                            </div>
                            <!-- Actual Price -->
                            <div class="col-md-4 mb-3">
                                <label class="form-label fw-semibold text-muted">Actual Buying Price *</label>
                                <div class="input-group">
                                    <span class="input-group-text bg-primary text-white border-primary">৳</span>
                                    <input type="number" step="0.01" name="actual_price" class="form-control border-primary" required>
                                </div>
                            </div>
                            <!-- Renewal Price -->
                            <div class="col-md-4 mb-3">
                                <label class="form-label fw-semibold text-muted">Renewal Price *</label>
                                <div class="input-group">
                                    <span class="input-group-text">৳</span>
                                    <input type="number" step="0.01" name="renewal_price" class="form-control" required>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <!-- WHM Package Name -->
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold text-muted">WHM Package Name *</label>
                                <input type="text" name="whm_package" class="form-control border-warning" placeholder="e.g. farha197_starter" required>
                                <small class="text-muted" style="font-size: 12px;">Must match exactly with your WHM Server.</small>
                            </div>
                            <!-- Color Theme Badge -->
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold text-muted">Color Theme (Badge/Border)</label>
                                <select name="color_theme" class="form-select">
                                    <option value="primary" class="text-primary fw-bold">Primary (Blue)</option>
                                    <option value="success" class="text-success fw-bold">Success (Green)</option>
                                    <option value="warning" class="text-warning fw-bold">Warning (Yellow)</option>
                                    <option value="danger" class="text-danger fw-bold">Danger (Red)</option>
                                    <option value="info" class="text-info fw-bold">Info (Light Blue)</option>
                                    <option value="dark" class="text-dark fw-bold">Dark (Black)</option>
                                </select>
                            </div>
                        </div>

                        <!-- Mark as Popular -->
                        <div class="mb-4 form-check form-switch p-0">
                            <label class="form-label fw-semibold text-muted d-block">Mark as Popular</label>
                            <input class="form-check-input ms-0 me-2" type="checkbox" name="is_popular" value="1" style="transform: scale(1.3);">
                            <label class="form-check-label text-muted ms-1 pt-1">Display the "POPULAR" badge on this package</label>
                        </div>

                        <hr>
                        
                        <!-- Simple Comma Separated Features List -->
                        <div class="mb-3">
                            <label class="form-label fw-bold text-dark"><i class="fas fa-list-check me-2"></i>Features List</label>
                            <textarea name="features" class="form-control bg-light" rows="3" placeholder="e.g. 5GB NVMe SSD, Unlimited Bandwidth, Free SSL, 2 MySQL Databases" required></textarea>
                            <small class="text-muted mt-2 d-block">
                                <i class="fas fa-info-circle text-primary"></i> Separate each feature with a comma (,). It will automatically show as beautiful bullet points on your website!
                            </small>
                        </div>

                        <div class="mb-4">
                            <label class="form-label fw-semibold text-muted">Status</label>
                            <select name="status" class="form-select">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>

                        <button type="submit" name="add_package" class="btn btn-primary w-100 py-3 fw-bold" style="border-radius: 10px; font-size: 16px;">
                            <i class="fas fa-save me-2"></i> Save Package
                        </button>
                    </form>
                <?php endif; ?>

            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Modal Fix (যাতে গ্লাসের নিচে না পড়ে)
    const pkgModal = document.getElementById('addPackageModal');
    if(pkgModal) {
        document.body.appendChild(pkgModal);
    }
});
</script>

<?php require_once '../includes/admin_footer.php'; ?>