<?php
require_once __DIR__ . '/config/config.php';
session_start();
header('Content-Type: application/json');

// Optional: validate admin session here

$user_id = $_POST['user_id'];
$amount = $_POST['amount'];
$desc = $_POST['description'] ?? 'Weekly Credit';

if (!$user_id || !$amount || $amount <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid input.']);
    exit;
}

// Insert earnings log
$insert = $conn->prepare("INSERT INTO earnings (user_id, amount, description) VALUES (?, ?, ?)");
$insert->bind_param("ids", $user_id, $amount, $desc);
$insert->execute();
$insert->close();

// Update user balance
$update = $conn->prepare("UPDATE users SET account_balance = account_balance + ? WHERE id = ?");
$update->bind_param("di", $amount, $user_id);
$update->execute();
$update->close();

// Log admin action in activity_logs
$admin_id = $_SESSION['admin_id'] ?? null;

$action_type = 'credit_earning';
$log_desc = "You've received a weekly earning of \$$amount credited by an admin. Note: $desc";

$log = $conn->prepare("INSERT INTO activity_logs (user_id, actor, action_type, description) VALUES (?, 'admin', ?, ?)");
$log->bind_param("iss", $user_id, $action_type, $log_desc);
$log->execute();
$log->close();

echo json_encode(['success' => true, 'message' => 'Earnings credited successfully.']);
?>
