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

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

session_start();
$pdo = require_once __DIR__ . '/../../config/database.php';

$method = $_SERVER['REQUEST_METHOD'];

function response($data, $status = 200) {
    http_response_code($status);
    echo json_encode($data);
    exit;
}

function getJsonInput() {
    return json_decode(file_get_contents('php://input'), true);
}

function checkAuth() {
    if (empty($_SESSION['user_id'])) {
        response(['error' => 'Unauthorized'], 401);
    }
    return $_SESSION['user_id'];
}

// Get goals
if ($method === 'GET') {
    $userId = checkAuth();
    
    $stmt = $pdo->prepare('SELECT * FROM goals WHERE user_id = ?');
    $stmt->execute([$userId]);
    $goals = $stmt->fetch();
    
    if (!$goals) {
        response(['error' => 'Goals not found'], 404);
    }
    
    response(['goals' => $goals]);
}

// Update goals
elseif ($method === 'PUT') {
    $userId = checkAuth();
    $data = getJsonInput();
    
    if (empty($data['weekday_goal']) || empty($data['holiday_goal'])) {
        response(['error' => 'Missing required fields'], 400);
    }
    
    $stmt = $pdo->prepare('
        UPDATE goals 
        SET weekday_goal = ?, holiday_goal = ?, updated_at = NOW()
        WHERE user_id = ?
    ');
    
    $stmt->execute([
        (int)$data['weekday_goal'],
        (int)$data['holiday_goal'],
        $userId
    ]);
    
    response([
        'success' => true,
        'message' => 'Goals updated successfully'
    ]);
}

else {
    response(['error' => 'Method not allowed'], 405);
}
?>
