<?php
require_once __DIR__ . '/includes/config.php';
requireLogin();

$user        = currentUser();
$currentPage = 'analyze';
$pageTitle   = 'Analyze Document – SPACE';

// Fetch recent uploaded documents
$stmt = db()->prepare('SELECT id, original_name, extracted_text, created_at FROM uploaded_docs WHERE user_id=? ORDER BY created_at DESC LIMIT 10');
$stmt->execute([$user['id']]);
$recentDocs = $stmt->fetchAll();

// Text Extraction Helper
function extractText(string $path, string $ext): string {
    switch ($ext) {
        case 'txt': case 'md': case 'csv':
            return mb_convert_encoding(file_get_contents($path), 'UTF-8', 'auto');
        case 'html':
            return strip_tags(mb_convert_encoding(file_get_contents($path), 'UTF-8', 'auto'));
        case 'pdf':
            $c = file_get_contents($path);
            $t = '';
            preg_match_all('/BT\s+(.*?)\s+ET/s', $c, $m);
            foreach ($m[1] ?? [] as $block) {
                preg_match_all('/\(([^)]+)\)/', $block, $s);
                foreach ($s[1] ?? [] as $x) $t .= stripcslashes($x) . ' ';
            }
            if (strlen(trim($t)) < 100) {
                preg_match_all('/stream\r?\n(.*?)\r?\nendstream/s', $c, $streams);
                foreach ($streams[1] ?? [] as $stream) {
                    $decoded = @gzuncompress($stream);
                    if (!$decoded) $decoded = @gzinflate(substr($stream, 2));
                    if ($decoded) {
                        preg_match_all('/\(([^)]{1,300})\)/', $decoded, $pm);
                        foreach ($pm[1] ?? [] as $p) $t .= $p . ' ';
                    }
                }
            }
            return trim(preg_replace('/\s+/', ' ', $t));
        case 'docx': case 'doc':
            if (!class_exists('ZipArchive')) return '';
            $zip = new ZipArchive();
            if ($zip->open($path) !== true) return '';
            $xml = $zip->getFromName('word/document.xml');
            $zip->close();
            if (!$xml) return '';
            $xml = preg_replace('/<w:br[^>]*\/>/', "\n", $xml);
            $xml = preg_replace('/<\/w:p>/', "\n", $xml);
            return trim(preg_replace('/\s+/', ' ', strip_tags($xml)));
        default:
            return '';
    }
}

function getFileIcon(string $name): string {
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    return match($ext) {
        'pdf'  => 'pdf',
        'docx','doc' => 'docx',
        'xlsx','xls' => 'xlsx',
        'pptx','ppt' => 'pptx',
        'txt','md'   => 'txt',
        'csv'        => 'csv',
        default      => 'file',
    };
}
function getFileColor(string $name): string {
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    return match($ext) {
        'pdf'  => '#ef4444',
        'docx','doc' => '#2563eb',
        'xlsx','xls' => '#16a34a',
        'pptx','ppt' => '#ea580c',
        'txt','md'   => '#6b7280',
        'csv'        => '#0891b2',
        default      => '#9333ea',
    };
}

$uploadMsg = '';
$docId = 0;
$viewDocId = 0;
$viewDocName = '';
$viewDocText = '';
$activeDocName = '';

// Handle Document Actions via AJAX API
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['doc_action'])) {
    $action = $_POST['doc_action'];
    $actionDocId = (int)($_POST['doc_id'] ?? 0);
    
    if (!$actionDocId) {
        jsonResponse(['success' => false, 'error' => 'No document ID']);
    }
    
    $stmt = db()->prepare('SELECT id, original_name, stored_name FROM uploaded_docs WHERE id=? AND user_id=?');
    $stmt->execute([$actionDocId, $user['id']]);
    $actionDoc = $stmt->fetch();
    
    if (!$actionDoc) {
        jsonResponse(['success' => false, 'error' => 'Document not found']);
    }
    
    if ($action === 'rename') {
        $newName = trim($_POST['new_name'] ?? '');
        $newName = preg_replace('/[^\w\s\-\.]/', '', $newName);
        if (empty($newName)) {
            jsonResponse(['success' => false, 'error' => 'Invalid document name']);
        }
        $updStmt = db()->prepare('UPDATE uploaded_docs SET original_name=? WHERE id=?');
        $updStmt->execute([$newName, $actionDocId]);
        jsonResponse(['success' => true, 'message' => 'Document renamed successfully!', 'new_name' => $newName]);
    } elseif ($action === 'delete') {
        $uploadDir = __DIR__ . '/uploads/';
        $filePath = $uploadDir . $actionDoc['stored_name'];
        if (file_exists($filePath)) unlink($filePath);
        $delStmt = db()->prepare('DELETE FROM uploaded_docs WHERE id=?');
        $delStmt->execute([$actionDocId]);
        jsonResponse(['success' => true, 'message' => 'Document deleted successfully!']);
    } elseif ($action === 'view') {
        $viewStmt = db()->prepare('SELECT original_name, extracted_text FROM uploaded_docs WHERE id=?');
        $viewStmt->execute([$actionDocId]);
        $viewDoc = $viewStmt->fetch();
        if ($viewDoc) {
            jsonResponse(['success' => true, 'name' => $viewDoc['original_name'], 'text' => $viewDoc['extracted_text']]);
        } else {
            jsonResponse(['success' => false, 'error' => 'Could not load document']);
        }
    }
}

// Handle File Upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_FILES['file'])) {
    if (!verifyCsrf($_POST['csrf_token'] ?? '')) {
        $uploadMsg = 'Invalid security token.';
    } else {
        $file = $_FILES['file'];
        if ($file['error'] === UPLOAD_ERR_OK) {
            $maxSize = 5 * 1024 * 1024; // 5MB
            $allowedExts = ['pdf','txt','docx','doc','html','csv','md'];
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            
            if (in_array($ext, $allowedExts) && $file['size'] <= $maxSize) {
                $uploadDir = __DIR__ . '/uploads/';
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
                $storedName = bin2hex(random_bytes(16)) . '.' . $ext;
                $dest = $uploadDir . $storedName;
                
                if (move_uploaded_file($file['tmp_name'], $dest)) {
                    $text = extractText($dest, $ext);
                    if (!empty(trim($text))) {
                        $text = mb_substr($text, 0, 6000); // Limit text length
                        
                        if (empty($_SESSION['chat_session_id'])) {
                            $_SESSION['chat_session_id'] = bin2hex(random_bytes(16));
                        }
                        $sessionId = $_SESSION['chat_session_id'];
                        
                        $stmt = db()->prepare('INSERT INTO uploaded_docs (user_id, session_id, original_name, stored_name, mime_type, file_size, extracted_text) VALUES (?,?,?,?,?,?,?)');
                        $stmt->execute([$user['id'], $sessionId, $file['name'], $storedName, $file['type'], $file['size'], $text]);
                        
                        $docId = db()->lastInsertId();
                        $activeDocName = $file['name'];
                        $uploadMsg = 'File uploaded and analyzed successfully!';
                    } else {
                        unlink($dest);
                        $uploadMsg = 'Could not extract text. Try a plain text or simpler PDF file.';
                    }
                } else {
                    $uploadMsg = 'Failed to save the file to the server.';
                }
            } else {
                $uploadMsg = 'Invalid file. Max 5MB. Allowed: PDF, TXT, DOCX, CSV, MD.';
            }
        } else {
            $uploadMsg = 'File upload error occurred.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, interactive-widget=resizes-content">
<title>Analyze Document – SPACE</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<style>
/* ── NEUMORPHIC STANDALONE VARIABLES ── */
:root {
  --bg: #e2e2e2;
  --light: #ffffff;
  --dark: #c1c1c1;
  --text: #111111;
  --muted: #777777;
  --blue: #0239eb;
  --green: #22c55e;
  --red: #ef4444;
  --neu-out: 5px 5px 10px var(--dark), -5px -5px 10px var(--light);
  --neu-in:  inset 3px 3px 6px var(--dark), inset -3px -3px 6px var(--light);
  --neu-sm:  3px 3px 7px var(--dark), -3px -3px 7px var(--light);
  --neu-lg:  7px 7px 14px var(--dark), -7px -7px 14px var(--light);
  --r-sm: 12px; --r-md: 16px; --r-lg: 22px;
}

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

html, body {
  width: 100%; height: 100dvh; background: var(--bg); font-family: 'Poppins', sans-serif;
  display: flex; justify-content: center; align-items: center; overflow: hidden;
  position: fixed; top: 0; left: 0; right: 0; bottom: 0; color: var(--text);
}

.shell {
  width: 100%; max-width: 600px; height: 100%; background: var(--bg);
  display: flex; flex-direction: column; position: relative;
  padding: clamp(15px, 2vh, 25px) clamp(15px, 4vw, 25px) clamp(10px, 2vh, 15px);
}

/* Header */
.header { display: flex; justify-content: space-between; align-items: center; flex-shrink: 0; margin-bottom: 2vh; z-index: 20; }
.icon-btn { width: 45px; height: 45px; border-radius: 50%; background: var(--bg); border: none; display: flex; align-items: center; justify-content: center; box-shadow: var(--neu-out); cursor: pointer; color: var(--text); transition: .15s; }
.icon-btn:active { box-shadow: var(--neu-in); }
.logo-circle { width: 70px; height: 70px; border-radius: 50%; background: var(--bg); box-shadow: var(--neu-lg); display: flex; align-items: center; justify-content: center; margin: 0 auto; cursor: pointer;}
.logo-circle img { width: 50px; height: 50px; }

.page-title { text-align: center; font-size: clamp(16px, 2.5vh, 20px); font-weight: 600; color: var(--text); margin-bottom: 1vh; flex-shrink: 0; }

/* Main Stage */
.main-stage { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 16px; width: 100%; padding: 1vh 5px 3vh 5px; -ms-overflow-style: none; scrollbar-width: none; }
.main-stage::-webkit-scrollbar { display: none; }

/* Upload Zone */
.upload-zone { 
  border: 2px dashed var(--dark); border-radius: 20px; padding: 30px 20px; 
  display: flex; flex-direction: column; align-items: center; justify-content: center; 
  gap: 12px; text-align: center; transition: .2s; background: var(--bg); cursor: pointer;
}
.upload-zone:active { background: #dcdcdc; }
.upload-icon { width: 60px; height: 60px; border-radius: 50%; background: var(--bg); box-shadow: var(--neu-out); display: flex; align-items: center; justify-content: center; color: var(--blue); }
.upload-icon svg { width: 28px; height: 28px; }
.upload-text { font-size: 14px; font-weight: 500; color: var(--text); }
.upload-hint { font-size: 11px; color: var(--muted); }

.msg-pill { padding: 10px 16px; border-radius: 12px; background: var(--bg); box-shadow: var(--neu-out); font-size: 12px; color: var(--green); text-align: center; font-weight: 500;}
.msg-error { color: var(--red); }

/* Document Preview Panel */
.doc-preview { background: var(--bg); border-radius: 20px; box-shadow: var(--neu-in); padding: 18px; display: flex; flex-direction: column; gap: 16px; }
.doc-header { display: flex; align-items: center; gap: 12px; }
.doc-icon { width: 45px; height: 45px; border-radius: 12px; background: var(--bg); box-shadow: var(--neu-out); display: flex; align-items: center; justify-content: center; color: var(--blue); flex-shrink: 0; }
.doc-icon svg { width: 22px; height: 22px; }
.doc-info { flex: 1; min-width: 0; }
.doc-name { font-size: 14px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--text); max-width: 100%;}
.doc-meta { font-size: 10px; color: var(--green); font-weight: 600; }

/* Custom Action Input */
.action-input-wrapper { display: flex; align-items: center; gap: 10px; width: 100%; }
.doc-input { flex: 1; height: 45px; border-radius: 22px; background: var(--bg); border: none; box-shadow: var(--neu-in); padding: 0 20px; font-family: 'Poppins', sans-serif; font-size: 12px; color: var(--text); outline: none; }
.send-btn { width: 45px; height: 45px; border-radius: 50%; background: var(--bg); border: none; box-shadow: var(--neu-out); display: flex; justify-content: center; align-items: center; cursor: pointer; color: var(--blue); transition: .15s; flex-shrink: 0;}
.send-btn:active { box-shadow: var(--neu-in); }

/* Action Pills */
.action-bar { display: flex; gap: 10px; flex-wrap: wrap; justify-content: space-between; }
.action-btn { flex: 1; min-width: max-content; padding: 10px 12px; border-radius: 14px; border: none; background: var(--bg); box-shadow: var(--neu-out); font-family: 'Poppins', sans-serif; font-size: 11px; font-weight: 600; color: var(--text); cursor: pointer; transition: .15s; display: flex; align-items: center; justify-content: center; gap: 6px; }
.action-btn:active { box-shadow: var(--neu-in); }
.action-btn svg { width: 14px; height: 14px; color: var(--blue); }

/* Recent Docs */
.recent-section { display: flex; flex-direction: column; gap: 10px; margin-top: 10px;}
.recent-title { font-size: 11px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 1px; padding-left: 5px;}
.recent-grid { display: flex; flex-wrap: wrap; place-content: center; gap: 10px; overflow-y: auto; -ms-overflow-style: none; scrollbar-width: none; width: 100%; }
.recent-grid::-webkit-scrollbar { display: none; }
.recent-card { flex-shrink: 0; width: 45%; background: var(--bg); border-radius: var(--r-md); padding: 12px 10px; cursor: pointer; transition: .15s; display: flex; flex-direction: column; align-items: center; gap: 6px; text-align: center; }
.recent-card:active { box-shadow: var(--neu-in); transform: scale(.97); }
.recent-card .doc-file-icon { width: 44px; height: 52px; border-radius: 6px; display: flex; align-items: center; justify-content: center; position: relative; font-size: 11px; font-weight: 800; color: #fff; letter-spacing: .5px; }
.recent-card .doc-file-icon::before { content: ''; position: absolute; top: 0; right: 0; width: 12px; height: 12px; background: rgba(255,255,255,.3); clip-path: polygon(100% 0,0 0,100% 100%); }
.recent-card .doc-name { font-size: 9px; font-weight: 600; color: var(--text); line-height: 1.3; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100%; }

/* ── MODALS & OVERLAYS ── */
.overlay { position: fixed; inset: 0; background: rgba(226,226,226,.5); backdrop-filter: blur(4px); z-index: 100; opacity: 0; pointer-events: none; transition: opacity .3s; }
.overlay.active { opacity: 1; pointer-events: all; }

/* Flashcard Setup Modal */
.modal { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%) scale(0.9); background: var(--bg); z-index: 102; width: 90%; max-width: 360px; border-radius: 24px; box-shadow: var(--neu-lg); padding: 25px; opacity: 0; pointer-events: none; transition: all .3s; display: flex; flex-direction: column; gap: 15px;}
.modal.active { opacity: 1; pointer-events: all; transform: translate(-50%, -50%) scale(1); }
.modal h2 { font-size: 18px; text-align: center; margin-bottom: 10px;}
.form-group { display: flex; flex-direction: column; gap: 6px; }
.form-group label { font-size: 11px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;}
.neu-input { width: 100%; padding: 12px 16px; border-radius: 12px; border: none; background: var(--bg); box-shadow: var(--neu-in); font-family: 'Poppins', sans-serif; font-size: 13px; color: var(--text); outline: none;}
.btn-neu { padding: 12px; border-radius: 12px; border: none; background: var(--bg); box-shadow: var(--neu-out); font-family: 'Poppins', sans-serif; font-size: 13px; font-weight: 600; cursor: pointer; transition: .1s; margin-top: 10px; color: var(--blue);}
.btn-neu:active { box-shadow: var(--neu-in); }
.btn-cancel { color: var(--red); margin-top: 0;}

/* Action Buttons */
.action-row { display: flex; gap: 8px; justify-content: center; }
.action-icon-btn { flex: 1; padding: 10px 8px; border-radius: 12px; border: none; background: var(--bg); box-shadow: var(--neu-out); font-family: 'Poppins', sans-serif; font-size: 10px; font-weight: 600; cursor: pointer; transition: .15s; display: flex; flex-direction: column; align-items: center; gap: 4px; color: var(--text); }
.action-icon-btn:active { box-shadow: var(--neu-in); }
.action-icon-btn svg { width: 18px; height: 18px; color: var(--blue); }
.action-icon-btn.btn-view svg { color: var(--blue); }
.action-icon-btn.btn-download svg { color: #16a34a; }
.action-icon-btn.btn-rename svg { color: #f59e0b; }
.action-icon-btn.btn-delete svg { color: var(--red); }

.embed-viewer { display: none; width: 100%; height: 350px; border-radius: 16px; overflow: hidden; background: #111; margin-top: 12px; box-shadow: var(--neu-in); }
.embed-viewer.active { display: block; }
.embed-viewer iframe { width: 100%; height: 100%; border: none; }

/* Confirm Modal */
.confirm-modal { text-align: center; }
.confirm-modal p { font-size: 13px; color: var(--text); margin-bottom: 10px; }
.confirm-actions { display: flex; gap: 10px; margin-top: 10px; }
.confirm-actions button { flex: 1; }
.btn-danger { color: var(--red); }

/* Toast Notifications */
.toast-container { position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); z-index: 200; display: flex; flex-direction: column; gap: 10px; pointer-events: none; }
.toast { padding: 12px 20px; border-radius: 12px; background: var(--bg); box-shadow: var(--neu-lg); font-size: 13px; font-weight: 500; color: var(--text); display: flex; align-items: center; gap: 10px; opacity: 0; transform: translateY(20px); transition: all .3s ease; pointer-events: auto; }
.toast.show { opacity: 1; transform: translateY(0); }
.toast.success { border-left: 4px solid var(--green); }
.toast.error { border-left: 4px solid var(--red); }
.toast.info { border-left: 4px solid var(--blue); }
.toast svg { width: 18px; height: 18px; flex-shrink: 0; }
.toast.success svg { color: var(--green); }
.toast.error svg { color: var(--red); }
.toast.info svg { color: var(--blue); }
</style>
</head>
<body>

<div class="shell">
  <div class="header">
    <button class="icon-btn" onclick="window.history.back()" title="Go Back">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" width="18"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
    </button>
    <div class="logo-wrap">
      <div class="logo-circle" onclick="window.location.href='dashboard.php'">
        <img src="assets/img/logo.svg" alt="S">
</div>

        <div class="embed-viewer" id="embed-viewer">
          <iframe id="embed-iframe" src=""></iframe>
        </div>
      </div>
    <div style="width:45px;"></div>
  </div>

  <h1 class="page-title">Document Hub</h1>

  <div class="main-stage">
    
    <label class="upload-zone" id="upload-zone">
      <div class="upload-icon">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
      </div>
      <div class="upload-text">Tap to upload a document</div>
      <div class="upload-hint">PDF, DOCX, TXT, CSV, MD (Max 5MB)</div>
    </label>

    <form id="upload-form" method="post" enctype="multipart/form-data" style="display:none;">
      <input type="hidden" name="csrf_token" value="<?= e(csrfToken()) ?>">
      <input type="file" name="file" id="file-input" accept=".pdf,.docx,.doc,.txt,.csv,.md,.html" onchange="submitUploadForm(this)">
    </form>

<script>
function submitUploadForm(input) {
    if(isSubmitting) {
        input.value = '';
        showToast('Please wait...', 'info');
        return;
    }
    isSubmitting = true;
    showToast('Uploading...', 'info');
    document.getElementById('upload-form').submit();
}
</script>

    <?php if ($uploadMsg): ?>
      <script>window.onload = function() { showToast(<?= json_encode($uploadMsg) ?>, <?= strpos($uploadMsg, 'error') !== false || strpos($uploadMsg, 'Invalid') !== false || strpos($uploadMsg, 'Failed') !== false ? "'error'" : "'success'" ?>); }</script>
    <?php endif; ?>

    <?php if ($docId): ?>
      <div class="doc-preview">
        <div class="doc-header">
          <div class="doc-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
          </div>
          <div class="doc-info">
            <div class="doc-name" id="current-doc-name"><?= e($activeDocName) ?></div>
            <div class="doc-meta">Ready for analysis</div>
          </div>
        </div>

        <div class="action-input-wrapper">
          <input type="text" class="doc-input" id="doc-ask-input" placeholder="Ask Astro about this doc..." onkeydown="if(event.key==='Enter') sendCustomDocRequest()">
          <button class="send-btn" onclick="sendCustomDocRequest()">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" width="18" style="margin-right:2px; margin-top:2px;"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
          </button>
        </div>

        <div class="action-bar">
          <button class="action-btn" onclick="sendDocToAI('Summarize this document into key bullet points.')">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="8" y1="6" x2="21" y2="6"></line><line x1="8" y1="12" x2="21" y2="12"></line><line x1="8" y1="18" x2="21" y2="18"></line><line x1="3" y1="6" x2="3.01" y2="6"></line><line x1="3" y1="12" x2="3.01" y2="12"></line><line x1="3" y1="18" x2="3.01" y2="18"></line></svg>
            Summarize
          </button>
          <button class="action-btn" onclick="window.location.href='flashcards.php?doc_id=<?= $docId ?>'">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M9 21V9"/></svg>
            Flashcards
          </button>
          <button class="action-btn" onclick="window.location.href='quiz.php?doc_id=<?= $docId ?>'">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
            Quiz
          </button>
        </div>

        <div class="action-row">
          <button class="action-icon-btn btn-view" onclick="toggleEmbedViewer(currentActiveDocId)">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
            View
          </button>
          <button class="action-icon-btn btn-download" onclick="downloadDoc(<?= $docId ?>)">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
            Download
          </button>
          <button class="action-icon-btn btn-rename" onclick="openRenameModal(<?= $docId ?>, '<?= e(addslashes($activeDocName)) ?>')">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"/></svg>
            Rename
          </button>
          <button class="action-icon-btn btn-delete" onclick="openDeleteModal(<?= $docId ?>)">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>
            Delete
          </button>
        </div>
        <div class="embed-viewer" id="embed-viewer">
          <iframe id="embed-iframe" src="" style="width:100%;height:100%;min-height:400px;border:none;background:#111;"></iframe>
        </div>
      </div>
    <?php endif; ?>

    <?php if (!empty($recentDocs) && !$docId): ?>
      <div class="recent-section">
        <div class="recent-title">Recent Documents</div>
        <div class="recent-grid">
        <?php foreach ($recentDocs as $doc): 
            $iconType = getFileIcon($doc['original_name']);
            $iconColor = getFileColor($doc['original_name']); ?>
          <div class="recent-card" onclick="loadPreviousDoc(<?= $doc['id'] ?>, '<?= e(addslashes($doc['original_name'])) ?>')">
            <div class="doc-file-icon" style="background:<?= $iconColor ?>;">
              <?= strtoupper($iconType) ?>
            </div>
            <div class="doc-name"><?= e($doc['original_name']) ?></div>
          </div>
        <?php endforeach; ?>
        </div>
      </div>
    <?php endif; ?>
  </div>
</div>

<div class="overlay" id="main-overlay" onclick="closeAllModals()"></div>

<!-- Rename Modal -->
<div class="modal confirm-modal" id="rename-modal">
  <h2>Rename Document</h2>
  <input type="hidden" id="rename-doc-id" value="">
  <div class="form-group">
    <label>New Name</label>
    <input type="text" id="rename-new-name" class="neu-input" placeholder="Enter new name...">
  </div>
  <div class="confirm-actions">
    <button class="btn-neu" onclick="submitRename()">Rename</button>
    <button class="btn-neu btn-cancel" onclick="closeRenameModal()">Cancel</button>
  </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal confirm-modal" id="delete-modal">
  <h2>Delete Document?</h2>
  <p>This action cannot be undone.</p>
  <input type="hidden" id="delete-doc-id" value="">
  <div class="confirm-actions">
    <button class="btn-neu btn-danger" onclick="submitDelete()">Delete</button>
    <button class="btn-neu btn-cancel" onclick="closeDeleteModal()">Cancel</button>
  </div>
</div>

<script>
// Trigger file selector
document.getElementById('upload-zone').addEventListener('click', () => {
  document.getElementById('file-input').click();
});

// Variables
let currentActiveDocId = <?= $docId ? $docId : 0 ?>;

// Toast Notification System
let isSubmitting = false;

function showToast(message, type = 'info') {
    const container = document.getElementById('toast-container');
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    
    const icons = {
        success: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>',
        error: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>',
        info: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>'
    };
    
    toast.innerHTML = icons[type] + message;
    container.appendChild(toast);
    
    setTimeout(() => toast.classList.add('show'), 10);
    
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

function safeSubmit(form, message, type = 'info') {
    if (isSubmitting) {
        showToast('Please wait...', 'info');
        return false;
    }
    isSubmitting = true;
    showToast(message, type);
    return true;
}

// If a user clicks a past document, fake-load it into the active slot
function loadPreviousDoc(id, name) {
    // A quick hack to visually load it by redirecting with a GET parameter
    // In a real app you might use AJAX to render the panel, but since we are PHP driven:
    window.location.href = 'analyze.php?load_doc=' + id;
}

// Check if we loaded a previous doc via GET
<?php if (isset($_GET['load_doc'])): ?>
    <?php
      $loadId = (int)$_GET['load_doc'];
      $checkStmt = db()->prepare('SELECT original_name FROM uploaded_docs WHERE id=? AND user_id=?');
      $checkStmt->execute([$loadId, $user['id']]);
      $loaded = $checkStmt->fetch();
      if ($loaded) {
          echo "currentActiveDocId = {$loadId};\n";
          echo "document.querySelector('.upload-zone').style.display = 'none';\n";
          // Inject the doc preview HTML dynamically via JS or reload logic
          // For simplicity, we just trigger the UI elements.
      }
    ?>
    // Force a visual state change if loaded from URL
    window.onload = function() {
        if(currentActiveDocId > 0) {
            document.querySelector('.upload-zone').insertAdjacentHTML('afterend', `
            <div class="doc-preview" id="injected-preview">
                <div class="doc-header">
                    <div class="doc-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg></div>
                    <div class="doc-info">
                        <div class="doc-name" style="max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"><?= $loaded ? e($loaded['original_name']) : '' ?></div>
                        <div class="doc-meta">Ready for analysis</div>
                    </div>
                </div>
                <div class="action-input-wrapper">
                    <input type="text" class="doc-input" id="doc-ask-input" placeholder="Ask Astro about this doc..." onkeydown="if(event.key==='Enter') sendCustomDocRequest()">
                    <button class="send-btn" onclick="sendCustomDocRequest()"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" width="18" style="margin-right:2px; margin-top:2px;"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg></button>
                </div>
                <div class="action-bar">
                    <button class="action-btn" onclick="sendDocToAI('Summarize this document into key bullet points.')">Summarize</button>
                    <button class="action-btn" onclick="window.location.href='flashcards.php?doc_id=${currentActiveDocId}'">Flashcards</button>
                    <button class="action-btn" onclick="window.location.href='quiz.php?doc_id=${currentActiveDocId}'">Quiz</button>
                </div>
                <div class="action-row">
                    <button class="action-icon-btn btn-view" onclick="toggleEmbedViewer(${currentActiveDocId})">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                        View
                    </button>
                    <button class="action-icon-btn btn-download" onclick="downloadDoc(${currentActiveDocId})">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                        Download
                    </button>
                    <button class="action-icon-btn btn-rename" onclick="openRenameModal(${currentActiveDocId}, '<?= e(addslashes($loaded['original_name'])) ?>')">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"/></svg>
                        Rename
                    </button>
                    <button class="action-icon-btn btn-delete" onclick="openDeleteModal(${currentActiveDocId})">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>
                        Delete
                    </button>
                </div>
                <div class="embed-viewer" id="embed-viewer-injected">
                    <iframe id="embed-iframe-injected" src=""></iframe>
                </div>
            </div>`);
            document.querySelector('.upload-zone').style.display = 'none';
            if(document.querySelector('.recent-section')) document.querySelector('.recent-section').style.display = 'none';
        }
    };
<?php endif; ?>


// Redirect logic for standard AI Chat
function sendCustomDocRequest() {
    const msg = document.getElementById('doc-ask-input').value.trim();
    if(msg) sendDocToAI(msg);
}

function sendDocToAI(message) {
    if(!currentActiveDocId) return;
    
    // Store the intended message in localStorage so ai.php can auto-send it
    localStorage.setItem('auto_send_msg', message);
    localStorage.setItem('auto_send_doc', currentActiveDocId);
    
    window.location.href = 'ai.php';
}

function toggleEmbedViewer(docId) {
    docId = docId || currentActiveDocId;
    if(!docId) return showToast('No document selected', 'error');
    
    const viewer = document.getElementById('embed-viewer') || document.getElementById('embed-viewer-injected');
    const iframe = document.getElementById('embed-iframe') || document.getElementById('embed-iframe-injected');
    
    if(!viewer || !iframe) return showToast('Error loading viewer', 'error');
    
    if(viewer.classList.contains('active')) {
        viewer.classList.remove('active');
        iframe.src = '';
    } else {
        showToast('Loading document...', 'info');
        iframe.src = 'view_doc.php?doc_id=' + docId;
        viewer.classList.add('active');
    }
}

function closeAllModals() {
    document.getElementById('view-modal').classList.remove('active');
    document.getElementById('rename-modal').classList.remove('active');
    document.getElementById('delete-modal').classList.remove('active');
    document.getElementById('main-overlay').classList.remove('active');
}

// Rename Modal
function openRenameModal(docId, currentName) {
    document.getElementById('rename-doc-id').value = docId;
    document.getElementById('rename-new-name').value = currentName;
    document.getElementById('rename-modal').classList.add('active');
    document.getElementById('main-overlay').classList.add('active');
}

function closeRenameModal() {
    document.getElementById('rename-modal').classList.remove('active');
    document.getElementById('main-overlay').classList.remove('active');
}

async function submitRename() {
    const docId = document.getElementById('rename-doc-id').value;
    const newName = document.getElementById('rename-new-name').value.trim();
    if(!newName) return showToast('Please enter a new name.', 'error');
    if(isSubmitting) return showToast('Please wait...', 'info');
    isSubmitting = true;
    showToast('Renaming...', 'info');
    
    try {
        const formData = new FormData();
        formData.append('doc_action', 'rename');
        formData.append('doc_id', docId);
        formData.append('new_name', newName);
        
        const response = await fetch('analyze.php', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        isSubmitting = false;
        
        if(data.success) {
            showToast(data.message, 'success');
            closeRenameModal();
            setTimeout(() => window.location.reload(), 1500);
        } else {
            showToast(data.error || 'Failed to rename', 'error');
        }
    } catch(e) {
        isSubmitting = false;
        showToast('Error renaming', 'error');
    }
}

// Delete Modal
function openDeleteModal(docId) {
    document.getElementById('delete-doc-id').value = docId;
    document.getElementById('delete-modal').classList.add('active');
    document.getElementById('main-overlay').classList.add('active');
}

function closeDeleteModal() {
    document.getElementById('delete-modal').classList.remove('active');
    document.getElementById('main-overlay').classList.remove('active');
}

async function submitDelete() {
    const docId = document.getElementById('delete-doc-id').value;
    if(isSubmitting) return showToast('Please wait...', 'info');
    isSubmitting = true;
    showToast('Deleting...', 'error');
    
    try {
        const formData = new FormData();
        formData.append('doc_action', 'delete');
        formData.append('doc_id', docId);
        
        const response = await fetch('analyze.php', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        isSubmitting = false;
        
        if(data.success) {
            showToast(data.message, 'success');
            closeDeleteModal();
            setTimeout(() => window.location.href = 'analyze.php', 1500);
        } else {
            showToast(data.error || 'Failed to delete', 'error');
        }
    } catch(e) {
        isSubmitting = false;
        showToast('Error deleting', 'error');
    }
}

// Download Document
function downloadDoc(docId) {
    docId = docId || currentActiveDocId;
    if(!docId) return showToast('No document selected', 'error');
    if(isSubmitting) return showToast('Please wait...', 'info');
    isSubmitting = true;
    showToast('Downloading...', 'info');
    setTimeout(() => {
        window.location.href = 'download.php?doc_id=' + docId;
        isSubmitting = false;
    }, 500);
}
</script>

<div class="toast-container" id="toast-container"></div>
</body>
</html>