<?php
require_once 'db_connection.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'User is not logged in.']);
    exit();
}

$data = json_decode(file_get_contents('php://input'), true);
$themeId = $data['theme_id'] ?? null;

if (!$themeId) {
    echo json_encode(['success' => false, 'message' => 'Theme ID is required.']);
    exit();
}

$userId = $_SESSION['user_id'];

try {
    $themeCheck = $pdo->prepare("SELECT id FROM themes WHERE id = :themeId");
    $themeCheck->bindParam(':themeId', $themeId, PDO::PARAM_INT);
    $themeCheck->execute();
    if (!$themeCheck->fetch(PDO::FETCH_ASSOC)) {
        echo json_encode(['success' => false, 'message' => 'Invalid theme ID.']);
        exit();
    }

    $updateQuery = $pdo->prepare("UPDATE emails_v SET theme_id = :themeId WHERE id = :userId");
    $updateQuery->bindParam(':themeId', $themeId, PDO::PARAM_INT);
    $updateQuery->bindParam(':userId', $userId, PDO::PARAM_INT);
    $updateQuery->execute();

    echo json_encode(['success' => true, 'message' => 'Theme updated successfully.']);
} catch (PDOException $e) {
    error_log("Error updating theme: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'An error occurred while updating the theme.']);
}
?>
