<?php
/**
 * Log Share Events for Analytics
 * This file logs when items are shared to social media platforms
 */

require_once 'db.php';

// Only accept POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}

// Sanitize input
$item_type = sanitize($conn, $_POST['item_type'] ?? '');
$item_id = (int)($_POST['item_id'] ?? 0);
$platform = sanitize($conn, $_POST['platform'] ?? '');

// Validate input
if (empty($item_type) || $item_id === 0 || empty($platform)) {
    http_response_code(400);
    error_log("Share log error: Invalid parameters - type: $item_type, id: $item_id, platform: $platform");
    exit('Bad Request');
}

// Validate item type
if (!in_array($item_type, ['lost', 'found'])) {
    http_response_code(400);
    error_log("Share log error: Invalid item_type: $item_type");
    exit('Invalid item type');
}

// Validate platform
if (!in_array($platform, ['facebook', 'twitter', 'linkedin', 'whatsapp', 'other'])) {
    http_response_code(400);
    error_log("Share log error: Invalid platform: $platform");
    exit('Invalid platform');
}

// Determine table name
$table = ($item_type === 'lost') ? 'lost_items' : 'found_items';

// Verify item exists
$check_query = "SELECT id FROM $table WHERE id = $item_id LIMIT 1";
$result = $conn->query($check_query);

if (!$result || $result->num_rows === 0) {
    http_response_code(404);
    error_log("Share log error: Item not found - table: $table, id: $item_id");
    exit('Item not found');
}

// Get user ID if logged in
$user_id = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : null;

// Get IP address and user agent
$ip_address = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$user_agent = substr($_SERVER['HTTP_USER_AGENT'] ?? 'unknown', 0, 255);

// Log the share event (write to error log for now - could be extended to database table)
$log_message = "SHARE_EVENT: " . json_encode([
    'timestamp' => date('Y-m-d H:i:s'),
    'platform' => $platform,
    'item_type' => $item_type,
    'item_id' => $item_id,
    'user_id' => $user_id,
    'ip_address' => $ip_address,
    'user_agent' => $user_agent
]);

error_log($log_message);

// Optional: Insert into a shares_log table if it exists
// This is commented out - uncomment if you create a shares_log table
/*
$insert_query = "INSERT INTO shares_log (user_id, item_type, item_id, platform, ip_address, user_agent, created_at) 
                 VALUES (" . ($user_id ? $user_id : "NULL") . ", '$item_type', $item_id, '$platform', '$ip_address', '$user_agent', NOW())";
if (!$conn->query($insert_query)) {
    error_log("Share log INSERT error: " . $conn->error);
}
*/

// Return success response
http_response_code(200);
header('Content-Type: application/json');
echo json_encode([
    'success' => true,
    'message' => 'Share event logged successfully',
    'timestamp' => date('Y-m-d H:i:s')
]);
