<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type');
// ==================== DATABASE SETUP ====================
$host = 'localhost';
$db = 'quotes_db';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
die(json_encode(['error' => 'Database connection failed']));
}
// ==================== API KEY AUTH (SIMPLIFIED) ====================
$valid_api_key = 'secret123';
$api_key = $_SERVER['HTTP_API_KEY'] ?? '';
if ($api_key !== $valid_api_key && $_SERVER['REQUEST_METHOD'] !== 'GET') {
die(json_encode(['error' => 'Invalid API key']));
}
// ==================== CRUD OPERATIONS ====================
$request_method = $_SERVER['REQUEST_METHOD'];
$input_data = json_decode(file_get_contents('php://input'), true);
switch ($request_method) {
case 'GET':
// Read all quotes or single quote
$id = $_GET['id'] ?? null;
if ($id) {
$stmt = $pdo->prepare("SELECT * FROM quotes WHERE id = ?");
$stmt->execute([$id]);
$quote = $stmt->fetch();
echo json_encode($quote ?: ['error' => 'Quote not found']);
} else {
$stmt = $pdo->query("SELECT * FROM quotes");
echo json_encode($stmt->fetchAll());
}
break;
case 'POST':
// Create new quote
$author = $input_data['author'] ?? '';
$text = $input_data['text'] ?? '';
if (empty($author) || empty($text)) {
echo json_encode(['error' => 'Author and text required']);
break;
}
$stmt = $pdo->prepare("INSERT INTO quotes (author, text) VALUES (?, ?)");
$stmt->execute([$author, $text]);
echo json_encode(['success' => 'Quote added', 'id' => $pdo->lastInsertId()]);
break;
case 'PUT':
// Update quote
$id = $input_data['id'] ?? null;
$author = $input_data['author'] ?? '';
$text = $input_data['text'] ?? '';
if (!$id || empty($author) || empty($text)) {
echo json_encode(['error' => 'ID, author, and text required']);
break;
}
$stmt = $pdo->prepare("UPDATE quotes SET author = ?, text = ? WHERE id = ?");
$stmt->execute([$author, $text, $id]);
echo json_encode(['success' => 'Quote updated']);
break;
case 'DELETE':
// Delete quote
$id = $input_data['id'] ?? null;
if (!$id) {
echo json_encode(['error' => 'ID required']);
break;
}
$stmt = $pdo->prepare("DELETE FROM quotes WHERE id = ?");
$stmt->execute([$id]);
echo json_encode(['success' => 'Quote deleted']);
break;
default:
echo json_encode(['error' => 'Method not allowed']);
}
?>