<?php
// Session Start
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once 'config/database.php';

// লগইন চেক
if (!isset($_SESSION['is_user_logged_in']) || $_SESSION['is_user_logged_in'] !== true) {
    $_SESSION['redirect_url'] = "my-domains.php";
    header("Location: login.php");
    exit();
}

$page_title = "My Domains";
$user_id = $_SESSION['user_id'];

// =========================================================
// 🚀 DYNAMIC API CONFIGURATION
// =========================================================
$system_settings = [];
try {
    $stmt = $db->query("SELECT * FROM system_settings WHERE id = 1");
    $system_settings = $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {}

$api_key = $system_settings['domain_api_key'] ?? '';
$api_email = $system_settings['domain_api_email'] ?? '';
$api_endpoint = rtrim($system_settings['domain_api_url'] ?? '', '/');

function checkDomainLiveStatusAPI($domain_name) {
    global $api_key, $api_email, $api_endpoint;
    
    $token = base64_encode(hash_hmac("sha256", $api_key, $api_email . ":" . gmdate("y-m-d H")));
    $headers = [
        "username: " . $api_email,
        "token: " . $token
    ];

    $curl = curl_init();
    $url = $api_endpoint . "/domains/" . urlencode(trim($domain_name)) . "/information";

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

    $response = curl_exec($curl);
    curl_close($curl);

    $decoded = json_decode($response, true);
    
    if (!$decoded) {
        return 'pending'; // API ফেইল করলে ডিফল্ট পেন্ডিং
    }

    $status = null;
    if (isset($decoded['status'])) $status = $decoded['status'];
    elseif (isset($decoded['domain']['status'])) $status = $decoded['domain']['status'];
    elseif (isset($decoded['data']['status'])) $status = $decoded['data']['status'];

    // স্মার্ট লজিক: যদি স্ট্যাটাস না থাকে, কিন্তু ডোমেইন ইনফো ও নেমসার্ভার থাকে, তারমানে ডোমেইন অ্যাক্টিভ!
    if (!$status && isset($decoded['domain']) && isset($decoded['nameservers'])) {
        $status = 'active';
    }

    if ($status) {
        return strtolower($status);
    }

    return 'pending';
}

// =========================================================
// 🚀 FETCH DOMAINS & AUTO-SYNC IN BACKGROUND
// =========================================================
$my_domains = [];
try {
    $stmt = $db->prepare("SELECT * FROM orders WHERE user_id = ? AND item_type = 'domain' ORDER BY order_date DESC");
    $stmt->execute([$user_id]);
    $my_domains = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // অটো-সিঙ্ক লজিক (পেজ লোড হওয়ার সাথে সাথে চেক করবে)
    foreach ($my_domains as $key => $domain) {
        if ($domain['status'] === 'pending') {
            $live_status = checkDomainLiveStatusAPI($domain['item_name']);
            
            // যদি API তে অ্যাক্টিভ হয়ে যায়, ডাটাবেস আপডেট করে নেবে
            if ($live_status === 'active') {
                $update = $db->prepare("UPDATE orders SET status = 'active' WHERE id = ?");
                $update->execute([$domain['id']]);
                
                // রিয়েল-টাইম ইউজারকে অ্যাক্টিভ দেখানোর জন্য অ্যারে আপডেট
                $my_domains[$key]['status'] = 'active';
            }
        }
    }
} catch(PDOException $e) {}

// স্ট্যাটাস অনুযায়ী ব্যাজের কালার দেওয়ার ফাংশন
function getStatusBadge($status) {
    if($status == 'active') return '<span class="badge bg-success bg-opacity-10 text-success fw-bold px-3 py-2 rounded-pill"><i class="fa-solid fa-circle-check me-1"></i> Active</span>';
    if($status == 'pending') return '<span class="badge bg-warning bg-opacity-10 text-warning fw-bold px-3 py-2 rounded-pill"><i class="fa-solid fa-clock-rotate-left me-1"></i> Processing</span>';
    if($status == 'cancelled') return '<span class="badge bg-danger bg-opacity-10 text-danger fw-bold px-3 py-2 rounded-pill"><i class="fa-solid fa-circle-xmark me-1"></i> Cancelled</span>';
    return '<span class="badge bg-secondary">Unknown</span>';
}

require_once 'includes/user_header.php';
require_once 'includes/user_sidebar.php';
?>

<style>
    body {
        background-color: #ffffff !important;
        background-image: 
            linear-gradient(rgba(37, 99, 235, 0.03) 1px, transparent 1px),
            linear-gradient(90deg, rgba(37, 99, 235, 0.03) 1px, transparent 1px) !important;
        background-size: 30px 30px !important;
        color: #1e293b !important;
    }

    .page-header { background: #ffffff; border-bottom: 1px solid rgba(15, 23, 42, 0.05); padding: 30px 25px; margin-bottom: 30px; }
    .content-box { background: #ffffff; border-radius: 20px; border: 1px solid rgba(15, 23, 42, 0.05); box-shadow: 0 10px 40px rgba(0, 0, 0, 0.03); padding: 25px; }

    .premium-table { width: 100%; border-collapse: separate; border-spacing: 0 10px; margin-top: -10px; }
    .premium-table thead th { color: #64748b; font-weight: 700; text-transform: uppercase; font-size: 12px; letter-spacing: 1px; padding: 0 20px 10px; border: none; }
    .premium-table tbody tr { background: #ffffff; box-shadow: 0 2px 10px rgba(0,0,0,0.02); border-radius: 12px; transition: all 0.3s; }
    .premium-table tbody tr:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(37, 99, 235, 0.08); }
    
    .premium-table tbody td { padding: 20px; vertical-align: middle; border: none; border-top: 1px solid rgba(15,23,42,0.03); border-bottom: 1px solid rgba(15,23,42,0.03); }
    .premium-table tbody td:first-child { border-left: 1px solid rgba(15,23,42,0.03); border-top-left-radius: 12px; border-bottom-left-radius: 12px; }
    .premium-table tbody td:last-child { border-right: 1px solid rgba(15,23,42,0.03); border-top-right-radius: 12px; border-bottom-right-radius: 12px; }

    .domain-name { font-size: 16px; font-weight: 800; color: #1e293b; display: block; margin-bottom: 4px; }
    .domain-id { font-size: 12px; color: #94a3b8; font-weight: 600; }
    .date-text { font-size: 14px; font-weight: 600; color: #334155; display: block; }
    .date-label { font-size: 11px; color: #94a3b8; text-transform: uppercase; font-weight: 700; }

    .btn-manage { background: #f8fafc; color: #2563eb; border: 1px solid rgba(37, 99, 235, 0.2); padding: 8px 20px; border-radius: 50px; font-weight: 700; font-size: 13px; transition: all 0.3s; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; cursor: pointer; }
    .btn-manage:hover { background: #2563eb; color: #ffffff; box-shadow: 0 5px 15px rgba(37, 99, 235, 0.3); }
    
    .btn-disabled { background: #f8fafc; color: #94a3b8; border: 1px solid rgba(15, 23, 42, 0.05); padding: 8px 20px; border-radius: 50px; font-weight: 700; font-size: 13px; display: inline-flex; align-items: center; gap: 8px; cursor: not-allowed; }

    @media (max-width: 768px) {
        .premium-table thead { display: none; }
        .premium-table tbody tr { display: flex; flex-direction: column; margin-bottom: 15px; border: 1px solid rgba(15,23,42,0.05); }
        .premium-table tbody td { border: none !important; padding: 15px; border-bottom: 1px dashed rgba(15,23,42,0.05) !important; }
        .premium-table tbody td:last-child { border-bottom: none !important; text-align: center; }
        .td-dates { display: flex; justify-content: space-between; }
        .td-status { display: flex; justify-content: space-between; align-items: center; }
    }
</style>

<div class="main-content flex-grow-1 w-100 d-flex flex-column" style="min-height: calc(100vh - 70px);">
    <div class="page-header d-flex justify-content-between align-items-center flex-wrap gap-3">
        <div>
            <h3 class="fw-bold text-dark mb-1">My Domains</h3>
            <p class="text-muted mb-0" style="font-size: 14px;">Manage your registered domains and nameservers.</p>
        </div>
        <div>
            <a href="register-domain.php" class="btn btn-primary rounded-pill px-4 fw-bold shadow-sm">
                <i class="fa-solid fa-plus me-2"></i> Register New Domain
            </a>
        </div>
    </div>

    <div class="container pb-5">
        <div class="content-box">
            
            <?php if(empty($my_domains)): ?>
                <div class="text-center py-5">
                    <div class="mb-4">
                        <div class="bg-light rounded-circle d-inline-flex align-items-center justify-content-center" style="width: 100px; height: 100px;">
                            <i class="fa-solid fa-globe fs-1 text-muted opacity-50"></i>
                        </div>
                    </div>
                    <h4 class="fw-bold text-dark">No Domains Found</h4>
                    <p class="text-muted mb-4">You haven't registered any domains with us yet.</p>
                    <a href="register-domain.php" class="btn btn-primary rounded-pill px-4 fw-bold">Search Now</a>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table premium-table">
                        <thead>
                            <tr>
                                <th>Domain Name</th>
                                <th>Registration Date</th>
                                <th>Expiry Date</th>
                                <th>Status</th>
                                <th class="text-end">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($my_domains as $domain): ?>
                                <?php 
                                    $order_date = isset($domain['order_date']) ? $domain['order_date'] : date('Y-m-d H:i:s');
                                    $created_date = new DateTime($order_date);
                                    $expiry_date = clone $created_date;
                                    $period = isset($domain['period']) ? $domain['period'] : 1;
                                    $expiry_date->modify('+' . $period . ' years');
                                ?>
                                <tr>
                                    <td>
                                        <span class="domain-name"><?= htmlspecialchars($domain['item_name']) ?></span>
                                        <span class="domain-id"><i class="fa-solid fa-hashtag me-1"></i> <?= htmlspecialchars($domain['invoice_id'] ?? 'N/A') ?></span>
                                    </td>
                                    
                                    <td class="td-dates">
                                        <div class="d-md-none date-label mb-1">Registered On</div>
                                        <span class="date-text"><?= $created_date->format('d M, Y') ?></span>
                                    </td>
                                    
                                    <td class="td-dates">
                                        <div class="d-md-none date-label mb-1">Expires On</div>
                                        <span class="date-text text-primary"><?= $expiry_date->format('d M, Y') ?></span>
                                    </td>
                                    
                                    <td class="td-status">
                                        <div class="d-md-none date-label mb-2">Status</div>
                                        <?= getStatusBadge($domain['status']) ?>
                                    </td>
                                    
                                    <td class="text-md-end">
                                        <?php if($domain['status'] == 'active'): ?>
                                            <a href="manage-domain.php?id=<?= $domain['id'] ?>" class="btn-manage">
                                                <i class="fa-solid fa-gear"></i> Manage
                                            </a>
                                        <?php else: ?>
                                            <!-- পেন্ডিং থাকলে কোনো বাটন ক্লিক করা যাবে না, শুধু Processing দেখাবে -->
                                            <span class="btn-disabled" title="Domain is processing...">
                                                <i class="fa-solid fa-hourglass-half"></i> Processing
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>

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

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