<?php
session_start();
require_once '../config/database.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$pdo = getDBConnection();
$success_message = '';
$error_message = '';

// Fetch quotes settings
$quotes_enabled = 'on';
$quotes_rotation_interval = '30';
$quotes_show_author = 'on';

$stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
$stmt->execute(['quotes_enabled']);
$quotes_enabled = $stmt->fetchColumn() ?: 'on';

$stmt->execute(['quotes_rotation_interval']);
$quotes_rotation_interval = $stmt->fetchColumn() ?: '30';

$stmt->execute(['quotes_show_author']);
$quotes_show_author = $stmt->fetchColumn() ?: 'on';

// Fetch existing quotes
$quotes = [];
try {
    $stmt = $pdo->query("SELECT * FROM quotes ORDER BY display_order, created_at");
    $quotes = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Quotes table might not exist yet
    $quotes = [];
}

// Handle quotes CRUD operations
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['quote_action'])) {
    try {
        switch ($_POST['quote_action']) {
            case 'add':
                $quote_text = trim($_POST['quote_text']);
                $author = trim($_POST['quote_author']);
                $category = trim($_POST['quote_category']);
                $display_order = (int)$_POST['quote_display_order'];
                
                if (empty($quote_text)) {
                    throw new Exception('Quote text is required');
                }
                
                $stmt = $pdo->prepare("INSERT INTO quotes (quote_text, author, category, display_order) VALUES (?, ?, ?, ?)");
                $stmt->execute([$quote_text, $author, $category, $display_order]);
                $success_message = "Quote added successfully!";
                break;
                
            case 'update':
                $quote_id = (int)$_POST['quote_id'];
                $quote_text = trim($_POST['quote_text']);
                $author = trim($_POST['quote_author']);
                $category = trim($_POST['quote_category']);
                $display_order = (int)$_POST['quote_display_order'];
                $is_active = isset($_POST['quote_is_active']) ? 1 : 0;
                
                if (empty($quote_text)) {
                    throw new Exception('Quote text is required');
                }
                
                $stmt = $pdo->prepare("UPDATE quotes SET quote_text = ?, author = ?, category = ?, display_order = ?, is_active = ? WHERE id = ?");
                $stmt->execute([$quote_text, $author, $category, $display_order, $is_active, $quote_id]);
                $success_message = "Quote updated successfully!";
                break;
                
            case 'delete':
                $quote_id = (int)$_POST['quote_id'];
                $stmt = $pdo->prepare("DELETE FROM quotes WHERE id = ?");
                $stmt->execute([$quote_id]);
                $success_message = "Quote deleted successfully!";
                break;
        }
        
        // Refresh quotes list
        header('Location: quotes.php');
        exit;
        
    } catch (Exception $e) {
        $error_message = "Error managing quotes: " . $e->getMessage();
    }
}

// Handle settings update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_settings'])) {
    try {
        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        
        if (isset($_POST['quotes_enabled'])) {
            $stmt->execute(['quotes_enabled', $_POST['quotes_enabled'], $_POST['quotes_enabled']]);
        }
        
        if (isset($_POST['quotes_rotation_interval'])) {
            $stmt->execute(['quotes_rotation_interval', $_POST['quotes_rotation_interval'], $_POST['quotes_rotation_interval']]);
        }
        
        if (isset($_POST['quotes_show_author'])) {
            $stmt->execute(['quotes_show_author', $_POST['quotes_show_author'], $_POST['quotes_show_author']]);
        }
        
        $success_message = "Settings updated successfully!";
        
        // Refresh page to show updated settings
        header('Location: quotes.php');
        exit;
        
    } catch (Exception $e) {
        $error_message = "Error updating settings: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quotes Management - Astro Admin</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">
    <style>
        body {
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
            color: #ffffff;
            min-height: 100vh;
        }
        .sidebar {
            background: rgba(0, 0, 0, 0.3);
            backdrop-filter: blur(10px);
            border-right: 1px solid rgba(255, 255, 255, 0.1);
        }
        .main-content {
            background: rgba(255, 255, 255, 0.05);
            backdrop-filter: blur(10px);
        }
        .quotes-card {
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 15px;
            backdrop-filter: blur(10px);
        }
        .form-control, .form-select {
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: #ffffff;
        }
        .form-control:focus, .form-select:focus {
            border-color: #ffc107;
            box-shadow: 0 0 0 0.2rem rgba(255, 193, 7, 0.25);
            background: rgba(255, 255, 255, 0.15);
        }
        .btn-save {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            border: none;
            border-radius: 25px;
            padding: 12px 30px;
            font-weight: 600;
            transition: all 0.3s;
        }
        .btn-save:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(40, 167, 69, 0.3);
        }
        .setting-item {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 15px;
            border-left: 4px solid #ffc107;
        }
        .table-dark {
            background: rgba(0, 0, 0, 0.3);
        }
        .table-dark th {
            background: rgba(255, 193, 7, 0.2);
            border-color: rgba(255, 255, 255, 0.2);
        }
        .table-dark td {
            border-color: rgba(255, 255, 255, 0.1);
        }
        .quote-text {
            max-width: 300px;
            word-wrap: break-word;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 px-0">
                <div class="sidebar p-3">
                    <div class="text-center mb-4">
                        <h4 class="text-warning">
                            <i class="fas fa-star"></i> ASTRO ADMIN
                        </h4>
                    </div>
                    
                    <nav class="nav flex-column">
                        <a class="nav-link" href="index.php">
                            <i class="fas fa-tachometer-alt me-2"></i> Dashboard
                        </a>
                        <a class="nav-link" href="users.php">
                            <i class="fas fa-users me-2"></i> Users
                        </a>
                        <a class="nav-link" href="appointments.php">
                            <i class="fas fa-calendar-check me-2"></i> Appointments
                        </a>
                        <a class="nav-link" href="notifications.php">
                            <i class="fas fa-bell me-2"></i> Push Notifications
                        </a>
                        <a class="nav-link" href="settings.php">
                            <i class="fas fa-cog me-2"></i> Settings
                        </a>
                        <a class="nav-link active" href="quotes.php">
                            <i class="fas fa-quote-left me-2"></i> Quotes Management
                        </a>
                        <a class="nav-link" href="logout.php">
                            <i class="fas fa-sign-out-alt me-2"></i> Logout
                        </a>
                        <hr class="text-light">
                        <a class="nav-link text-warning" href="#" onclick="openHelp()">
                            <i class="fab fa-whatsapp me-2"></i> Help & Support
                        </a>
                        <a class="nav-link text-info" href="HELP_GUIDE.md" target="_blank">
                            <i class="fas fa-book me-2"></i> Help Guide
                        </a>
                        <a class="nav-link text-success" href="help_utility.php">
                            <i class="fas fa-tools me-2"></i> Admin Tools
                        </a>
                    </nav>
                </div>
            </div>
            
            <!-- Main Content -->
            <div class="col-md-9 col-lg-10 main-content">
                <div class="p-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-quote-left me-2"></i>Quotes Management</h2>
                        <a href="settings.php" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left me-2"></i>Back to Settings
                        </a>
                    </div>
                    
                    <?php if ($success_message) { ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars($success_message); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php } ?>
                    
                    <?php if ($error_message) { ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-triangle me-2"></i><?php echo htmlspecialchars($error_message); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php } ?>
                    
                    <div class="row">
                        <div class="col-md-8">
                            <div class="quotes-card">
                                <div class="card-body">
                                    <h5 class="card-title mb-4">
                                        <i class="fas fa-cog me-2 text-warning"></i>Quotes Settings
                                    </h5>
                                    
                                    <form method="POST" action="">
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-toggle-on me-2"></i>Quotes Display
                                                    </label>
                                                    <select name="quotes_enabled" class="form-select">
                                                        <option value="on" <?php echo $quotes_enabled === 'on' ? 'selected' : ''; ?>>Enabled</option>
                                                        <option value="off" <?php echo $quotes_enabled === 'off' ? 'selected' : ''; ?>>Disabled</option>
                                                    </select>
                                                    <small class="text-muted">Show quotes on app home screen</small>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-clock me-2"></i>Rotation Interval (sec)
                                                    </label>
                                                    <input type="number" name="quotes_rotation_interval" class="form-control" 
                                                           value="<?php echo htmlspecialchars($quotes_rotation_interval); ?>" 
                                                           min="10" max="300" required>
                                                    <small class="text-muted">How often quotes change (10-300 seconds)</small>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="setting-item">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-user me-2"></i>Show Author
                                                    </label>
                                                    <select name="quotes_show_author" class="form-select">
                                                        <option value="on" <?php echo $quotes_show_author === 'on' ? 'selected' : ''; ?>>Yes</option>
                                                        <option value="off" <?php echo $quotes_show_author === 'off' ? 'selected' : ''; ?>>No</option>
                                                    </select>
                                                    <small class="text-muted">Display quote author with quote</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="text-center mt-4">
                                            <button type="submit" name="update_settings" class="btn btn-save btn-lg">
                                                <i class="fas fa-save me-2"></i>Save Settings
                                            </button>
                                        </div>
                                    </form>
                                    
                                    <hr class="my-4">
                                    
                                    <!-- Add New Quote -->
                                    <h5 class="mb-3">
                                        <i class="fas fa-plus me-2 text-success"></i>Add New Quote
                                    </h5>
                                    <form method="POST" action="" class="row g-3">
                                        <input type="hidden" name="quote_action" value="add">
                                        <div class="col-md-6">
                                            <label class="form-label">Quote Text</label>
                                            <textarea name="quote_text" class="form-control" rows="3" 
                                                      placeholder="Enter inspirational quote" required></textarea>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Author</label>
                                            <input type="text" name="quote_author" class="form-control" 
                                                   placeholder="Author name">
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Category</label>
                                            <select name="quote_category" class="form-select">
                                                <option value="astrology">Astrology</option>
                                                <option value="motivation">Motivation</option>
                                                <option value="spirituality">Spirituality</option>
                                                <option value="destiny">Destiny</option>
                                                <option value="cosmic">Cosmic</option>
                                                <option value="general">General</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Order</label>
                                            <input type="number" name="quote_display_order" class="form-control" 
                                                   value="0" min="0" max="100">
                                        </div>
                                        <div class="col-12">
                                            <button type="submit" class="btn btn-success">
                                                <i class="fas fa-plus me-2"></i>Add Quote
                                            </button>
                                        </div>
                                    </form>
                                    
                                    <hr class="my-4">
                                    
                                    <!-- Manage Existing Quotes -->
                                    <h5 class="mb-3">
                                        <i class="fas fa-edit me-2 text-primary"></i>Manage Quotes
                                    </h5>
                                    
                                    <?php if (empty($quotes)): ?>
                                        <div class="text-center py-4">
                                            <i class="fas fa-quote-left fa-3x text-muted mb-3"></i>
                                            <p class="text-muted">No quotes added yet. Add your first inspirational quote above!</p>
                                        </div>
                                    <?php else: ?>
                                        <div class="table-responsive">
                                            <table class="table table-dark table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>Order</th>
                                                        <th>Quote</th>
                                                        <th>Author</th>
                                                        <th>Category</th>
                                                        <th>Status</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($quotes as $quote): ?>
                                                    <tr>
                                                        <td><?php echo $quote['display_order']; ?></td>
                                                        <td>
                                                            <div class="quote-text">
                                                                <?php echo htmlspecialchars($quote['quote_text']); ?>
                                                            </div>
                                                        </td>
                                                        <td><?php echo htmlspecialchars($quote['author'] ?: 'Unknown'); ?></td>
                                                        <td>
                                                            <span class="badge bg-info"><?php echo ucfirst($quote['category']); ?></span>
                                                        </td>
                                                        <td>
                                                            <span class="badge <?php echo $quote['is_active'] ? 'bg-success' : 'bg-secondary'; ?>">
                                                                <?php echo $quote['is_active'] ? 'Active' : 'Inactive'; ?>
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <button type="button" class="btn btn-sm btn-primary" 
                                                                    onclick="editQuote(<?php echo htmlspecialchars(json_encode($quote)); ?>)">
                                                                <i class="fas fa-edit"></i>
                                                            </button>
                                                            <button type="button" class="btn btn-sm btn-danger" 
                                                                    onclick="deleteQuote(<?php echo $quote['id']; ?>)">
                                                                <i class="fas fa-trash"></i>
                                                            </button>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="quotes-card">
                                <div class="card-body">
                                    <h6 class="card-title text-warning">
                                        <i class="fas fa-info-circle me-2"></i>Current Settings
                                    </h6>
                                    
                                    <div class="mt-3">
                                        <p><strong>Quotes Status:</strong><br>
                                            <span class="badge <?php echo $quotes_enabled === 'on' ? 'bg-success' : 'bg-danger'; ?>">
                                                <?php echo $quotes_enabled === 'on' ? '✅ Enabled' : '❌ Disabled'; ?>
                                            </span>
                                        </p>
                                        <p><strong>Rotation Interval:</strong><br><?php echo htmlspecialchars($quotes_rotation_interval); ?> seconds</p>
                                        <p><strong>Show Author:</strong><br>
                                            <span class="badge <?php echo $quotes_show_author === 'on' ? 'bg-success' : 'bg-secondary'; ?>">
                                                <?php echo $quotes_show_author === 'on' ? 'Yes' : 'No'; ?>
                                            </span>
                                        </p>
                                        
                                        <hr>
                                        
                                        <p><strong>Total Quotes:</strong><br><?php echo count($quotes); ?></p>
                                        <p><strong>Active Quotes:</strong><br><?php echo count(array_filter($quotes, fn($q) => $q['is_active'])); ?></p>
                                        
                                        <hr>
                                        
                                        <div class="text-center">
                                            <a href="../api/get_quotes.php" target="_blank" class="btn btn-outline-info btn-sm">
                                                <i class="fas fa-code me-2"></i>View API
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Edit Quote Modal -->
    <div class="modal fade" id="editQuoteModal" tabindex="-1" aria-labelledby="editQuoteModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content bg-dark text-light">
                <div class="modal-header">
                    <h5 class="modal-title" id="editQuoteModalLabel">
                        <i class="fas fa-edit me-2"></i>Edit Quote
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST" action="" id="editQuoteForm">
                    <div class="modal-body">
                        <input type="hidden" name="quote_action" value="update">
                        <input type="hidden" name="quote_id" id="edit_quote_id">
                        
                        <div class="row g-3">
                            <div class="col-12">
                                <label class="form-label">Quote Text</label>
                                <textarea name="quote_text" id="edit_quote_text" class="form-control" rows="4" 
                                          placeholder="Enter inspirational quote" required></textarea>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Author</label>
                                <input type="text" name="quote_author" id="edit_quote_author" class="form-control" 
                                       placeholder="Author name">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Category</label>
                                <select name="quote_category" id="edit_quote_category" class="form-select">
                                    <option value="astrology">Astrology</option>
                                    <option value="motivation">Motivation</option>
                                    <option value="spirituality">Spirituality</option>
                                    <option value="destiny">Destiny</option>
                                    <option value="cosmic">Cosmic</option>
                                    <option value="general">General</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Display Order</label>
                                <input type="number" name="quote_display_order" id="edit_quote_display_order" class="form-control" 
                                       min="0" max="100">
                            </div>
                            <div class="col-12">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="quote_is_active" id="edit_quote_is_active">
                                    <label class="form-check-label" for="edit_quote_is_active">
                                        Quote is active
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Quote</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Quote management functions
        function editQuote(quoteData) {
            document.getElementById('edit_quote_id').value = quoteData.id;
            document.getElementById('edit_quote_text').value = quoteData.quote_text;
            document.getElementById('edit_quote_author').value = quoteData.author || '';
            document.getElementById('edit_quote_category').value = quoteData.category;
            document.getElementById('edit_quote_display_order').value = quoteData.display_order;
            document.getElementById('edit_quote_is_active').checked = quoteData.is_active == 1;
            
            const modal = new bootstrap.Modal(document.getElementById('editQuoteModal'));
            modal.show();
        }
        
        function deleteQuote(quoteId) {
            if (confirm('Are you sure you want to delete this quote? This action cannot be undone.')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="quote_action" value="delete">
                    <input type="hidden" name="quote_id" value="${quoteId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        function openHelp() {
            // You can implement help functionality here
            alert('Help & Support feature coming soon!');
        }
    </script>
</body>
</html> 