<?php
/**
 * Food Production Schedule 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);
    
    // 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 generation and saving
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['generate_pdf'])) {
            $pdf_data = generatePDF($pdo, $user, true);
            $schedule_id = saveScheduleToDatabase($pdo, $user, $_POST, $pdf_data);
            if ($schedule_id) {
                $_SESSION['last_schedule_id'] = $schedule_id;
                header("Location: schedules.php?success=1&schedule_id=" . $schedule_id);
                exit;
            }
        } elseif (isset($_POST['generate_excel'])) {
            generateExcel($pdo, $user);
            exit;
        } elseif (isset($_POST['update_schedule'])) {
            updateScheduleInDatabase($pdo, $_POST);
            header("Location: schedules.php?success=2");
            exit;
        } elseif (isset($_POST['delete_schedule'])) {
            deleteScheduleFromDatabase($pdo, $_POST['schedule_id']);
            header("Location: schedules.php?success=3");
            exit;
        }
    }
    
    // Fetch saved schedules
    $savedSchedules = getSavedSchedules($pdo, $user['user_id']);
    
    // Fetch recipes created by the logged-in user only
    $search = $_GET['search'] ?? '';
    $sql = "SELECT rc.id, rc.recipe_name 
            FROM recipe_costings rc 
            WHERE rc.created_by = ?";
    $params = [$user['user_id']];

    if (!empty($search)) {
        $sql .= " AND (rc.recipe_name LIKE ?)";
        $params[] = "%$search%";
    }

    $sql .= " ORDER BY rc.recipe_name";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $allRecipes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Throwable $t) {
    die("Error: " . $t->getMessage());
}

// Function to save schedule to database
function saveScheduleToDatabase($pdo, $user, $postData, $pdf_data) {
    $schedule_name = $postData['pdf_filename'] ?? 'food_production_schedule_' . date('Y-m-d');
    $unit_name = $postData['unit_name'] ?? '';
    $selected_meals = isset($postData['meals']) ? json_encode($postData['meals']) : '[]';
    
    $sql = "INSERT INTO production_schedules (user_id, schedule_name, unit_name, selected_meals, pdf_data, created_at) 
            VALUES (?, ?, ?, ?, ?, NOW())";
    
    $stmt = $pdo->prepare($sql);
    $result = $stmt->execute([$user['user_id'], $schedule_name, $unit_name, $selected_meals, $pdf_data]);
    
    return $result ? $pdo->lastInsertId() : false;
}

// Function to update schedule in database
function updateScheduleInDatabase($pdo, $postData) {
    $schedule_id = $postData['schedule_id'] ?? 0;
    $schedule_name = $postData['schedule_name'] ?? '';
    $unit_name = $postData['unit_name'] ?? '';
    
    $sql = "UPDATE production_schedules SET schedule_name = ?, unit_name = ?, updated_at = NOW() WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    return $stmt->execute([$schedule_name, $unit_name, $schedule_id]);
}

// Function to delete schedule from database
function deleteScheduleFromDatabase($pdo, $schedule_id) {
    $sql = "DELETE FROM production_schedules WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    return $stmt->execute([$schedule_id]);
}

// Function to get saved schedules
function getSavedSchedules($pdo, $user_id) {
    $sql = "SELECT id, schedule_name, unit_name, created_at FROM production_schedules 
            WHERE user_id = ? ORDER BY created_at DESC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$user_id]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Function to generate Excel file - UPDATED FOR TABLE FORMAT
function generateExcel($pdo, $user) {
    $selectedMeals = isset($_POST['meals']) ? $_POST['meals'] : [];
    $unit_name = $_POST['unit_name'] ?? '';
    
    if (empty($selectedMeals)) {
        die("No meals selected.");
    }
    
    // Get recipe data with preparation steps
    $placeholders = str_repeat('?,', count($selectedMeals) - 1) . '?';
    $sql = "SELECT rc.id, rc.recipe_name 
            FROM recipe_costings rc 
            WHERE rc.id IN ($placeholders) AND rc.created_by = ?";
    $stmt = $pdo->prepare($sql);
    $params = array_merge($selectedMeals, [$user['user_id']]);
    $stmt->execute($params);
    $recipes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $filename = "food_production_schedule_" . date('Y-m-d') . ".csv";
    
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    
    $output = fopen('php://output', 'w');
    
    // Add BOM for UTF-8
    fputs($output, "\xEF\xBB\xBF");
    
    // HEADER ROWS
    fputcsv($output, ['FOOD PRODUCTION SCHEDULE', '', '', '', '', '', '']);
    fputcsv($output, ['', '', '', '', '', '', '']);
    fputcsv($output, ['Date:', date('d/m/Y'), '', 'Unit:', $unit_name, '', '']);
    fputcsv($output, ['', '', '', '', '', '', '']);
    fputcsv($output, ['Date:', 'Week:', 'Day:', 'Meal:', 'Breakfast', 'Lunch', 'Dinner', 'Meal Count:']);
    fputcsv($output, ['', '', '', '', '', '', '', '']);
    
    // COLUMN HEADERS - UPDATED FOR TABLE FORMAT
    fputcsv($output, [
        'Employee', 
        'Menu Item', 
        'Quantity (Portions)', 
        'Quantity (kg/h)', 
        'Recipe Item',
        'Instruction',
        'Time Allocation',
        'Time Schedule', 
        'Comments (Cleaning / Other)'
    ]);
    
    // RECIPE DATA
    foreach ($recipes as $recipe) {
        // Get preparation steps for this recipe
        $stepSql = "SELECT item, instruction, time_allocation 
                   FROM recipe_preparation_steps 
                   WHERE recipe_id = ? 
                   ORDER BY id";
        $stepStmt = $pdo->prepare($stepSql);
        $stepStmt->execute([$recipe['id']]);
        $steps = $stepStmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (empty($steps)) {
            // If no steps, add one row with recipe name
            fputcsv($output, [
                '', // Employee
                $recipe['recipe_name'] ?? '',
                '', // Quantity (Portions)
                '', // Quantity (kg/h)
                '', // Recipe Item
                '', // Instruction
                '', // Time Allocation
                '', // Time Schedule
                ''  // Comments
            ]);
        } else {
            // Add a row for each preparation step
            foreach ($steps as $index => $step) {
                $menuItem = ($index === 0) ? $recipe['recipe_name'] : '';
                
                fputcsv($output, [
                    '', // Employee
                    $menuItem,
                    '', // Quantity (Portions)
                    '', // Quantity (kg/h)
                    $step['item'] ?? '',
                    $step['instruction'] ?? '',
                    $step['time_allocation'] ?? '',
                    '', // Time Schedule
                    ''  // Comments
                ]);
            }
        }
    }
    
    // FOOTER
    fputcsv($output, ['', '', '', '', '', '', '', '', '']);
    fputcsv($output, ['Generated by: Serve Smart Pro - ' . ($user['user_full_name'] ?? $user['user_email']) . ' - Unit: ' . $unit_name, '', '', '', '', '', '', '', '']);
    
    fclose($output);
    exit;
}

// Function to generate PDF - UPDATED FOR TABLE FORMAT
function generatePDF($pdo, $user, $return_data = false) {
    $selectedMeals = isset($_POST['meals']) ? $_POST['meals'] : [];
    $pdf_filename = $_POST['pdf_filename'] ?? 'food_production_schedule';
    $unit_name = $_POST['unit_name'] ?? '';
    
    if (empty($selectedMeals)) {
        die("No meals selected.");
    }
    
    // Get recipe data
    $placeholders = str_repeat('?,', count($selectedMeals) - 1) . '?';
    $sql = "SELECT rc.id, rc.recipe_name 
            FROM recipe_costings rc 
            WHERE rc.id IN ($placeholders) AND rc.created_by = ?";
    $stmt = $pdo->prepare($sql);
    $params = array_merge($selectedMeals, [$user['user_id']]);
    $stmt->execute($params);
    $recipes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // For each recipe, get preparation steps
    $recipesWithSteps = [];
    foreach ($recipes as $recipe) {
        $stepSql = "SELECT item, instruction, time_allocation 
                   FROM recipe_preparation_steps 
                   WHERE recipe_id = ? 
                   ORDER BY id";
        $stepStmt = $pdo->prepare($stepSql);
        $stepStmt->execute([$recipe['id']]);
        $steps = $stepStmt->fetchAll(PDO::FETCH_ASSOC);
        
        $recipesWithSteps[] = [
            'recipe_name' => $recipe['recipe_name'],
            'steps' => $steps
        ];
    }
    
    // Create PDF content
    $pdf_content = generatePDFContent($recipesWithSteps, $user, $unit_name);
    
    if ($return_data) {
        return $pdf_content;
    }
    
    // Clean filename
    $pdf_filename = preg_replace('/[^a-zA-Z0-9_-]/', '_', $pdf_filename);
    if (empty($pdf_filename)) {
        $pdf_filename = 'food_production_schedule';
    }
    
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . $pdf_filename . '.pdf"');
    echo $pdf_content;
    exit;
}

// PDF GENERATION WITH HEADER IMAGE - UPDATED FOR TABLE FORMAT
function generatePDFContent($recipes, $user, $unit_name) {
    require_once(__DIR__ . '/../includes/fpdf/fpdf.php');
    
    class PDF extends FPDF {
        var $unit_name;
        var $user_name;
        var $current_recipe_number = 0;
        
        function Header() {
            // Header image - try multiple possible locations
            $header_image_path = null;
            $possible_paths = [
                __DIR__ . '/../assets/uploads/header.png',
                __DIR__ . '/../../assets/uploads/header.png',
                __DIR__ . '/../../../assets/uploads/header.png',
                'assets/uploads/header.png',
                '../assets/uploads/header.png',
                '../../assets/uploads/header.png'
            ];
            
            foreach ($possible_paths as $path) {
                if (file_exists($path)) {
                    $header_image_path = $path;
                    break;
                }
            }
            
            // Add header image if found
            if ($header_image_path) {
                $this->Image($header_image_path, 10, 8, 190);
                $this->SetY(40);
            } else {
                $this->SetY(20);
            }
            
            // Title only - NO DATE BELOW TITLE
            $this->SetFont('Arial', 'B', 16);
            $this->Cell(0, 10, 'FOOD PRODUCTION SCHEDULE', 0, 1, 'C');
            $this->Ln(5);
        }
        
        function Footer() {
            $this->SetY(-15);
            $this->SetFont('Arial', 'I', 8);
            $footer_text = 'Generated by: Serve Smart Pro - ' . $this->user_name . ' - Unit: ' . $this->unit_name;
            $this->Cell(0, 10, $footer_text, 0, 0, 'C');
        }
        
        function addHeaderInfo() {
            // Unit name at top right
            $this->SetFont('Arial', 'B', 12);
            $this->Cell(0, 8, 'Unit: ' . $this->unit_name, 0, 1, 'R');
            $this->Ln(5);
            
            // Main header row
            $this->SetFont('Arial', 'B', 11);
            $this->Cell(25, 8, 'Date:', 0, 0);
            $this->SetFont('Arial', '', 11);
            $this->Cell(25, 8, '____________', 0, 0);
            
            $this->SetFont('Arial', 'B', 11);
            $this->Cell(25, 8, 'Week:', 0, 0);
            $this->SetFont('Arial', '', 11);
            $this->Cell(25, 8, '____________', 0, 0);
            
            $this->SetFont('Arial', 'B', 11);
            $this->Cell(20, 8, 'Day:', 0, 0);
            $this->SetFont('Arial', '', 11);
            $this->Cell(25, 8, '____________', 0, 0);
            
            $this->SetFont('Arial', 'B', 11);
            $this->Cell(25, 8, 'Meal:', 0, 0);
            $this->SetFont('Arial', '', 11);
            $this->Cell(40, 8, 'Breakfast  Lunch  Dinner', 0, 0);
            
            $this->SetFont('Arial', 'B', 11);
            $this->Cell(30, 8, 'Meal Count:', 0, 0);
            $this->SetFont('Arial', '', 11);
            $this->Cell(0, 8, '____________', 0, 1);
            
            $this->Ln(8);
        }
        
        function addRecipeBlock($recipe) {
            $this->current_recipe_number++;
            
            // Check if we need a new page
            if ($this->GetY() > 250) {
                $this->AddPage();
                $this->addHeaderInfo();
            }
            
            // RED BLOCK HEADER
            $this->SetFillColor(220, 53, 69);
            $this->SetTextColor(255, 255, 255);
            $this->SetFont('Arial', 'B', 12);
            $this->Cell(0, 10, 'Meal ' . $this->current_recipe_number . ': ' . $recipe['recipe_name'], 1, 1, 'L', true);
            
            // Reset colors for content
            $this->SetFillColor(255, 255, 255);
            $this->SetTextColor(0, 0, 0);
            
            // Table header for preparation steps
            $this->SetFont('Arial', 'B', 10);
            $this->Cell(30, 8, 'Recipe Item', 1, 0, 'L', true);
            $this->Cell(100, 8, 'Instruction', 1, 0, 'L', true);
            $this->Cell(30, 8, 'Time Allocation', 1, 1, 'L', true);
            
            // Preparation steps rows
            $this->SetFont('Arial', '', 9);
            if (!empty($recipe['steps'])) {
                foreach ($recipe['steps'] as $step) {
                    // Check if we need a new page
                    if ($this->GetY() > 270) {
                        $this->AddPage();
                        $this->addHeaderInfo();
                        // Redraw table header
                        $this->SetFont('Arial', 'B', 10);
                        $this->Cell(30, 8, 'Recipe Item', 1, 0, 'L', true);
                        $this->Cell(100, 8, 'Instruction', 1, 0, 'L', true);
                        $this->Cell(30, 8, 'Time Allocation', 1, 1, 'L', true);
                        $this->SetFont('Arial', '', 9);
                    }
                    
                    $this->Cell(30, 8, substr($step['item'] ?? '', 0, 20), 1, 0, 'L');
                    $this->Cell(100, 8, substr($step['instruction'] ?? '', 0, 50), 1, 0, 'L');
                    $this->Cell(30, 8, $step['time_allocation'] ?? '', 1, 1, 'L');
                }
            } else {
                $this->Cell(160, 8, 'No preparation steps available', 1, 1, 'C');
            }
            
            // Manual completion fields
            $this->Ln(5);
            
            // First row of fields
            $this->SetFont('Arial', 'B', 10);
            $this->Cell(40, 8, 'Employee:', 1, 0, 'L');
            $this->SetFont('Arial', '', 10);
            $this->Cell(50, 8, '', 1, 0, 'L');
            
            $this->SetFont('Arial', 'B', 10);
            $this->Cell(50, 8, 'Quantity (Portions):', 1, 0, 'L');
            $this->SetFont('Arial', '', 10);
            $this->Cell(0, 8, '', 1, 1, 'L');
            
            // Second row of fields
            $this->SetFont('Arial', 'B', 10);
            $this->Cell(40, 8, 'Quantity (kg/h):', 1, 0, 'L');
            $this->SetFont('Arial', '', 10);
            $this->Cell(50, 8, '', 1, 0, 'L');
            
            $this->SetFont('Arial', 'B', 10);
            $this->Cell(50, 8, 'Time Schedule:', 1, 0, 'L');
            $this->SetFont('Arial', '', 10);
            $this->Cell(0, 8, '', 1, 1, 'L');
            
            // Comments section
            $this->SetFont('Arial', 'B', 10);
            $this->Cell(0, 8, 'Comments (Cleaning / Other):', 1, 1, 'L');
            $this->SetFont('Arial', '', 10);
            $this->MultiCell(0, 20, '', 1, 'L');
            
            $this->Ln(8);
        }
    }
    
    $pdf = new PDF('P', 'mm', 'A4');
    $pdf->unit_name = $unit_name ?: 'Not specified';
    $pdf->user_name = $user['user_full_name'] ?? $user['user_email'];
    $pdf->AddPage();
    
    // Add header info
    $pdf->addHeaderInfo();
    
    // Add recipe blocks
    foreach ($recipes as $recipe) {
        $pdf->addRecipeBlock($recipe);
    }
    
    return $pdf->Output('S');
}

// Function to download saved PDF
function downloadSchedulePDF($pdo, $schedule_id, $user_id) {
    $sql = "SELECT pdf_data, schedule_name FROM production_schedules WHERE id = ? AND user_id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$schedule_id, $user_id]);
    $schedule = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($schedule) {
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $schedule['schedule_name'] . '.pdf"');
        echo $schedule['pdf_data'];
        exit;
    }
}

// Handle PDF download
if (isset($_GET['download_schedule'])) {
    downloadSchedulePDF($pdo, $_GET['download_schedule'], $user['user_id']);
}

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

// Check for success messages
$success_message = '';
if (isset($_GET['success'])) {
    switch ($_GET['success']) {
        case '1':
            $success_message = 'Schedule generated and saved successfully!';
            break;
        case '2':
            $success_message = 'Schedule updated successfully!';
            break;
        case '3':
            $success_message = 'Schedule deleted successfully!';
            break;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Serve Smart Pro - Food Production Schedule</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;
        }
        .btn-outline-custom {
            border-color: #8B0000;
            color: #8B0000;
        }
        .btn-outline-custom:hover {
            background-color: #8B0000;
            color: white;
        }
        .btn-excel {
            background-color: #217346;
            color: white;
            border: none;
        }
        .btn-excel:hover {
            background-color: #1a5c38;
            color: white;
        }
        .recipe-list {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 15px;
            background: white;
        }
        .recipe-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            transition: background-color 0.2s;
        }
        .recipe-item:hover {
            background-color: #f8f9fa;
        }
        .recipe-item:last-child {
            border-bottom: none;
        }
        .instructions {
            background-color: #f8f9fa;
            border-left: 4px solid #8B0000;
            padding: 15px;
            margin-bottom: 20px;
        }
        .search-box {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .selected-count {
            background-color: #8B0000;
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.9em;
            margin-left: 10px;
        }
        .filename-input {
            max-width: 300px;
        }
        .unit-input {
            max-width: 250px;
        }
        .user-recipes-badge {
            background-color: #198754;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.8em;
            margin-left: 10px;
        }
        .saved-schedules {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-top: 30px;
        }
        .schedule-item {
            padding: 15px;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            margin-bottom: 15px;
            background: #f8f9fa;
        }
        .schedule-item:hover {
            background: #e9ecef;
        }
        .schedule-actions {
            display: flex;
            gap: 10px;
            align-items: center;
        }
        .edit-form {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-top: 10px;
            border-left: 4px solid #8B0000;
        }
        .export-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        .preview-section {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            border-left: 4px solid #217346;
        }
        .pdf-block-preview {
            border: 1px solid #dc3545;
            border-radius: 5px;
            margin-bottom: 15px;
            overflow: hidden;
        }
        .pdf-block-header {
            background-color: #dc3545;
            color: white;
            padding: 8px 12px;
            font-weight: bold;
        }
        .pdf-block-content {
            padding: 12px;
            background-color: white;
        }
        .pdf-field-row {
            display: flex;
            margin-bottom: 8px;
        }
        .pdf-field-label {
            font-weight: bold;
            width: 120px;
        }
        .pdf-field-value {
            flex: 1;
            border-bottom: 1px solid #dee2e6;
            min-height: 20px;
        }
        .header-preview {
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .header-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        .header-fields {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }
        .header-field {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .header-label {
            font-weight: bold;
            font-size: 14px;
        }
        .header-underline {
            border-bottom: 1px solid #000;
            min-width: 80px;
            height: 20px;
        }
        .image-preview {
            background: #e9ecef;
            border: 2px dashed #dee2e6;
            border-radius: 5px;
            padding: 20px;
            text-align: center;
            margin-bottom: 15px;
        }
        .image-preview img {
            max-width: 100%;
            max-height: 100px;
        }
        .table-preview {
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 15px;
            margin-top: 15px;
        }
        .table-preview table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        .table-preview th {
            background: #8B0000;
            color: white;
            padding: 8px 12px;
            text-align: left;
            font-weight: 600;
            border: 1px solid #dee2e6;
        }
        .table-preview td {
            padding: 8px 12px;
            border: 1px solid #dee2e6;
        }
        .table-preview tr:nth-child(even) {
            background: #f8f9fa;
        }
    </style>
</head>
<body>
    <?php if ($hasNavbar) include __DIR__ . '/../includes/navbar.php'; ?>

    <main class="rcp-main">
        <div class="container mt-4">
            <!-- Success Message -->
            <?php if ($success_message): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle"></i> <?= $success_message ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1>Food Production Schedule</h1>
                <span class="text-muted">Welcome, <?= htmlspecialchars($user['user_full_name'] ?? $user['user_email']) ?></span>
            </div>

            <div class="instructions">
                <h5><i class="fas fa-info-circle"></i> Instructions</h5>
                <p class="mb-0">Select one or more meals from <strong>your recipes</strong> below. The system will generate a clean, printable schedule with header image, colored blocks for each recipe and proper Excel export. <strong>Now includes tabular preparation steps!</strong></p>
            </div>

            <!-- Search Section -->
            <div class="search-box">
                <form method="get" class="row g-3 align-items-end">
                    <div class="col-md-8">
                        <label class="form-label fw-bold">Search Your Recipes:</label>
                        <div class="input-group">
                            <input type="text" class="form-control" name="search" placeholder="Search your recipes by name..." value="<?= htmlspecialchars($search) ?>">
                            <button type="submit" class="btn btn-custom">
                                <i class="fas fa-search"></i> Search
                            </button>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <?php if (!empty($search)): ?>
                            <a href="schedules.php" class="btn btn-outline-custom">
                                <i class="fas fa-times"></i> Clear Search
                            </a>
                        <?php endif; ?>
                        <span class="user-recipes-badge">
                            <i class="fas fa-user"></i> Your Recipes
                        </span>
                    </div>
                </form>
            </div>

            <div class="card">
                <div class="card-body">
                    <form method="post" id="scheduleForm">
                        <!-- Filename and Unit Input -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Schedule Name:</label>
                                <div class="input-group filename-input">
                                    <input type="text" class="form-control" name="pdf_filename" 
                                           placeholder="Enter schedule name" value="food_production_schedule_<?= date('Y-m-d') ?>" required>
                                </div>
                                <small class="text-muted">This will be the name of your saved schedule</small>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Unit Name:</label>
                                <div class="input-group unit-input">
                                    <input type="text" class="form-control" name="unit_name" 
                                           placeholder="Enter unit name (e.g., MacCare Tzaneen)" required>
                                </div>
                                <small class="text-muted">Required - will appear in schedule header and footer</small>
                            </div>
                        </div>

                        <!-- Recipe Selection -->
                        <div class="mb-4">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <label class="form-label fw-bold mb-0">
                                    Select Your Meals for Schedule:
                                    <span id="selectedCount" class="selected-count">0 selected</span>
                                </label>
                                <div class="btn-group">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" id="selectAllBtn">
                                        <i class="fas fa-check-double"></i> Select All
                                    </button>
                                    <button type="button" class="btn btn-outline-secondary btn-sm" id="deselectAllBtn">
                                        <i class="fas fa-times"></i> Deselect All
                                    </button>
                                </div>
                            </div>
                            
                            <div class="recipe-list">
                                <?php if (empty($allRecipes)): ?>
                                    <div class="alert alert-warning text-center">
                                        <i class="fas fa-exclamation-triangle"></i><br>
                                        <?php if (!empty($search)): ?>
                                            No recipes found matching "<?= htmlspecialchars($search) ?>". 
                                            <a href="schedules.php" class="alert-link">Show all your recipes</a>
                                        <?php else: ?>
                                            You haven't created any recipes yet. Please add recipes first in the costing section.
                                        <?php endif; ?>
                                    </div>
                                <?php else: ?>
                                    <?php foreach ($allRecipes as $recipe): ?>
                                        <div class="recipe-item">
                                            <div class="form-check">
                                                <input class="form-check-input meal-checkbox" type="checkbox" name="meals[]" 
                                                       value="<?= $recipe['id'] ?>" id="meal_<?= $recipe['id'] ?>">
                                                <label class="form-check-label w-100" for="meal_<?= $recipe['id'] ?>">
                                                    <div class="d-flex justify-content-between align-items-start">
                                                        <div>
                                                            <strong><?= htmlspecialchars($recipe['recipe_name']) ?></strong>
                                                        </div>
                                                        <small class="text-muted ms-3">
                                                            ID: <?= $recipe['id'] ?>
                                                        </small>
                                                    </div>
                                                </label>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Action Buttons -->
                        <div class="export-buttons">
                            <button type="submit" name="generate_pdf" class="btn btn-custom" 
                                    id="generatePdfBtn" <?= empty($allRecipes) ? 'disabled' : '' ?>>
                                <i class="fas fa-file-pdf"></i> Generate & Save PDF
                            </button>
                            <button type="submit" name="generate_excel" class="btn btn-excel" 
                                    id="generateExcelBtn" <?= empty($allRecipes) ? 'disabled' : '' ?>>
                                <i class="fas fa-file-excel"></i> Download Excel
                            </button>
                            <a href="dashboard.php" class="btn btn-outline-custom">
                                <i class="fas fa-arrow-left"></i> Back to Dashboard
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Layout Preview -->
            <div class="preview-section">
                <h6><i class="fas fa-eye"></i> New PDF Layout Preview</h6>
                <p class="mb-3">Updated layout with preparation steps table format:</p>
                
                <!-- Header Image Preview -->
                <div class="image-preview">
                    <i class="fas fa-image fa-3x text-muted mb-2"></i>
                    <p class="mb-0">Company Header Image (header.png)</p>
                    <small class="text-muted">Will be displayed at the top of each PDF page</small>
                </div>
                
                <!-- Header Preview -->
                <div class="header-preview">
                    <div class="header-row">
                        <h5 class="mb-0">FOOD PRODUCTION SCHEDULE</h5>
                        <div class="text-end">
                            <strong>Unit:</strong> MacCare Tzaneen
                        </div>
                    </div>
                    <div class="header-fields">
                        <div class="header-field">
                            <span class="header-label">Date:</span>
                            <div class="header-underline"></div>
                        </div>
                        <div class="header-field">
                            <span class="header-label">Week:</span>
                            <div class="header-underline"></div>
                        </div>
                        <div class="header-field">
                            <span class="header-label">Day:</span>
                            <div class="header-underline"></div>
                        </div>
                        <div class="header-field">
                            <span class="header-label">Meal:</span>
                            <span>Breakfast Lunch Dinner</span>
                        </div>
                        <div class="header-field">
                            <span class="header-label">Meal Count:</span>
                            <div class="header-underline"></div>
                        </div>
                    </div>
                </div>
                
                <!-- Recipe Block Preview with Table -->
                <div class="pdf-block-preview">
                    <div class="pdf-block-header">Meal 1: Matlabela Porridge</div>
                    <div class="pdf-block-content">
                        <!-- Table for preparation steps -->
                        <div class="table-preview">
                            <table>
                                <thead>
                                    <tr>
                                        <th width="20%">Recipe Item</th>
                                        <th width="60%">Instruction</th>
                                        <th width="20%">Time Allocation</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>Matlabela</td>
                                        <td>Make a slurry with the matlabela and some cold water</td>
                                        <td>5 mins</td>
                                    </tr>
                                    <tr>
                                        <td>Water</td>
                                        <td>Bring water to boil. Add salt</td>
                                        <td>10 mins</td>
                                    </tr>
                                    <tr>
                                        <td>Combined</td>
                                        <td>Pour slurry into boiling water and mix thoroughly. Let simmer until cooked</td>
                                        <td>15 mins</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        
                        <div class="pdf-field-row mt-3">
                            <div class="pdf-field-label">Employee:</div>
                            <div class="pdf-field-value"></div>
                        </div>
                        <div class="pdf-field-row">
                            <div class="pdf-field-label">Quantity (Portions):</div>
                            <div class="pdf-field-value"></div>
                        </div>
                        <div class="pdf-field-row">
                            <div class="pdf-field-label">Quantity (kg/h):</div>
                            <div class="pdf-field-value"></div>
                        </div>
                        <div class="pdf-field-row">
                            <div class="pdf-field-label">Time Schedule:</div>
                            <div class="pdf-field-value"></div>
                        </div>
                        <div class="pdf-field-row">
                            <div class="pdf-field-label">Comments:</div>
                            <div class="pdf-field-value" style="height: 40px;"></div>
                        </div>
                    </div>
                </div>
                <small class="text-muted">PDF will include your company header image and tabular preparation steps format.</small>
            </div>

            <!-- Saved Schedules Section -->
            <div class="saved-schedules">
                <h4 class="mb-4"><i class="fas fa-history"></i> Your Saved Production Schedules</h4>
                
                <?php if (empty($savedSchedules)): ?>
                    <div class="alert alert-info text-center">
                        <i class="fas fa-info-circle"></i><br>
                        No saved schedules yet. Generate your first schedule above!
                    </div>
                <?php else: ?>
                    <?php foreach ($savedSchedules as $schedule): ?>
                        <div class="schedule-item">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-1"><?= htmlspecialchars($schedule['schedule_name']) ?></h6>
                                    <small class="text-muted">
                                        <i class="fas fa-building"></i> Unit: <?= htmlspecialchars($schedule['unit_name']) ?> | 
                                        <i class="fas fa-calendar"></i> Created: <?= date('M j, Y g:i A', strtotime($schedule['created_at'])) ?>
                                    </small>
                                </div>
                                <div class="schedule-actions">
                                    <a href="schedules.php?download_schedule=<?= $schedule['id'] ?>" class="btn btn-success btn-sm">
                                        <i class="fas fa-download"></i> Download PDF
                                    </a>
                                    <button type="button" class="btn btn-warning btn-sm edit-schedule-btn" 
                                            data-schedule-id="<?= $schedule['id'] ?>" 
                                            data-schedule-name="<?= htmlspecialchars($schedule['schedule_name']) ?>" 
                                            data-unit-name="<?= htmlspecialchars($schedule['unit_name']) ?>">
                                        <i class="fas fa-edit"></i> Edit
                                    </button>
                                    <form method="post" class="d-inline">
                                        <input type="hidden" name="schedule_id" value="<?= $schedule['id'] ?>">
                                        <button type="submit" name="delete_schedule" class="btn btn-danger btn-sm" 
                                                onclick="return confirm('Are you sure you want to delete this schedule?')">
                                            <i class="fas fa-trash"></i> Delete
                                        </button>
                                    </form>
                                </div>
                            </div>
                            
                            <!-- Edit Form (Hidden by default) -->
                            <div class="edit-form" id="edit-form-<?= $schedule['id'] ?>" style="display: none;">
                                <form method="post">
                                    <input type="hidden" name="schedule_id" value="<?= $schedule['id'] ?>">
                                    <div class="row g-3 align-items-end">
                                        <div class="col-md-5">
                                            <label class="form-label">Schedule Name:</label>
                                            <input type="text" class="form-control" name="schedule_name" 
                                                   value="<?= htmlspecialchars($schedule['schedule_name']) ?>" required>
                                        </div>
                                        <div class="col-md-5">
                                            <label class="form-label">Unit Name:</label>
                                            <input type="text" class="form-control" name="unit_name" 
                                                   value="<?= htmlspecialchars($schedule['unit_name']) ?>" required>
                                        </div>
                                        <div class="col-md-2">
                                            <button type="submit" name="update_schedule" class="btn btn-custom w-100">
                                                <i class="fas fa-save"></i> Update
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </main>

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

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const selectAllBtn = document.getElementById('selectAllBtn');
            const deselectAllBtn = document.getElementById('deselectAllBtn');
            const checkboxes = document.querySelectorAll('.meal-checkbox');
            const selectedCount = document.getElementById('selectedCount');
            const generatePdfBtn = document.getElementById('generatePdfBtn');
            const generateExcelBtn = document.getElementById('generateExcelBtn');
            const editButtons = document.querySelectorAll('.edit-schedule-btn');
            
            function updateSelectedCount() {
                const selected = document.querySelectorAll('.meal-checkbox:checked').length;
                selectedCount.textContent = selected + ' selected';
                
                // Enable/disable generate buttons based on selection
                const isDisabled = selected === 0;
                generatePdfBtn.disabled = isDisabled;
                generateExcelBtn.disabled = isDisabled;
            }
            
            // Initial count update
            updateSelectedCount();
            
            // Select all functionality
            if (selectAllBtn) {
                selectAllBtn.addEventListener('click', function() {
                    checkboxes.forEach(checkbox => {
                        checkbox.checked = true;
                    });
                    updateSelectedCount();
                });
            }
            
            // Deselect all functionality
            if (deselectAllBtn) {
                deselectAllBtn.addEventListener('click', function() {
                    checkboxes.forEach(checkbox => {
                        checkbox.checked = false;
                    });
                    updateSelectedCount();
                });
            }
            
            // Update count when checkboxes change
            checkboxes.forEach(checkbox => {
                checkbox.addEventListener('change', updateSelectedCount);
            });
            
            // Edit schedule functionality
            editButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const scheduleId = this.getAttribute('data-schedule-id');
                    const editForm = document.getElementById('edit-form-' + scheduleId);
                    
                    // Toggle edit form visibility
                    if (editForm.style.display === 'none') {
                        editForm.style.display = 'block';
                        this.innerHTML = '<i class="fas fa-times"></i> Cancel';
                    } else {
                        editForm.style.display = 'none';
                        this.innerHTML = '<i class="fas fa-edit"></i> Edit';
                    }
                });
            });
        });
    </script>
</body>
</html>