<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');
require_once 'db_config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = intval($_POST['user_id'] ?? 0);
    $items = $_POST['items'] ?? [];

    if (!$user_id || empty($items)) {
        echo json_encode(['status' => 'error', 'message' => '❌ Missing user or items.']);
        exit;
    }

    $stmt = $conn->prepare("SELECT fullname FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();

    if (!$user) {
        echo json_encode(['status' => 'error', 'message' => '❌ User not found.']);
        exit;
    }

    $checkStmt = $conn->prepare("SELECT id FROM promotional_materials WHERE user_id = ?");
    $checkStmt->bind_param("i", $user_id);
    $checkStmt->execute();
    if ($checkStmt->get_result()->num_rows > 0) {
        echo json_encode(['status' => 'error', 'message' => '⚠️ Already Collected.']);
        exit;
    }

    $material_collected = implode(", ", $items);
    $insertStmt = $conn->prepare("INSERT INTO promotional_materials (user_id, material_collected) VALUES (?, ?)");
    $insertStmt->bind_param("is", $user_id, $material_collected);

    if ($insertStmt->execute()) {
        $time = date("Y-m-d H:i:s");
        echo json_encode([
            'status' => 'success',
            'message' => "✅ Collected for {$user['fullname']}",
            'id' => $insertStmt->insert_id,
            'user_id' => $user_id,
            'fullname' => $user['fullname'],
            'material_collected' => $material_collected,
            'collection_time' => $time
        ]);
    } else {
        echo json_encode(['status' => 'error', 'message' => '❌ Failed to collect.']);
    }
}