<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

require_once '../config/database.php';

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

try {
    $pdo = getDBConnection();
    
    // Create quotes table if not exists
    $createTableSQL = "
        CREATE TABLE IF NOT EXISTS quotes (
            id INT AUTO_INCREMENT PRIMARY KEY,
            text TEXT NOT NULL,
            author VARCHAR(255) DEFAULT NULL,
            is_active TINYINT(1) DEFAULT 1,
            display_order INT DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
    ";
    $pdo->exec($createTableSQL);
    
    // Check if table is empty and insert default quotes
    $countStmt = $pdo->query("SELECT COUNT(*) FROM quotes");
    $count = $countStmt->fetchColumn();
    
    if ($count == 0) {
        $defaultQuotes = [
            ['The stars are the land-marks of the universe.', 'Sir John Herschel', 1, 1],
            ['Astrology is a language. If you understand this language, the sky speaks to you.', 'Dane Rudhyar', 1, 2],
            ['The cosmos is within us. We are made of star-stuff.', 'Carl Sagan', 1, 3],
            ['Look up at the stars and not down at your feet.', 'Stephen Hawking', 1, 4],
            ['The universe is not only queerer than we suppose, but queerer than we can suppose.', 'J.B.S. Haldane', 1, 5],
            ['In the vastness of space and the immensity of time, it is my joy to share a planet and an epoch with you.', 'Carl Sagan', 1, 6],
            ['The sky is the daily bread of the eyes.', 'Ralph Waldo Emerson', 1, 7],
            ['Astronomy compels the soul to look upward and leads us from this world to another.', 'Plato', 1, 8]
        ];
        
        $insertStmt = $pdo->prepare("INSERT INTO quotes (text, author, is_active, display_order) VALUES (?, ?, ?, ?)");
        foreach ($defaultQuotes as $quote) {
            $insertStmt->execute($quote);
        }
    }
    
    $method = $_SERVER['REQUEST_METHOD'];
    
    switch ($method) {
        case 'GET':
            // Get all quotes
            $stmt = $pdo->prepare("SELECT * FROM quotes ORDER BY display_order ASC, created_at ASC");
            $stmt->execute();
            $quotes = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'quotes' => $quotes,
                'total_quotes' => count($quotes)
            ]);
            break;
            
        case 'POST':
            // Add new quote
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($input['text']) || empty(trim($input['text']))) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Quote text is required']);
                exit;
            }
            
            $text = trim($input['text']);
            $author = isset($input['author']) ? trim($input['author']) : null;
            $isActive = isset($input['is_active']) ? (int)$input['is_active'] : 1;
            $displayOrder = isset($input['display_order']) ? (int)$input['display_order'] : 0;
            
            $stmt = $pdo->prepare("INSERT INTO quotes (text, author, is_active, display_order) VALUES (?, ?, ?, ?)");
            $stmt->execute([$text, $author, $isActive, $displayOrder]);
            
            echo json_encode([
                'success' => true,
                'message' => 'Quote added successfully',
                'quote_id' => $pdo->lastInsertId()
            ]);
            break;
            
        case 'PUT':
            // Update quote
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($input['id']) || !isset($input['text']) || empty(trim($input['text']))) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Quote ID and text are required']);
                exit;
            }
            
            $id = (int)$input['id'];
            $text = trim($input['text']);
            $author = isset($input['author']) ? trim($input['author']) : null;
            $isActive = isset($input['is_active']) ? (int)$input['is_active'] : 1;
            $displayOrder = isset($input['display_order']) ? (int)$input['display_order'] : 0;
            
            $stmt = $pdo->prepare("UPDATE quotes SET text = ?, author = ?, is_active = ?, display_order = ? WHERE id = ?");
            $stmt->execute([$text, $author, $isActive, $displayOrder, $id]);
            
            if ($stmt->rowCount() > 0) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Quote updated successfully'
                ]);
            } else {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Quote not found']);
            }
            break;
            
        case 'DELETE':
            // Delete quote
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($input['id'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Quote ID is required']);
                exit;
            }
            
            $id = (int)$input['id'];
            $stmt = $pdo->prepare("DELETE FROM quotes WHERE id = ?");
            $stmt->execute([$id]);
            
            if ($stmt->rowCount() > 0) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Quote deleted successfully'
                ]);
            } else {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Quote not found']);
            }
            break;
            
        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
            break;
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
