<?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 `domain_pricing` (
            `id` INT AUTO_INCREMENT PRIMARY KEY,
            `extension` VARCHAR(20) NOT NULL UNIQUE,
            `fake_price` DECIMAL(10,2) NULL,
            `register_price` DECIMAL(10,2) NOT NULL,
            `renew_price` DECIMAL(10,2) NOT NULL,
            `transfer_price` DECIMAL(10,2) NOT NULL,
            `tag` VARCHAR(50) NULL,
            `status` ENUM('active', 'inactive') DEFAULT 'active',
            `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )");
        $success_msg = "Domain Pricing table created successfully!";
        header("Location: domain_pricing.php");
        exit();
    } catch(PDOException $e) {
        $error_msg = "Table creation failed: " . $e->getMessage();
    }
}

// ২. নতুন ডোমেইন এক্সটেনশন যুক্ত করা
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_domain'])) {
    // '.com' এর মতো ইনপুট দিলে ডট (.) রিমুভ করে ক্লিন করা
    $extension      = ltrim(strtolower(trim($_POST['extension'])), '.'); 
    $fake_price     = !empty($_POST['fake_price']) ? $_POST['fake_price'] : null;
    $register_price = $_POST['register_price'];
    $renew_price    = $_POST['renew_price'];
    $transfer_price = $_POST['transfer_price'];
    $tag            = $_POST['tag'];
    $status         = $_POST['status'];

    try {
        $stmt = $db->prepare("INSERT INTO domain_pricing (extension, fake_price, register_price, renew_price, transfer_price, tag, status) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$extension, $fake_price, $register_price, $renew_price, $transfer_price, $tag, $status]);
        $success_msg = "Domain extension (.$extension) added successfully!";
    } catch(PDOException $e) {
        $error_msg = "Failed to add domain! Note: Extensions must be unique.";
    }
}

// ৩. ডাটাবেস থেকে ডোমেইন লিস্ট আনা
$domains = [];
try {
    $stmt = $db->query("SELECT * FROM domain_pricing ORDER BY id DESC");
    $domains = $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);
    }
    
    .domain-badge {
        font-size: 16px;
        font-weight: 800;
        letter-spacing: 1px;
        padding: 5px 15px;
        border-radius: 8px;
        background: rgba(1, 71, 201, 0.1);
        color: var(--primary-blue);
    }

    .tld-tag {
        font-size: 11px;
        font-weight: bold;
        text-transform: uppercase;
        padding: 4px 10px;
        border-radius: 50px;
    }
    .tag-hot { background: #fee2e2; color: #ef4444; }
    .tag-popular { background: #fef3c7; color: #d97706; }
    .tag-sale { background: #dcfce7; color: #10b981; }
    .tag-new { background: #e0e7ff; color: #4f46e5; }
</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-globe me-2 text-primary"></i>Domain Pricing</h3>
        <button type="button" class="btn btn-primary px-4 fw-semibold" data-bs-toggle="modal" data-bs-target="#addDomainModal">
            <i class="fas fa-plus-circle me-2"></i>Add Extension
        </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>Table Missing!</h4>
            <p class="text-muted">You need to create the `domain_pricing` table first.</p>
            <a href="?create_table=true" class="btn btn-success px-4 mt-2"><i class="fas fa-tools me-2"></i>Auto-Create Table</a>
        </div>
    <?php else: ?>

        <div class="glass-card p-4">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Extension (TLD)</th>
                            <th>Tag</th>
                            <th>Register Price</th>
                            <th>Renew Price</th>
                            <th>Transfer Price</th>
                            <th>Status</th>
                            <th class="text-end">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($domains)): ?>
                            <tr>
                                <td colspan="7" class="text-center py-4 text-muted">
                                    <i class="fas fa-globe fa-2x mb-2" style="opacity: 0.3;"></i><br>
                                    No domains found. Add your first domain extension!
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach($domains as $dom): ?>
                                <tr>
                                    <td>
                                        <span class="domain-badge">.<?= htmlspecialchars($dom['extension']) ?></span>
                                    </td>
                                    <td>
                                        <?php if($dom['tag']): ?>
                                            <span class="tld-tag tag-<?= strtolower($dom['tag']) ?>"><i class="fas fa-star me-1"></i><?= htmlspecialchars($dom['tag']) ?></span>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if($dom['fake_price']): ?>
                                            <small class="text-muted text-decoration-line-through d-block" style="font-size: 12px;">৳<?= number_format($dom['fake_price'], 2) ?></small>
                                        <?php endif; ?>
                                        <strong class="text-dark">৳<?= number_format($dom['register_price'], 2) ?></strong>
                                    </td>
                                    <td class="text-muted">৳<?= number_format($dom['renew_price'], 2) ?></td>
                                    <td class="text-muted">৳<?= number_format($dom['transfer_price'], 2) ?></td>
                                    <td>
                                        <span class="badge bg-<?= $dom['status'] == 'active' ? 'success' : 'danger' ?>"><?= ucfirst($dom['status']) ?></span>
                                    </td>
                                    <td class="text-end">
                                        <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>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    <?php endif; ?>
</div>

<!-- Add Domain Modal -->
<div class="modal fade" id="addDomainModal" tabindex="-1">
    <div class="modal-dialog 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>Add Domain TLD</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <form action="" method="POST">
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold text-muted">Extension (TLD) *</label>
                            <div class="input-group">
                                <span class="input-group-text fw-bold text-primary">.</span>
                                <input type="text" name="extension" class="form-control fw-bold" placeholder="com" required>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold text-muted">Marketing Tag</label>
                            <select name="tag" class="form-select">
                                <option value="">None</option>
                                <option value="Hot">🔥 Hot</option>
                                <option value="Popular">⭐ Popular</option>
                                <option value="Sale">🏷️ Sale</option>
                                <option value="New">🚀 New</option>
                            </select>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 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="fake_price" class="form-control" placeholder="e.g. 1500">
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold text-muted">Register 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="register_price" class="form-control border-primary" required>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold text-muted">Renew Price *</label>
                            <div class="input-group">
                                <span class="input-group-text">৳</span>
                                <input type="number" step="0.01" name="renew_price" class="form-control" required>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-semibold text-muted">Transfer Price *</label>
                            <div class="input-group">
                                <span class="input-group-text">৳</span>
                                <input type="number" step="0.01" name="transfer_price" class="form-control" required>
                            </div>
                        </div>
                    </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 (Available for order)</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>

                    <button type="submit" name="add_domain" class="btn btn-primary w-100 py-2 fw-bold">Save Extension</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Modal Fix
    const domModal = document.getElementById('addDomainModal');
    if(domModal) {
        document.body.appendChild(domModal);
    }
});
</script>

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