<?php
/**
 * Stock Issue Sheets Generator
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);

// AUTH CHECK
$auth_token = $_COOKIE['rcp_auth'] ?? null;
if (!$auth_token) {
    header("Location: login.php");
    exit;
}

try {
    require_once __DIR__ . '/../includes/config.php';
    require_once __DIR__ . '/../includes/database.php';
    
    $pdo = Database::getInstance()->getConnection();
    
    $stmt = $pdo->prepare("SELECT session_data FROM user_sessions WHERE session_id = ? AND expires_at > NOW()");
    $stmt->execute([$auth_token]);
    $session_data = $stmt->fetchColumn();
    
    if (!$session_data) {
        header("Location: login.php");
        exit;
    }
    
    $user = json_decode($session_data, true);
    $user_id = $user['user_id'] ?? $user['id'] ?? null;
    
    if (!$user_id) {
        die("User ID not found in session.");
    }
    
    // Update last activity
    $user['last_activity'] = time();
    $updateStmt = $pdo->prepare("UPDATE user_sessions SET session_data = ?, expires_at = DATE_ADD(NOW(), INTERVAL 2 HOUR) WHERE session_id = ?");
    $updateStmt->execute([json_encode($user), $auth_token]);
    
    // Handle PDF generation - check if we just generated a PDF to trigger refresh
    $just_generated = false;
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['generate_issue_sheet'])) {
            generateIssueSheetPDF($pdo, $user_id);
            // This will exit, so code below won't run
        } elseif (isset($_POST['delete_download'])) {
            if (deleteDownloadRecord($pdo, $user_id)) {
                header("Location: issue_sheets.php?deleted=success");
                exit;
            }
        }
    }
    
    // Check if we're returning from a PDF generation (using session flag)
    session_start();
    if (isset($_SESSION['pdf_generated']) && $_SESSION['pdf_generated']) {
        $just_generated = true;
        unset($_SESSION['pdf_generated']);
        
        // Force refresh of recent downloads
        header("Location: issue_sheets.php?refreshed=true");
        exit;
    }
    
    // Get user's meals
    $meals = [];
    try {
        $columns = $pdo->query("SHOW COLUMNS FROM meals LIKE 'created_by'")->fetch();
        
        if ($columns) {
            $stmt = $pdo->prepare("
                SELECT m.*, 
                       COUNT(mc.id) as costing_count
                FROM meals m 
                LEFT JOIN meal_costings mc ON m.id = mc.meal_id
                WHERE m.created_by = ? 
                GROUP BY m.id
                ORDER BY m.created_at DESC
            ");
            $stmt->execute([$user_id]);
        } else {
            $stmt = $pdo->prepare("
                SELECT m.*, 
                       COUNT(mc.id) as costing_count
                FROM meals m 
                LEFT JOIN meal_costings mc ON m.id = mc.meal_id
                GROUP BY m.id
                ORDER BY m.created_at DESC
            ");
            $stmt->execute();
        }
        
        $meals = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
    } catch (Exception $e) {
        error_log("Error loading meals: " . $e->getMessage());
        $stmt = $pdo->prepare("SELECT * FROM meals ORDER BY created_at DESC");
        $stmt->execute();
        $meals = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    // Get recent downloads
    $recentDownloads = [];
    try {
        $stmt = $pdo->prepare("
            SELECT isd.*, m.name as actual_meal_name
            FROM issue_sheet_downloads isd
            LEFT JOIN meals m ON isd.meal_id = m.id
            WHERE isd.downloaded_by = ?
            ORDER BY isd.created_at DESC
            LIMIT 20
        ");
        $stmt->execute([$user_id]);
        $recentDownloads = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
    } catch (Exception $e) {
        $recentDownloads = [];
    }
    
} catch (Throwable $t) {
    die("Error: " . $t->getMessage());
}

// Function to delete download record
function deleteDownloadRecord($pdo, $user_id) {
    $download_id = $_POST['download_id'] ?? null;
    
    if (!$download_id) {
        return false;
    }
    
    try {
        // Verify the download belongs to the current user
        $verifyStmt = $pdo->prepare("SELECT id FROM issue_sheet_downloads WHERE id = ? AND downloaded_by = ?");
        $verifyStmt->execute([$download_id, $user_id]);
        $download = $verifyStmt->fetch();
        
        if ($download) {
            $deleteStmt = $pdo->prepare("DELETE FROM issue_sheet_downloads WHERE id = ?");
            $deleteStmt->execute([$download_id]);
            return true;
        }
    } catch (Exception $e) {
        error_log("Error deleting download record: " . $e->getMessage());
    }
    
    return false;
}

// Function to generate Stock Issue Sheet PDF
function generateIssueSheetPDF($pdo, $user_id) {
    // Set session flag before generating PDF
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    $_SESSION['pdf_generated'] = true;
    session_write_close();
    
    $meal_id = $_POST['meal_id'] ?? null;
    $custom_people_count = $_POST['people_count'] ?? null;
    
    if (!$meal_id) {
        die("No meal selected.");
    }
    
    // Get meal details
    try {
        $columns = $pdo->query("SHOW COLUMNS FROM meals LIKE 'created_by'")->fetch();
        
        if ($columns) {
            $stmt = $pdo->prepare("SELECT * FROM meals WHERE id = ? AND created_by = ?");
            $stmt->execute([$meal_id, $user_id]);
        } else {
            $stmt = $pdo->prepare("SELECT * FROM meals WHERE id = ?");
            $stmt->execute([$meal_id]);
        }
        
        $meal = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        die("Error fetching meal: " . $e->getMessage());
    }
    
    if (!$meal) {
        die("Meal not found or you don't have permission to access it.");
    }
    
    // ALWAYS use the custom people_count from the Stock Issue Sheets page form
    $people_count = $custom_people_count ? intval($custom_people_count) : ($meal['people_count'] ?? 1);
    $meal_name = $meal['name'] ?? $meal['meal_name'] ?? 'Unnamed Meal';
    
    // Log the calculation details
    error_log("Generating issue sheet for meal '$meal_name' with $people_count people");
    
    // Get all ingredients from all costings used in this meal
    $ingredients = [];
    $totalIngredients = 0;
    
    try {
        // First, get all costing sheets linked to this meal
        $costingStmt = $pdo->prepare("
            SELECT mc.costing_sheet_id, mc.servings, rc.recipe_name, rc.portions
            FROM meal_costings mc 
            JOIN recipe_costings rc ON mc.costing_sheet_id = rc.id 
            WHERE mc.meal_id = ?
        ");
        $costingStmt->execute([$meal_id]);
        $mealCostings = $costingStmt->fetchAll(PDO::FETCH_ASSOC);
        
        error_log("Found " . count($mealCostings) . " costing sheets for meal $meal_id");
        
        foreach ($mealCostings as $mealCosting) {
            $costing_id = $mealCosting['costing_sheet_id'];
            $servings = $mealCosting['servings'];
            $costing_name = $mealCosting['recipe_name'];
            $portions = $mealCosting['portions'] ?: 1;
            
            error_log("Processing costing $costing_id: $servings servings, $portions portions");
            
            // Get ingredients for this costing sheet FROM recipe_ingredients
            try {
                $ingredientStmt = $pdo->prepare("
                    SELECT ri.recipe_id, ri.ingredient_id, ri.quantity, 
                           i.name as ingredient_name, 
                           COALESCE(i.unit, 'each') as unit
                    FROM recipe_ingredients ri 
                    JOIN ingredients i ON ri.ingredient_id = i.id 
                    WHERE ri.recipe_id = ? 
                    ORDER BY i.name
                ");
                $ingredientStmt->execute([$costing_id]);
                $costingIngredients = $ingredientStmt->fetchAll(PDO::FETCH_ASSOC);
                
                error_log("Found " . count($costingIngredients) . " ingredients for costing $costing_id");
                
                foreach ($costingIngredients as $ingredient) {
                    $ingredient_id = $ingredient['ingredient_id'];
                    $ingredient_name = $ingredient['ingredient_name'];
                    $unit = $ingredient['unit'];
                    $base_quantity = floatval($ingredient['quantity']) ?: 1;
                    
                    // Calculate total quantity for this ingredient
                    // Formula: (base quantity / portions) * servings * people_count
                    $quantity_per_portion = $portions > 0 ? ($base_quantity / $portions) : $base_quantity;
                    $total_quantity = $quantity_per_portion * $servings * $people_count;
                    
                    // Round to reasonable precision
                    $total_quantity = round($total_quantity, 3);
                    
                    error_log("Ingredient: $ingredient_name - Base: $base_quantity, Per portion: $quantity_per_portion, Total: $total_quantity");
                    
                    // Check if ingredient already exists in the list
                    $existingIndex = -1;
                    foreach ($ingredients as $index => $existingIngredient) {
                        if ($existingIngredient['ingredient_name'] === $ingredient_name && 
                            $existingIngredient['unit'] === $unit) {
                            $existingIndex = $index;
                            break;
                        }
                    }
                    
                    if ($existingIndex !== -1) {
                        // Add to existing ingredient
                        $ingredients[$existingIndex]['total_quantity'] += $total_quantity;
                    } else {
                        // Add new ingredient
                        $ingredients[] = [
                            'ingredient_id' => $ingredient_id,
                            'ingredient_name' => $ingredient_name,
                            'unit' => $unit,
                            'total_quantity' => $total_quantity,
                            'source_costing' => $costing_name
                        ];
                        $totalIngredients++;
                    }
                }
                
            } catch (Exception $e) {
                error_log("ERROR getting ingredients for costing $costing_id: " . $e->getMessage());
                continue;
            }
        }
        
    } catch (Exception $e) {
        error_log("ERROR getting meal costings: " . $e->getMessage());
    }
    
    error_log("Final ingredient count: " . count($ingredients));
    
    // Generate PDF
    require_once(__DIR__ . '/../includes/fpdf/fpdf.php');
    
    class PDF extends FPDF {
        function Header() {
            // Add header image
            $headerPath = __DIR__ . '/../assets/uploads/header3.png';
            if (file_exists($headerPath)) {
                // Calculate image dimensions to fit the PDF width while maintaining aspect ratio
                $pdfWidth = $this->GetPageWidth() - 20; // 10px margin on each side
                $imgWidth = $pdfWidth;
                $imgInfo = getimagesize($headerPath);
                if ($imgInfo) {
                    $imgHeight = ($imgInfo[1] * $imgWidth) / $imgInfo[0];
                    
                    // Add the image at the top
                    $this->Image($headerPath, 10, 10, $imgWidth, $imgHeight);
                    
                    // Set Y position below the image
                    $this->SetY(10 + $imgHeight + 5);
                } else {
                    $this->SetY(20);
                }
            } else {
                // If image not found, start at normal position
                $this->SetY(20);
            }
        }
        
        function Footer() {
            $this->SetY(-15);
            $this->SetFont('Arial', 'I', 8);
            $this->Cell(0, 10, 'Page ' . $this->PageNo(), 0, 0, 'C');
        }
    }
    
    $pdf = new PDF();
    $pdf->AddPage();
    
    // Meal Information - Start content below the image
    $pdf->SetFont('Arial', 'B', 12);
    $pdf->Cell(0, 8, 'Meal Information', 0, 1);
    $pdf->SetFont('Arial', '', 10);
    
    $pdf->Cell(40, 6, 'Meal Name:', 0, 0);
    $pdf->Cell(0, 6, $meal_name, 0, 1);
    
    $pdf->Cell(40, 6, 'People Count:', 0, 0);
    $pdf->Cell(0, 6, $people_count, 0, 1);
    
    if (!empty($meal['description'])) {
        $pdf->Cell(40, 6, 'Description:', 0, 0);
        $pdf->MultiCell(0, 6, $meal['description'], 0, 1);
    }
    
    $pdf->Cell(40, 6, 'Ingredients Found:', 0, 0);
    $pdf->Cell(0, 6, count($ingredients) . ' items', 0, 1);
    
    $pdf->Ln(5);
    
    // Ingredients Table Header
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->Cell(80, 8, 'Ingredient', 1, 0, 'C');
    $pdf->Cell(30, 8, 'Unit', 1, 0, 'C');
    $pdf->Cell(40, 8, 'Required Qty', 1, 0, 'C');
    $pdf->Cell(40, 8, 'Issued Qty', 1, 1, 'C');
    
    // Ingredients Table Content
    $pdf->SetFont('Arial', '', 9);
    if (!empty($ingredients)) {
        foreach ($ingredients as $ingredient) {
            $ingredientName = $ingredient['ingredient_name'] ?? 'Unknown Ingredient';
            
            if (strlen($ingredientName) > 35) {
                $ingredientName = substr($ingredientName, 0, 32) . '...';
            }
            
            $pdf->Cell(80, 8, $ingredientName, 1, 0);
            $pdf->Cell(30, 8, $ingredient['unit'] ?? 'each', 1, 0, 'C');
            $pdf->Cell(40, 8, number_format($ingredient['total_quantity'], 3), 1, 0, 'C');
            $pdf->Cell(40, 8, '', 1, 1, 'C');
        }
        
        // Add total row
        $pdf->SetFont('Arial', 'B', 9);
        $pdf->Cell(80, 8, 'TOTAL', 1, 0);
        $pdf->Cell(30, 8, '', 1, 0, 'C');
        $pdf->Cell(40, 8, count($ingredients) . ' items', 1, 0, 'C');
        $pdf->Cell(40, 8, '', 1, 1, 'C');
        
    } else {
        $pdf->Cell(190, 8, 'No ingredients found for this meal', 1, 1, 'C');
    }
    
    // Additional notes section
    $pdf->Ln(10);
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->Cell(0, 8, 'Kitchen Notes:', 0, 1);
    $pdf->SetFont('Arial', '', 9);
    
    for ($i = 0; $i < 4; $i++) {
        $pdf->Cell(0, 6, '________________________________________________________________________________', 0, 1);
    }
    
    // Footer information
    $pdf->Ln(10);
    $pdf->SetFont('Arial', '', 9);
    $pdf->Cell(95, 6, 'Issued By: _________________________', 0, 0);
    $pdf->Cell(95, 6, 'Received By: _________________________', 0, 1);
    
    $pdf->Cell(95, 6, 'Date: _________________________', 0, 0);
    $pdf->Cell(95, 6, 'Time: _________________________', 0, 1);
    
    // Generate filename and save download record
    $filename = 'stock_issue_' . preg_replace('/[^a-zA-Z0-9]/', '_', $meal_name) . '_' . $people_count . '_people.pdf';
    
    try {
        $insertStmt = $pdo->prepare("
            INSERT INTO issue_sheet_downloads 
            (meal_id, meal_name, people_count, file_name, downloaded_by) 
            VALUES (?, ?, ?, ?, ?)
        ");
        $insertStmt->execute([
            $meal_id,
            $meal_name,
            $people_count,
            $filename,
            $user_id
        ]);
        error_log("Download record saved for $people_count people");
    } catch (Exception $e) {
        error_log("Error saving download record: " . $e->getMessage());
    }
    
    // Output PDF
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    echo $pdf->Output('S');
    exit;
}

// Check for includes
$hasNavbar = is_file(__DIR__ . '/../includes/navbar.php');
$hasFooter = is_file(__DIR__ . '/../includes/footer.php');
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stock Issue Sheets - Smart Serve Pro</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background: #f8f9fa; padding-top: 0; }
        .card { border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); border: none; }
        .btn-custom { background-color: #8B0000; color: white; border: none; }
        .btn-custom:hover { background-color: #600000; color: white; }
        .meal-card { transition: transform 0.2s ease; }
        .meal-card:hover { transform: translateY(-2px); }
        .people-badge { background-color: #8B0000; color: white; padding: 4px 8px; border-radius: 4px; font-size: 0.8rem; }
        .costing-badge { background-color: #28a745; color: white; padding: 2px 6px; border-radius: 3px; font-size: 0.7rem; }
        .download-item { 
            border-left: 4px solid #28a745; 
            padding: 12px 15px; 
            margin-bottom: 10px; 
            background: white; 
            border-radius: 5px;
            transition: all 0.2s ease;
        }
        .download-item:hover {
            background: #f8f9fa;
            transform: translateX(5px);
        }
        .download-actions {
            opacity: 0;
            transition: opacity 0.2s ease;
        }
        .download-item:hover .download-actions {
            opacity: 1;
        }
        .btn-download {
            background-color: #28a745;
            color: white;
            border: none;
        }
        .btn-download:hover {
            background-color: #218838;
            color: white;
        }
        .btn-delete {
            background-color: #dc3545;
            color: white;
            border: none;
        }
        .btn-delete:hover {
            background-color: #c82333;
            color: white;
        }
        .generating-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        .generating-spinner {
            background: white;
            padding: 30px;
            border-radius: 10px;
            text-align: center;
        }
    </style>
</head>
<body>
    <?php if ($hasNavbar) include __DIR__ . '/../includes/navbar.php'; ?>

    <main class="rcp-main">
        <div class="container mt-4">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1>Stock Issue Sheets</h1>
            </div>

            <?php if (isset($_GET['deleted']) && $_GET['deleted'] === 'success'): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <i class="fas fa-check-circle"></i> Download record deleted successfully.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if (isset($_GET['refreshed']) && $_GET['refreshed'] === 'true'): ?>
                <div class="alert alert-info alert-dismissible fade show">
                    <i class="fas fa-sync-alt"></i> Page refreshed with latest issue sheets.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <div class="row">
                <div class="col-lg-8">
                    <div class="row">
                        <?php if (!empty($meals)): ?>
                            <?php foreach ($meals as $meal): ?>
                                <div class="col-md-6 mb-4">
                                    <div class="card meal-card h-100">
                                        <div class="card-body">
                                            <h5 class="card-title"><?= htmlspecialchars($meal['name'] ?? $meal['meal_name'] ?? 'Unnamed Meal') ?></h5>
                                            <p class="card-text text-muted"><?= htmlspecialchars($meal['description'] ?? 'No description') ?></p>
                                            <div class="mb-2">
                                                <span class="people-badge">
                                                    <i class="fas fa-users"></i> 
                                                    Standard: <?= $meal['people_count'] ?? 1 ?> people
                                                </span>
                                                <?php if (($meal['costing_count'] ?? 0) > 0): ?>
                                                    <span class="costing-badge ms-2">
                                                        <i class="fas fa-calculator"></i> 
                                                        <?= $meal['costing_count'] ?> costing(s)
                                                    </span>
                                                <?php endif; ?>
                                            </div>
                                            <small class="text-muted">
                                                <i class="fas fa-calendar"></i> 
                                                Created: <?= date('M j, Y', strtotime($meal['created_at'])) ?>
                                            </small>
                                        </div>
                                        <div class="card-footer bg-white border-0">
                                            <form method="post" class="d-flex gap-2 align-items-end" id="mealForm-<?= $meal['id'] ?>" target="_blank" onsubmit="showGeneratingSpinner()">
                                                <input type="hidden" name="meal_id" value="<?= $meal['id'] ?>">
                                                <div class="flex-grow-1">
                                                    <label class="form-label small mb-1">Custom People Count</label>
                                                    <input type="number" name="people_count" 
                                                           value="<?= $meal['people_count'] ?? 1 ?>" 
                                                           min="1" max="1000"
                                                           class="form-control form-control-sm"
                                                           required>
                                                </div>
                                                <button type="submit" name="generate_issue_sheet" class="btn btn-custom btn-sm generate-btn">
                                                    <i class="fas fa-file-pdf"></i> Generate & Download
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="col-12">
                                <div class="card text-center py-5">
                                    <div class="card-body">
                                        <i class="fas fa-utensils fa-3x text-muted mb-3"></i>
                                        <h5 class="card-title">No Meals Found</h5>
                                        <p class="card-text text-muted">You haven't created any meals yet.</p>
                                        <a href="meals.php" class="btn btn-custom">Create Your First Meal</a>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="col-lg-4">
                    <div class="card">
                        <div class="card-header bg-white d-flex justify-content-between align-items-center">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-history text-primary"></i> Recent Issue Sheets
                            </h5>
                            <span class="badge bg-primary"><?= count($recentDownloads) ?></span>
                        </div>
                        <div class="card-body">
                            <?php if (!empty($recentDownloads)): ?>
                                <?php foreach ($recentDownloads as $download): ?>
                                    <div class="download-item position-relative">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div class="flex-grow-1">
                                                <strong class="d-block mb-1">
                                                    <i class="fas fa-file-pdf text-danger me-1"></i>
                                                    <?= htmlspecialchars($download['actual_meal_name'] ?? $download['meal_name'] ?? 'Unknown Meal') ?>
                                                </strong>
                                                <small class="text-muted d-block">
                                                    <i class="fas fa-users me-1"></i>
                                                    <?= $download['people_count'] ?> people
                                                </small>
                                                <small class="text-muted d-block">
                                                    <i class="fas fa-calendar me-1"></i>
                                                    <?= date('M j, g:i A', strtotime($download['created_at'])) ?>
                                                </small>
                                                <small class="text-muted d-block">
                                                    <i class="fas fa-file me-1"></i>
                                                    <?= htmlspecialchars($download['file_name']) ?>
                                                </small>
                                            </div>
                                            <div class="download-actions ms-3">
                                                <form method="post" class="d-inline" target="_blank">
                                                    <input type="hidden" name="meal_id" value="<?= $download['meal_id'] ?>">
                                                    <input type="hidden" name="people_count" value="<?= $download['people_count'] ?>">
                                                    <button type="submit" name="generate_issue_sheet" 
                                                            class="btn btn-download btn-sm me-1"
                                                            title="Download this issue sheet">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </form>
                                                <form method="post" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this download record?');">
                                                    <input type="hidden" name="download_id" value="<?= $download['id'] ?>">
                                                    <button type="submit" name="delete_download" 
                                                            class="btn btn-delete btn-sm"
                                                            title="Delete this record">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="text-center text-muted py-4">
                                    <i class="fas fa-file-pdf fa-3x mb-3"></i>
                                    <p>No issue sheets generated yet</p>
                                    <small>Generate your first issue sheet to see it here</small>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Quick Stats -->
                    <div class="card mt-4">
                        <div class="card-header bg-white">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-chart-bar text-success"></i> Quick Stats
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row text-center">
                                <div class="col-6">
                                    <div class="metric-value text-primary"><?= count($meals) ?></div>
                                    <small class="text-muted">Total Meals</small>
                                </div>
                                <div class="col-6">
                                    <div class="metric-value text-success"><?= count($recentDownloads) ?></div>
                                    <small class="text-muted">Issue Sheets</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- Generating Spinner Overlay -->
    <div id="generatingOverlay" class="generating-overlay" style="display: none;">
        <div class="generating-spinner">
            <div class="spinner-border text-primary mb-3" role="status">
                <span class="visually-hidden">Generating PDF...</span>
            </div>
            <h5>Generating Issue Sheet...</h5>
            <p class="text-muted">Your PDF will download shortly. The page will refresh automatically.</p>
        </div>
    </div>

    <?php if ($hasFooter) include __DIR__ . '/../includes/footer.php'; ?>

    <script>
        function showGeneratingSpinner() {
            document.getElementById('generatingOverlay').style.display = 'flex';
            
            // Set a timeout to refresh the page after PDF generation
            setTimeout(function() {
                window.location.reload();
            }, 3000); // Refresh after 3 seconds
        }

        document.addEventListener('DOMContentLoaded', function() {
            // Add confirmation for delete actions
            const deleteForms = document.querySelectorAll('form[onsubmit]');
            deleteForms.forEach(form => {
                form.addEventListener('submit', function(e) {
                    if (!confirm('Are you sure you want to create this Issue Sheet?')) {
                        e.preventDefault();
                    }
                });
            });

            // Auto-hide alerts after 5 seconds
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(alert => {
                setTimeout(() => {
                    if (alert.parentNode) {
                        alert.remove();
                    }
                }, 5000);
            });

            // Check if we should show the generating spinner (for page refreshes)
            if (window.location.search.includes('refreshed=true')) {
                setTimeout(function() {
                    window.location.href = window.location.pathname;
                }, 1000);
            }
        });
    </script>
</body>
</html>