<?php
require_once 'config/config.php';
require_once 'includes/functions.php';
startSecureSession();
$pageTitle = 'RFQ Cart';

// Handle form actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'remove') {
        removeFromCart((int)$_POST['item_id']);
        $_SESSION['flash']['success'] = 'Item removed from cart.';
        $target = (SITE_URL ? rtrim(SITE_URL, '/') : '') . '/quote-cart.php';
        header("Location: $target");
        exit;
    }

    if ($action === 'submit_rfq') {
        $items = getCartItems();
        if (empty($items)) {
            $_SESSION['flash']['error'] = 'Your RFQ cart is empty.';
            $target = (SITE_URL ? rtrim(SITE_URL, '/') : '') . '/quote-cart.php';
            header("Location: $target");
            exit;
        }

        $customerId   = $_SESSION['customer_id'] ?? null;
        $name         = sanitize($_POST['contact_name'] ?? '');
        $email        = sanitize($_POST['contact_email'] ?? '');
        $company      = sanitize($_POST['company_name'] ?? '');
        $phone        = sanitize($_POST['phone'] ?? '');
        $notes        = sanitize($_POST['notes'] ?? '');
        $validUntil   = date('Y-m-d', strtotime('+30 days'));

        // If not logged in, check email
        if (!$customerId) {
            if (!$name || !$email) {
                $_SESSION['flash']['error'] = 'Name and email are required.';
                $target = (SITE_URL ? rtrim(SITE_URL, '/') : '') . '/quote-cart.php';
                header("Location: $target");
                exit;
            }
            // Create or find customer
            $existing = Database::fetchOne("SELECT id FROM customers WHERE email=?", [$email]);
            if ($existing) {
                $customerId = $existing['id'];
            } else {
                $customerId = Database::insert(
                    "INSERT INTO customers (company_name, contact_name, email, password, phone) VALUES (?,?,?,?,?)",
                    [$company ?: $name, $name, $email, password_hash(bin2hex(random_bytes(8)), PASSWORD_BCRYPT), $phone]
                );
            }
        } else {
            $cust = getCurrentCustomer();
            $name = $cust['contact_name'];
            $email = $cust['email'];
        }

        // Handle attachment
        $attachment = null;
        if (!empty($_FILES['attachment']['tmp_name'])) {
            $res = handleFileUpload($_FILES['attachment'], 'documents', array_merge(ALLOWED_IMAGE_TYPES, ALLOWED_DOC_TYPES));
            if ($res['success']) $attachment = $res['filename'];
        }

        // Create quotation
        $quoteNum = generateNumber(setting('quote_prefix', 'RFQ-'), 'quotations', 'quote_number');
        $quoteId = Database::insert(
            "INSERT INTO quotations (quote_number, customer_id, notes, attachment, valid_until) VALUES (?,?,?,?,?)",
            [$quoteNum, $customerId, $notes, $attachment, $validUntil]
        );

        // Insert items
        foreach ($items as $item) {
            Database::insert(
                "INSERT INTO quotation_items (quotation_id, product_id, description, quantity, notes) VALUES (?,?,?,?,?)",
                [$quoteId, $item['product_id'], $item['product_name'], $item['quantity'], $item['notes']]
            );
        }

        clearCart();
        logActivity('customer', $customerId, 'RFQ Submitted', "Quote #$quoteNum");
        sendEmailFromTemplate('rfq_received', $email, [
            'customer_name' => $name, 'quote_number' => $quoteNum
        ]);

        $_SESSION['flash']['success'] = "RFQ submitted successfully! Reference: $quoteNum. We'll respond within 24-48 hours.";
        $target = (SITE_URL ? rtrim(SITE_URL, '/') : '') . '/quote-cart.php';
        header("Location: $target");
        exit;
    }
}

$items = getCartItems();
$customer = getCurrentCustomer();
include 'includes/header.php';
?>

<div class="max-w-7xl mx-auto px-4 py-20">
  <div class="flex flex-col md:flex-row md:items-end justify-between gap-6 mb-12 fade-in">
    <div>
      <nav class="text-[10px] font-bold uppercase tracking-widest text-gray-500 mb-2">
        <a href="/" class="hover:text-orange-500 transition-colors">Industrial Hub</a> / <span class="text-orange-500">RFQ Terminal</span>
      </nav>
      <h1 class="text-4xl font-black text-white leading-tight">Request for <span class="text-orange-500">Quotation</span></h1>
    </div>
    <div class="flex items-center gap-4">
      <div class="text-right hidden sm:block">
        <div class="text-[10px] font-bold uppercase tracking-widest text-gray-500">Session Status</div>
        <div class="text-sm font-medium text-green-500 flex items-center gap-2 justify-end">
          <span class="w-1.5 h-1.5 rounded-full bg-green-500 animate-pulse"></span>
          Secure B2B Channel
        </div>
      </div>
    </div>
  </div>

  <?php if (empty($items)): ?>
  <div class="text-center py-24 glass-panel p-16 rounded-3xl fade-in overflow-hidden relative">
    <div class="absolute inset-0 bg-gradient-to-b from-orange-600/5 to-transparent opacity-50"></div>
    <div class="relative z-10">
      <div class="text-8xl mb-8">📦</div>
      <h2 class="text-3xl font-black text-white mb-4 uppercase tracking-tighter">Your RFQ Vault is Empty</h2>
      <p class="text-gray-400 max-w-md mx-auto mb-10 leading-relaxed">Add technical specifications and products to your cart to receive a comprehensive industrial quotation from our specialists.</p>
      <a href="/shop.php" class="btn-primary px-12 py-4 text-sm font-black uppercase tracking-widest">Explore Product Range →</a>
    </div>
  </div>
  <?php else: ?>
  <div class="grid grid-cols-1 lg:grid-cols-12 gap-12">
    <!-- Items -->
    <div class="lg:col-span-7 space-y-8">
      <div class="glass-panel rounded-2xl overflow-hidden fade-in">
        <div class="px-8 py-5 border-b border-white/5 bg-white/5 flex justify-between items-center">
          <h3 class="text-xs font-black uppercase tracking-widest text-gray-300">Technical Data Sheet (<?= count($items) ?> Items)</h3>
          <span class="text-[10px] py-1 px-2 rounded-full bg-orange-600/10 text-orange-500 font-bold border border-orange-600/20 uppercase tracking-widest">Active RFQ</span>
        </div>
        <div class="divide-y divide-white/5">
          <?php foreach ($items as $item): ?>
          <div class="p-8 group hover:bg-white/[0.02] transition-colors flex gap-6 items-start">
            <div class="relative shrink-0">
              <?php if ($item['image']): ?>
              <img src="/uploads/<?= e($item['image']) ?>" class="w-24 h-24 object-cover rounded-xl border border-white/5 group-hover:border-orange-500/50 transition-colors" alt="">
              <?php else: ?>
              <div class="w-24 h-24 rounded-xl bg-navy-800 border border-white/5 flex items-center justify-center text-4xl group-hover:border-orange-500/50 transition-colors">⚙️</div>
              <?php endif; ?>
            </div>
            <div class="flex-1 pt-1">
              <div class="flex justify-between items-start mb-2">
                <a href="/product-detail.php?slug=<?= e($item['slug'] ?? '') ?>" class="text-lg font-black text-white hover:text-orange-500 transition-colors"><?= e($item['product_name']) ?></a>
                <form method="POST">
                  <input type="hidden" name="action" value="remove">
                  <input type="hidden" name="item_id" value="<?= $item['id'] ?>">
                  <button type="submit" class="text-gray-600 hover:text-red-500 transition-colors" onclick="return confirm('Remove this from RFQ?')">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                  </button>
                </form>
              </div>
              <div class="flex flex-wrap gap-4 text-xs font-medium text-gray-500 mb-4">
                <?php if ($item['sku']): ?><span>SKU • <?= e($item['sku']) ?></span><?php endif; ?>
                <span class="text-orange-500 uppercase tracking-widest font-bold">Qty • <?= $item['quantity'] ?></span>
              </div>
              <?php if ($item['notes']): ?>
              <div class="p-3 rounded-lg bg-navy-800/50 border border-white/5 text-[11px] text-gray-400 italic">
                "<?= e($item['notes']) ?>"
              </div>
              <?php endif; ?>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="glass-panel p-10 rounded-2xl fade-in">
        <h3 class="text-xl font-black text-white mb-8 border-l-4 border-orange-600 pl-4 uppercase tracking-tight">Technical Submission</h3>
        <form method="POST" enctype="multipart/form-data" class="space-y-8">
          <input type="hidden" name="action" value="submit_rfq">

          <?php if (!$customer): ?>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
            <div class="space-y-2">
              <label class="text-[10px] font-bold uppercase tracking-widest text-gray-500 block">Full Name <span class="text-orange-500">*</span></label>
              <input type="text" name="contact_name" required placeholder="Authorized Representative" class="w-full">
            </div>
            <div class="space-y-2">
              <label class="text-[10px] font-bold uppercase tracking-widest text-gray-500 block">Business Email <span class="text-orange-500">*</span></label>
              <input type="email" name="contact_email" required placeholder="office@company.com">
            </div>
          </div>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
            <div class="space-y-2">
              <label class="text-[10px] font-bold uppercase tracking-widest text-gray-500 block">Company / Entity</label>
              <input type="text" name="company_name" placeholder="Legal Organization Name">
            </div>
            <div class="space-y-2">
              <label class="text-[10px] font-bold uppercase tracking-widest text-gray-500 block">Direct Phone</label>
              <input type="tel" name="phone" placeholder="+92 ...">
            </div>
          </div>
          <?php else: ?>
          <div class="glass-card bg-orange-600/10 border-orange-600/20 p-6 flex items-center gap-4">
            <div class="w-12 h-12 rounded-full bg-orange-600 flex items-center justify-center text-xl">🏢</div>
            <div>
              <div class="text-xs text-orange-500 font-bold uppercase tracking-wider">Authenticated Corporate Account</div>
              <div class="text-lg font-black text-white"><?= e($customer['contact_name']) ?> <span class="text-gray-500 text-sm font-medium">at <?= e($customer['company_name']) ?></span></div>
            </div>
          </div>
          <?php endif; ?>

          <div class="space-y-2">
            <label class="text-[10px] font-bold uppercase tracking-widest text-gray-500 block">Global Project Notes / Special Requirements</label>
            <textarea name="notes" rows="4" placeholder="Specify API standards, material grades (e.g. F51 Duplex, Inconel 625), coating requirements, and expected lead times..."></textarea>
          </div>

          <div class="space-y-2">
            <label class="text-[10px] font-bold uppercase tracking-widest text-gray-500 block">Upload Technical Specs / Drawings <span class="text-gray-600">(PDF, images up to 10MB)</span></label>
            <div class="flex items-center justify-center w-full">
                <label class="flex flex-col items-center justify-center w-full h-32 border-2 border-white/5 border-dashed rounded-2xl cursor-pointer hover:bg-white/[0.02] hover:border-orange-500/50 transition-all">
                    <div class="flex flex-col items-center justify-center pt-5 pb-6">
                        <svg class="w-8 h-8 mb-3 text-gray-400 group-hover:text-orange-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"/></svg>
                        <p class="text-[10px] font-bold uppercase tracking-widest text-gray-500"><span class="text-orange-500">Click to upload</span> or drag and drop</p>
                    </div>
                    <input type="file" name="attachment" class="hidden" accept=".pdf,.jpg,.jpeg,.png">
                </label>
            </div>
          </div>

          <div class="pt-6">
            <button type="submit" class="btn-primary w-full py-5 text-base uppercase tracking-widest font-black shadow-2xl shadow-orange-600/20">🚀 Execute RFQ Transmission</button>
            <div class="flex items-center justify-center gap-4 mt-6">
              <div class="flex items-center gap-2 text-[10px] font-bold text-gray-500"><span class="text-green-500">✓</span> SSL Encrypted</div>
              <div class="flex items-center gap-2 text-[10px] font-bold text-gray-500"><span class="text-green-500">✓</span> Priority Support</div>
              <div class="flex items-center gap-2 text-[10px] font-bold text-gray-500"><span class="text-green-500">✓</span> Technical Audit</div>
            </div>
          </div>
        </form>
      </div>
    </div>

    <!-- Sidebar Info -->
    <div class="lg:col-span-5 space-y-8">
      <div class="glass-panel p-10 rounded-2xl relative overflow-hidden group">
        <div class="absolute top-0 right-0 w-48 h-48 bg-orange-600/5 rounded-full -mr-24 -mt-24 blur-3xl"></div>
        <h3 class="text-xl font-black text-white mb-8 border-l-4 border-orange-600 pl-4 uppercase tracking-tight">RFQ Workflow</h3>
        <div class="space-y-8">
          <?php foreach ([
            ['📦', 'Strategic Sourcing', 'Submit your technical specifications to our global supply chain experts.'],
            ['🔬', 'Technical Validation', 'Our engineers verify material standards, sizes, and compatibility.'],
            ['📈', 'Direct Quotation', 'Receive a detailed pricing package within 24-48 business hours.'],
            ['🎛️', 'Procurement Execution', 'Finalize terms and trigger localized or global delivery logistics.'],
          ] as $i => [$icon, $title, $desc]): ?>
          <div class="flex gap-6 relative">
            <?php if ($i < 3): ?>
            <div class="absolute left-6 top-10 w-[1px] h-12 bg-white/5"></div>
            <?php endif; ?>
            <div class="w-12 h-12 rounded-2xl bg-navy-800 border border-white/5 flex items-center justify-center shrink-0 z-10 text-2xl group-hover:border-orange-500 transition-colors">
              <?= $icon ?>
            </div>
            <div>
              <h4 class="font-bold text-sm text-white mb-1 uppercase tracking-wider"><?= $title ?></h4>
              <p class="text-xs text-gray-500 leading-relaxed"><?= $desc ?></p>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="glass-panel p-10 rounded-2xl">
        <h3 class="text-xl font-black text-white mb-6 uppercase tracking-tight">Dedicated Support</h3>
        <p class="text-xs text-gray-500 mb-8 leading-relaxed">Need help with technical dimensions or API certifications? Our specialized team is available via direct B2B channels.</p>
        <div class="space-y-4">
          <a href="https://wa.me/<?= preg_replace('/[^0-9]/', '', setting('whatsapp')) ?>" class="glass-card p-4 flex items-center gap-4 hover:bg-green-600 group transition-all duration-500">
            <div class="w-10 h-10 rounded-xl bg-green-600/20 flex items-center justify-center text-xl group-hover:bg-white/20">💬</div>
            <div class="text-sm font-black text-white uppercase tracking-widest">WhatsApp Business</div>
          </a>
          <a href="tel:<?= e(setting('phone')) ?>" class="glass-card p-4 flex items-center gap-4 hover:bg-orange-600 group transition-all duration-500">
            <div class="w-10 h-10 rounded-xl bg-orange-600/20 flex items-center justify-center text-xl group-hover:bg-white/20">📞</div>
            <div class="text-sm font-black text-white uppercase tracking-widest"><?= e(setting('phone')) ?></div>
          </a>
        </div>
      </div>
      
      <!-- Trust Shield -->
      <div class="glass-panel p-8 rounded-2xl bg-gradient-to-br from-navy-800 to-navy-950 flex items-center gap-5">
        <div class="text-4xl">🛡️</div>
        <div>
          <div class="text-xs font-black text-white uppercase tracking-widest">Secure RFQ Protocol</div>
          <div class="text-[10px] text-gray-500 mt-1 uppercase tracking-widest font-bold">Standard ISO • 256-bit AES Encryption</div>
        </div>
      </div>
    </div>
  </div>
  <?php endif; ?>
</div>

<?php include 'includes/footer.php'; ?>
