<?php
require 'config.php';
require_login();

if (!function_exists('h')) {
    function h($s){ return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }
}

// 1) Get subcategory details
$subcat_id = (int)($_GET['subcategory_id'] ?? 0);
if ($subcat_id <= 0) redirect('index.php');

$stmt = $pdo->prepare("SELECT sc.*, s.name AS service_name FROM subcategories sc 
                        JOIN services s ON sc.service_id = s.id WHERE sc.id=?");
$stmt->execute([$subcat_id]);
$subcat = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$subcat) redirect('index.php');

// 2) Get user details
$user_id = $_SESSION['user_id'];
$stmt = $pdo->prepare("SELECT id, name, email, balance FROM users WHERE id=?");
$stmt->execute([$user_id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// 3) Handle order
if (is_post()) {
    verify_csrf();
    $service_info = trim($_POST['service_info'] ?? '');

    if ($user['balance'] < $subcat['price']) {
        set_flash("অর্ডার করার জন্য পর্যাপ্ত ব্যালেন্স নেই।", "danger");
        redirect("order.php?subcategory_id={$subcat_id}");
    }
    if (empty($service_info)) {
        set_flash("অনুগ্রহ করে প্রয়োজনীয় তথ্য দিন।", "danger");
        redirect("order.php?subcategory_id={$subcat_id}");
    }

    try {
        $pdo->beginTransaction();

        $pdo->prepare("UPDATE users SET balance=balance-? WHERE id=?")
            ->execute([$subcat['price'], $user_id]);

        $pdo->prepare("INSERT INTO orders (user_id, service_id, subcategory_id, price, id_number)
                      VALUES (?,?,?,?,?)")
            ->execute([$user_id, $subcat['service_id'], $subcat['id'], $subcat['price'], $service_info]);

        if (function_exists('sendTelegramMessage')) {
            $msg = "<b>New Order!</b>\n\n<b>User:</b> " . h($user['email']) .
                   "\n<b>Service:</b> " . h($subcat['service_name']) .
                   "\n<b>Subcategory:</b> " . h($subcat['name']) .
                   "\n<b>Price:</b> " . h($subcat['price']) .
                   "\n<b>Info:</b> " . h($service_info) .
                   "\n\n<b>Time:</b> " . date("d M Y, h:i A");
            sendTelegramMessage($msg, $settings);
        }

        $pdo->commit();
        set_flash("আপনার অর্ডার সফলভাবে সম্পন্ন হয়েছে!", "success");
    } catch (Exception $e) {
        $pdo->rollBack();
        set_flash("অর্ডার ব্যর্থ হয়েছে: " . $e->getMessage(), "danger");
    }

    redirect("order.php?subcategory_id={$subcat_id}");
}

// 4) Fetch order history
$stmt = $pdo->prepare("
    SELECT o.*, sc.name AS subcat_name
    FROM orders o
    LEFT JOIN subcategories sc ON sc.id = o.subcategory_id
    WHERE o.user_id=? AND o.subcategory_id=?
    ORDER BY o.id DESC
");
$stmt->execute([$user_id, $subcat_id]);
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

require_once 'header.php';
?>

<link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">

<style>
:root {
    --primary: #6C3FAA;
    --primary-dark: #4B2A7A;
    --accent: #FF9F43;
    --bg-light: #F8F5FD;
    --card-bg: #FFFFFF;
    --text-dark: #1E1135;
    --text-muted: #6C6A7A;
    --border: #E2DEF0;
    --success: #10B981;
    --warning: #F59E0B;
    --danger: #EF4444;
    --info: #3B82F6;
    --shadow-sm: 0 4px 15px rgba(108, 63, 170, 0.08);
    --shadow-md: 0 8px 25px rgba(108, 63, 170, 0.12);
    --shadow-lg: 0 12px 40px rgba(108, 63, 170, 0.2);
    --radius: 20px;
    --transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background: linear-gradient(135deg, #F5F0FF 0%, #EDE4FB 100%);
    font-family: 'Hind Siliguri', sans-serif;
    color: var(--text-dark);
    min-height: 100vh;
}

.premium-container {
    max-width: 1140px;
    margin: 0 auto;
    padding: 2rem 1.5rem;
}

/* Hero Header */
.hero-header {
    background: linear-gradient(135deg, #7B4DC7 0%, #542E90 100%);
    border-radius: var(--radius);
    padding: 2.5rem 2rem;
    color: white;
    margin-bottom: 2rem;
    box-shadow: var(--shadow-lg);
    position: relative;
    overflow: hidden;
}
.hero-header::after {
    content: '';
    position: absolute;
    width: 200px;
    height: 200px;
    background: rgba(255,255,255,0.05);
    border-radius: 50%;
    top: -60px;
    right: -60px;
}
.breadcrumb {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 1rem;
    position: relative;
    z-index: 1;
}
.breadcrumb a {
    color: var(--accent);
    text-decoration: none;
    font-weight: 600;
    transition: var(--transition);
}
.breadcrumb a:hover { color: white; }
.breadcrumb span { color: rgba(255,255,255,0.7); }
.hero-title {
    font-size: 2rem;
    font-weight: 700;
    position: relative;
    z-index: 1;
}

/* Premium Card */
.premium-card {
    background: var(--card-bg);
    border-radius: var(--radius);
    border: 1px solid var(--border);
    box-shadow: var(--shadow-sm);
    overflow: hidden;
    transition: var(--transition);
}
.premium-card:hover { box-shadow: var(--shadow-md); }
.card-header-premium {
    background: #FAF8FE;
    padding: 1.2rem 1.8rem;
    border-bottom: 1px solid var(--border);
    font-weight: 700;
    color: var(--primary-dark);
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 1.1rem;
}
.card-body { padding: 1.8rem; }

/* Price Box */
.price-box {
    background: linear-gradient(135deg, #F1ECFB, #E6DEF7);
    border: 1px solid var(--border);
    padding: 1rem 1.5rem;
    border-radius: 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;
}
.price-label { font-weight: 700; color: var(--primary-dark); }
.price-value { font-weight: 900; color: var(--primary); font-size: 1.4rem; }

/* Notice Box */
.notice-box {
    background: #FFF8E7;
    border-left: 4px solid var(--accent);
    padding: 1rem 1.2rem;
    border-radius: 10px;
    margin-bottom: 1.5rem;
    color: #856404;
    font-size: 0.95rem;
    line-height: 1.6;
}

/* Form */
.form-label {
    font-weight: 600;
    color: var(--text-dark);
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    gap: 6px;
}
.form-control {
    width: 100%;
    padding: 12px 16px;
    border: 1px solid var(--border);
    border-radius: 12px;
    font-size: 1rem;
    background: white;
    transition: var(--transition);
    font-family: 'Hind Siliguri', sans-serif;
    resize: vertical;
}
.form-control:focus {
    border-color: var(--primary);
    box-shadow: 0 0 0 4px rgba(108,63,170,0.1);
    outline: none;
}

.btn-premium {
    background: linear-gradient(135deg, #7B4DC7, #542E90);
    border: none;
    color: white;
    padding: 14px 24px;
    border-radius: 14px;
    font-weight: 700;
    font-size: 1rem;
    width: 100%;
    cursor: pointer;
    transition: var(--transition);
    box-shadow: 0 8px 20px rgba(108,63,170,0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}
.btn-premium:hover {
    transform: translateY(-2px);
    box-shadow: 0 12px 25px rgba(108,63,170,0.4);
    background: linear-gradient(135deg, #8A5ED4, #6337A0);
}

/* History Item */
.history-item {
    background: var(--card-bg);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 1.5rem;
    margin-bottom: 1rem;
    transition: var(--transition);
}
.history-item:hover {
    border-color: var(--primary);
    box-shadow: var(--shadow-md);
    transform: translateX(4px);
}
.history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 1rem;
    border-bottom: 1px solid var(--border);
    margin-bottom: 1rem;
}
.status-badge {
    padding: 5px 14px;
    border-radius: 50px;
    font-weight: 700;
    font-size: 0.75rem;
    text-transform: uppercase;
}
.st-pending { background: #FEF3C7; color: #92400E; }
.st-received { background: #DBEAFE; color: #1E40AF; }
.st-completed { background: #D1FAE5; color: #065F46; }
.st-cancelled { background: #FEE2E2; color: #991B1B; }

.delivery-box {
    background: #F8F5FD;
    padding: 1rem;
    border-radius: 12px;
    border: 1px solid var(--border);
    font-family: monospace;
    font-size: 0.9rem;
    margin-top: 10px;
    word-break: break-all;
    border-left: 4px solid var(--primary);
    color: var(--text-dark);
}
.btn-copy, .btn-download {
    width: 100%;
    padding: 10px;
    border-radius: 10px;
    font-weight: 600;
    border: none;
    cursor: pointer;
    transition: var(--transition);
    font-family: 'Hind Siliguri', sans-serif;
}
.btn-copy {
    background: var(--primary);
    color: white;
    margin-top: 10px;
}
.btn-copy:hover { background: var(--primary-dark); }
.btn-download {
    background: var(--success);
    color: white;
    margin-top: 10px;
    text-decoration: none;
    display: block;
    text-align: center;
}
.btn-download:hover { background: #059669; }

/* Empty State */
.empty-state {
    text-align: center;
    padding: 3rem;
}
.empty-state i {
    font-size: 3rem;
    color: #D1CAE5;
    margin-bottom: 1rem;
}

@media (max-width: 850px) {
    .premium-container { padding: 1rem; }
    .hero-title { font-size: 1.5rem; }
}
</style>

<div class="premium-container">
    <?php show_flash(); ?>

    <!-- Hero Header -->
    <div class="hero-header">
        <div class="breadcrumb">
            <a href="index.php"><i class="bi bi-house-door-fill"></i> হোম</a>
            <span><i class="bi bi-chevron-right small"></i></span>
            <span>অর্ডার করুন</span>
        </div>
        <h1 class="hero-title"><?php echo h($subcat['name']); ?></h1>
    </div>

    <div style="display: grid; grid-template-columns: 1fr 1.6fr; gap: 1.5rem;">
        <!-- Order Form -->
        <div class="premium-card">
            <div class="card-header-premium">
                <i class="bi bi-cart-plus-fill"></i> আবেদন ফরম
            </div>
            <div class="card-body">
                <div class="price-box">
                    <span class="price-label">সার্ভিস মূল্য:</span>
                    <span class="price-value">৳ <?php echo number_format($subcat['price'], 0); ?></span>
                </div>

                <?php if (!empty($subcat['notice'])): ?>
                    <div class="notice-box">
                        <i class="bi bi-info-circle-fill me-1"></i>
                        <?php echo nl2br(h($subcat['notice'])); ?>
                    </div>
                <?php endif; ?>

                <form method="post">
                    <?php csrf_field(); ?>
                    <div style="margin-bottom: 1.5rem;">
                        <label class="form-label">
                            <i class="bi bi-pencil-square"></i> প্রয়োজনীয় তথ্য দিন:
                        </label>
                        <textarea name="service_info" class="form-control" rows="5" placeholder="<?php echo h($subcat['order_text']); ?>" required></textarea>
                    </div>
                    <button type="submit" class="btn-premium">
                        <i class="bi bi-check-circle-fill"></i> অর্ডার নিশ্চিত করুন
                    </button>
                </form>
            </div>
        </div>

        <!-- Order History -->
        <div class="premium-card">
            <div class="card-header-premium">
                <i class="bi bi-clock-history"></i> আপনার এই সার্ভিস হিস্টরি
            </div>
            <div class="card-body">
                <?php if (!$orders): ?>
                    <div class="empty-state">
                        <i class="bi bi-inbox"></i>
                        <p class="text-muted">এখনো কোনো অর্ডার করা হয়নি।</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($orders as $o):
                        $status = strtolower($o['status']);
                        $badge_class = 'st-pending'; $status_text = 'Pending';
                        if ($status == 'received') { $badge_class = 'st-received'; $status_text = 'Received'; }
                        elseif ($status == 'completed') { $badge_class = 'st-completed'; $status_text = 'Completed'; }
                        elseif ($status == 'cancelled') { $badge_class = 'st-cancelled'; $status_text = 'Cancelled'; }
                    ?>
                        <div class="history-item">
                            <div class="history-header">
                                <span class="fw-bold" style="color:var(--primary);">অর্ডার আইডি: #<?php echo (int)$o['id']; ?></span>
                                <span class="status-badge <?php echo $badge_class; ?>"><?php echo $status_text; ?></span>
                            </div>
                            <div style="margin-bottom: 0.8rem;">
                                <small style="color: var(--text-muted);">আপনার ইনপুট:</small><br>
                                <strong><?php echo h($o['id_number']); ?></strong>
                            </div>
                            <small style="color: var(--text-muted);">
                                <i class="bi bi-calendar-event"></i> <?php echo date("d M Y, h:i A", strtotime($o['created_at'])); ?>
                            </small>

                            <?php if ($status === 'completed'): ?>
                                <div style="margin-top: 1rem;">
                                    <?php if ($o['delivery_type'] === 'text'): ?>
                                        <div class="delivery-box" id="delivery-<?php echo $o['id']; ?>"><?php echo h($o['delivery_text']); ?></div>
                                        <button class="btn-copy" onclick="copyDelivery(<?php echo $o['id']; ?>)">
                                            <i class="bi bi-clipboard-check"></i> কপি করুন
                                        </button>
                                    <?php elseif ($o['delivery_type'] === 'file'): ?>
                                        <a href="uploads/<?php echo rawurlencode($o['delivery_file']); ?>" class="btn-download" download>
                                            <i class="bi bi-cloud-arrow-down"></i> ফাইল ডাউনলোড করুন
                                        </a>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
function copyDelivery(id){
    const el = document.getElementById('delivery-'+id);
    navigator.clipboard.writeText(el.innerText).then(() => {
        alert('সফলভাবে কপি করা হয়েছে!');
    });
}
</script>

<?php require_once 'footer.php'; ?>