<%# Ruby Calculator - Interactive calculator built with Ruby on Rails %>
<%# Author: RSK World (Molla Samser, Founder | Rima Khatun, Designer & Tester) %>
<%# Contact: help@rskworld.in | +91 93305 39277 %>
<%# Website: https://rskworld.in %>
<%# Year: 2026 %>
<%# Description: Build a fully functional calculator using Ruby on Rails with modern UI %>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculation History - Ruby Calculator Pro | RSK World</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.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">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" rel="stylesheet">
    <style>
        :root {
            --theme-primary: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --theme-secondary: #4a5568;
            --theme-accent: #ed8936;
            --theme-success: #48bb78;
            --theme-danger: #e53e3e;
            --theme-warning: #ecc94b;
            --theme-info: #4299e1;
            --theme-background: #f7fafc;
            --theme-text: #2d3748;
            --theme-display: #2d3748;
        }
        
        body {
            background: var(--theme-background);
            color: var(--theme-text);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            min-height: 100vh;
            transition: all 0.3s ease;
        }
        
        .history-container {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            transition: all 0.3s ease;
        }
        
        .history-container:hover {
            transform: translateY(-3px);
            box-shadow: 0 15px 40px rgba(0,0,0,0.15);
        }
        
        .table-hover tbody tr:hover {
            background-color: #f8f9fa;
            cursor: pointer;
        }
        
        .operation-badge {
            font-size: 0.8em;
            padding: 4px 8px;
            border-radius: 12px;
        }
        
        .stats-card {
            background: var(--theme-primary);
            color: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            transition: all 0.3s ease;
        }
        
        .stats-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.2);
        }
        
        .search-box {
            position: relative;
        }
        
        .search-box input {
            padding-left: 40px;
            border-radius: 25px;
            border: 2px solid var(--theme-info);
        }
        
        .search-box i {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--theme-info);
        }
        
        .filter-dropdown {
            border-radius: 25px;
            border: 2px solid var(--theme-accent);
        }
        
        .export-btn {
            border-radius: 25px;
            transition: all 0.3s ease;
        }
        
        .export-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        .history-item {
            transition: all 0.3s ease;
        }
        
        .history-item:hover {
            background-color: #e3f2fd;
            border-left: 4px solid var(--theme-info);
        }
        
        .footer-info {
            background: var(--theme-secondary);
            color: white;
            padding: 25px;
            border-radius: 15px;
            margin-top: 30px;
            text-align: center;
        }
        
        @media (max-width: 768px) {
            .history-container {
                padding: 20px;
                margin-bottom: 15px;
            }
            
            .stats-card {
                margin-bottom: 15px;
            }
        }
    </style>
</head>
<body class="bg-light">
    <div class="container py-5">
        <div class="row">
            <div class="col-lg-12">
                <!-- Header -->
                <div class="text-center mb-4 animate__animated animate__fadeInDown">
                    <h1 class="display-4">
                        <i class="fas fa-history text-info"></i> Calculation History
                    </h1>
                    <p class="lead">View, Search, and Analyze Your Calculation History</p>
                </div>

                <!-- Statistics Cards -->
                <div class="row mb-4 animate__animated animate__fadeIn">
                    <div class="col-md-3">
                        <div class="stats-card text-center">
                            <h3><i class="fas fa-calculator"></i></h3>
                            <h4><%= @history.count %></h4>
                            <p>Total Calculations</p>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card text-center">
                            <h3><i class="fas fa-chart-line"></i></h3>
                            <h4><%= @history.group(:operation).count.keys.count %></h4>
                            <p>Operations Used</p>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card text-center">
                            <h3><i class="fas fa-clock"></i></h3>
                            <h4><%= @history.first&.created_at&.strftime("%H:%M") || "N/A" %></h4>
                            <p>Last Calculation</p>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stats-card text-center">
                            <h3><i class="fas fa-star"></i></h3>
                            <h4><%= @history.where.not(favorite_calculation_id: nil).count %></h4>
                            <p>Favorites Used</p>
                        </div>
                    </div>
                </div>

                <!-- Search and Filter -->
                <div class="history-container animate__animated animate__fadeIn">
                    <div class="row align-items-center mb-3">
                        <div class="col-md-4">
                            <div class="search-box">
                                <i class="fas fa-search"></i>
                                <input type="text" class="form-control" id="search-history" 
                                       placeholder="Search calculations..." onkeyup="searchHistory()">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <select class="form-select filter-dropdown" id="filter-operation" onchange="filterHistory()">
                                <option value="">All Operations</option>
                                <option value="addition">Addition</option>
                                <option value="subtraction">Subtraction</option>
                                <option value="multiplication">Multiplication</option>
                                <option value="division">Division</option>
                                <option value="scientific">Scientific</option>
                                <option value="currency">Currency</option>
                                <option value="unit">Unit Conversion</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select class="form-select filter-dropdown" id="filter-date" onchange="filterHistory()">
                                <option value="">All Time</option>
                                <option value="today">Today</option>
                                <option value="week">This Week</option>
                                <option value="month">This Month</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <button class="btn btn-success export-btn w-100" onclick="exportHistory()">
                                <i class="fas fa-download"></i> Export
                            </button>
                        </div>
                    </div>
                </div>

                <!-- History Table -->
                <div class="history-container animate__animated animate__fadeInUp">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5><i class="fas fa-list"></i> Recent Calculations</h5>
                        <div>
                            <%= link_to root_path, class: "btn btn-primary me-2" do %>
                                <i class="fas fa-calculator"></i> Calculator
                            <% end %>
                            <button class="btn btn-danger" onclick="clearHistory()">
                                <i class="fas fa-trash"></i> Clear All
                            </button>
                        </div>
                    </div>
                    
                    <div class="table-responsive">
                        <table class="table table-hover" id="history-table">
                            <thead class="table-dark">
                                <tr>
                                    <th>#</th>
                                    <th>Expression</th>
                                    <th>Result</th>
                                    <th>Operation</th>
                                    <th>Date & Time</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="history-tbody">
                                <% @history.each_with_index do |calc, index| %>
                                    <tr class="history-item" data-operation="<%= calc.operation %>" 
                                        data-date="<%= calc.created_at.strftime('%Y-%m-%d') %>">
                                        <td><%= index + 1 %></td>
                                        <td><code><%= calc.expression %></code></td>
                                        <td><strong><%= calc.result %></strong></td>
                                        <td>
                                            <span class="badge bg-<%= get_operation_color(calc.operation) %> operation-badge">
                                                <%= calc.operation.upcase %>
                                            </span>
                                        </td>
                                        <td><small><%= calc.created_at.strftime("%Y-%m-%d %H:%M:%S") %></small></td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <button class="btn btn-outline-primary" onclick="reuseCalculation('<%= calc.expression %>')">
                                                    <i class="fas fa-redo"></i>
                                                </button>
                                                <button class="btn btn-outline-warning" onclick="addToFavorites('<%= calc.expression %>', <%= calc.id %>)">
                                                    <i class="fas fa-star"></i>
                                                </button>
                                                <button class="btn btn-outline-danger" onclick="deleteCalculation(<%= calc.id %>)">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <% end %>
                            </tbody>
                        </table>
                    </div>

                    <% if @history.empty? %>
                        <div class="text-center py-5 animate__animated animate__fadeIn">
                            <i class="fas fa-inbox fa-4x text-muted mb-3"></i>
                            <h5 class="text-muted">No calculations yet</h5>
                            <p class="text-muted">Start using the calculator to see your history here.</p>
                            <%= link_to root_path, class: "btn btn-primary" do %>
                                <i class="fas fa-calculator"></i> Go to Calculator
                            <% end %>
                        </div>
                    <% end %>
                </div>

                <!-- Footer Info -->
                <div class="footer-info animate__animated animate__fadeInUp">
                    <h6><i class="fas fa-gem text-danger"></i> Ruby Calculator Pro</h6>
                    <p class="mb-1">Professional Calculation History Manager</p>
                    <p class="mb-1">© 2026 <a href="https://rskworld.in" target="_blank" class="text-white">RSK World</a></p>
                    <p class="mb-0">Developed by: Molla Samser (Founder) | Rima Khatun (Designer & Tester)</p>
                    <p class="mb-0">Contact: <a href="mailto:help@rskworld.in" class="text-white">help@rskworld.in</a> | +91 93305 39277</p>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Search functionality
        function searchHistory() {
            const searchTerm = document.getElementById('search-history').value.toLowerCase();
            const rows = document.querySelectorAll('#history-tbody tr');
            
            rows.forEach(row => {
                const text = row.textContent.toLowerCase();
                if (text.includes(searchTerm)) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        }

        // Filter functionality
        function filterHistory() {
            const operation = document.getElementById('filter-operation').value;
            const dateFilter = document.getElementById('filter-date').value;
            const rows = document.querySelectorAll('#history-tbody tr');
            
            rows.forEach(row => {
                let show = true;
                
                // Filter by operation
                if (operation && row.getAttribute('data-operation') !== operation) {
                    show = false;
                }
                
                // Filter by date
                if (dateFilter) {
                    const rowDate = new Date(row.getAttribute('data-date'));
                    const today = new Date();
                    
                    switch(dateFilter) {
                        case 'today':
                            show = rowDate.toDateString() === today.toDateString();
                            break;
                        case 'week':
                            const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
                            show = rowDate >= weekAgo;
                            break;
                        case 'month':
                            const monthAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000);
                            show = rowDate >= monthAgo;
                            break;
                    }
                }
                
                row.style.display = show ? '' : 'none';
            });
        }

        // Reuse calculation
        function reuseCalculation(expression) {
            sessionStorage.setItem('reuseExpression', expression);
            window.location.href = '/';
        }

        // Add to favorites
        function addToFavorites(expression, historyId) {
            const name = prompt('Enter a name for this favorite:', expression);
            if (name) {
                fetch('/favorites', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        name: name, 
                        expression: expression,
                        category: 'history',
                        description: 'From calculation history'
                    })
                }).then(response => response.json())
                  .then(data => {
                      if (data.id) {
                          alert('Added to favorites successfully!');
                      } else {
                          alert('Error adding to favorites');
                      }
                  });
            }
        }

        // Delete calculation
        function deleteCalculation(id) {
            if (confirm('Are you sure you want to delete this calculation?')) {
                fetch(`/calculator/history/${id}`, {
                    method: 'DELETE'
                }).then(response => response.json())
                  .then(data => {
                      if (data.success) {
                          location.reload();
                      } else {
                          alert('Error deleting calculation');
                      }
                  });
            }
        }

        // Clear all history
        function clearHistory() {
            if (confirm('Are you sure you want to clear all calculation history? This cannot be undone.')) {
                fetch('/calculator/history/clear', {
                    method: 'DELETE'
                }).then(response => response.json())
                  .then(data => {
                      if (data.success) {
                          location.reload();
                      } else {
                          alert('Error clearing history');
                      }
                  });
            }
        }

        // Export history
        function exportHistory() {
            const rows = document.querySelectorAll('#history-tbody tr:not([style*="display: none"])');
            let csv = 'Expression,Result,Operation,Date Time\n';
            
            rows.forEach(row => {
                const cells = row.querySelectorAll('td');
                const expression = cells[1].textContent.trim();
                const result = cells[2].textContent.trim();
                const operation = cells[3].textContent.trim();
                const dateTime = cells[4].textContent.trim();
                
                csv += `"${expression}","${result}","${operation}","${dateTime}"\n`;
            });
            
            const blob = new Blob([csv], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `calculation_history_${new Date().toISOString().split('T')[0]}.csv`;
            a.click();
            window.URL.revokeObjectURL(url);
        }

        // Add keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            if (e.key === '/' && e.ctrlKey) {
                e.preventDefault();
                document.getElementById('search-history').focus();
            }
            if (e.key === 'e' && e.ctrlKey) {
                e.preventDefault();
                exportHistory();
            }
        });
    </script>
</body>
</html>
