<?php
function runMatchingAlgorithm($conn, $lost_id = null, $found_id = null) {
    // Get items to match
    if ($lost_id) {
        $lost_query = "SELECT * FROM lost_items WHERE id = $lost_id AND status = 'pending'";
    } else {
        $lost_query = "SELECT * FROM lost_items WHERE status = 'pending'";
    }
    $lost_result = $conn->query($lost_query);

    while ($lost = $lost_result->fetch_assoc()) {
        $found_query = "SELECT * FROM found_items WHERE status = 'pending'";
        if ($found_id) $found_query .= " AND id = $found_id";
        $found_result = $conn->query($found_query);

        while ($found = $found_result->fetch_assoc()) {
            // Skip if match already exists
            $check = $conn->query("SELECT id FROM matches WHERE lost_item_id = {$lost['id']} AND found_item_id = {$found['id']}");
            if ($check->num_rows > 0) continue;

            $score = 0;
            // Category match
            if (!empty($lost['category']) && !empty($found['category']) && strtolower($lost['category']) === strtolower($found['category'])) $score += 30;
            // Location match
            if (!empty($lost['location']) && !empty($found['location']) && stripos($found['location'], $lost['location']) !== false) $score += 25;
            // Item name similarity
            similar_text(strtolower($lost['item_name']), strtolower($found['item_name']), $name_pct);
            if ($name_pct >= 60) $score += 30;
            elseif ($name_pct >= 40) $score += 15;
            // Description keyword match
            if (!empty($lost['description']) && !empty($found['description'])) {
                $lost_words = array_filter(explode(' ', strtolower($lost['description'])), fn($w) => strlen($w) > 3);
                $found_desc = strtolower($found['description']);
                $matched_words = 0;
                foreach ($lost_words as $word) {
                    if (strpos($found_desc, $word) !== false) $matched_words++;
                }
                if (count($lost_words) > 0) {
                    $desc_pct = ($matched_words / count($lost_words)) * 100;
                    if ($desc_pct >= 50) $score += 15;
                }
            }

            if ($score >= 40) {
                $conn->query("INSERT INTO matches (lost_item_id, found_item_id, match_score) VALUES ({$lost['id']}, {$found['id']}, $score)");
                // Notify users
                createNotification($conn, $lost['user_id'], "A possible match was found for your lost item: {$lost['item_name']}. Score: $score%", 'match');
                createNotification($conn, $found['user_id'], "Your found item: {$found['item_name']} may match a lost item report.", 'match');
            }
        }
    }
}

function createNotification($conn, $user_id, $message, $type = 'general') {
    $message = $conn->real_escape_string($message);
    $conn->query("INSERT INTO notifications (user_id, message, notification_type) VALUES ($user_id, '$message', '$type')");
}

function sendSMS($conn, $phone, $message, $user_id = null) {
    $api_key = getSettingValue($conn, 'sms_api_key');
    $sender = getSettingValue($conn, 'sms_sender') ?: 'RELINK';
    $enabled = getSettingValue($conn, 'sms_enabled');

    $status = 'pending';
    if ($enabled == '1' && !empty($api_key) && !empty($phone)) {
        // Semaphore SMS API
        $data = ['apikey' => $api_key, 'number' => $phone, 'message' => $message, 'sendername' => $sender];
        $ch = curl_init('https://api.semaphore.co/api/v4/messages');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        $status = $response ? 'sent' : 'failed';
    }

    $msg = $conn->real_escape_string($message);
    $ph = $conn->real_escape_string($phone);
    $uid = $user_id ? $user_id : 'NULL';
    $conn->query("INSERT INTO sms_logs (user_id, phone, message, status) VALUES ($uid, '$ph', '$msg', '$status')");
    return $status;
}

function getSettingValue($conn, $key) {
    $key = $conn->real_escape_string($key);
    $r = $conn->query("SELECT setting_value FROM settings WHERE setting_key = '$key'");
    if ($r && $r->num_rows > 0) return $r->fetch_assoc()['setting_value'];
    return '';
}

function getUnreadCount($conn, $user_id) {
    $r = $conn->query("SELECT COUNT(*) as c FROM notifications WHERE user_id = $user_id AND status = 'unread'");
    return $r->fetch_assoc()['c'];
}

function uploadImage($file, $folder = 'uploads/') {
    $allowed = ['jpg','jpeg','png'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowed)) return false;
    if ($file['size'] > 5 * 1024 * 1024) return false;
    $filename = uniqid('img_') . '.' . $ext;
    $dest = $folder . $filename;
    $root = rtrim($_SERVER['DOCUMENT_ROOT'], '/\\');
    $abs_dest = $root . '/lostfound_relink/' . $dest;
    if (!is_dir(dirname($abs_dest))) mkdir(dirname($abs_dest), 0755, true);
    if (move_uploaded_file($file['tmp_name'], $abs_dest)) return $dest;
    return false;
}

function logActivity($conn, $action, $entity_type = null, $entity_id = null, $description = null) {
    if (!isset($_SESSION['user_id'])) return false;
    
    $admin_id = $_SESSION['user_id'];
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    $action = $conn->real_escape_string($action);
    $entity_type = $entity_type ? $conn->real_escape_string($entity_type) : null;
    $description = $description ? $conn->real_escape_string($description) : null;
    
    $query = "INSERT INTO activity_logs (admin_id, action, entity_type, entity_id, description, ip_address, user_agent) VALUES 
              ($admin_id, '$action', " . ($entity_type ? "'$entity_type'" : "NULL") . ", " . ($entity_id ? $entity_id : "NULL") . ", " . ($description ? "'$description'" : "NULL") . ", '$ip_address', '$user_agent')";
    
    return $conn->query($query);
}

// ========== FACEBOOK SHARE FUNCTIONS ==========

/**
 * Generate a shareable URL for an item
 * @param int $item_id - The item ID
 * @param string $item_type - Either 'lost' or 'found'
 * @param string $item_name - The item name
 * @return string - The full shareable URL
 */
function generateShareUrl($item_id, $item_type, $item_name) {
    // Get the base URL
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $base_url = $protocol . '://' . $_SERVER['HTTP_HOST'];
    
    // Generate SEO-friendly slug from item name
    $slug = sanitizeSlug($item_name);
    
    // Create the share URL with query parameters
    $share_url = $base_url . '/lostfound_relink/public/browse.php' . 
                 '?view=' . urlencode($item_type) . 
                 '&id=' . urlencode($item_id) . 
                 '&shared=1';
    
    return $share_url;
}

/**
 * Create an SEO-friendly slug from a string
 * @param string $string - The string to slugify
 * @return string - The slugified string
 */
function sanitizeSlug($string) {
    // Convert to lowercase
    $string = strtolower($string);
    
    // Remove special characters and replace spaces with hyphens
    $string = preg_replace('/[^a-z0-9\s-]/', '', $string);
    $string = preg_replace('/[\s-]+/', '-', $string);
    $string = trim($string, '-');
    
    // Limit to 50 characters for URL safety
    return substr($string, 0, 50);
}

/**
 * Generate Facebook Share URL with all item details
 * @param array $item - The item data array
 * @param string $item_type - Either 'lost' or 'found'
 * @return string - The Facebook share URL
 */
function generateFacebookShareUrl($item, $item_type) {
    // Generate the item detail share URL
    $share_url = generateShareUrl($item['id'], $item_type, $item['item_name']);
    
    // Prepare share parameters
    $share_params = [
        'u' => $share_url,  // The URL to share
        'quote' => generateShareQuote($item, $item_type)
    ];
    
    // Build Facebook Share URL
    $facebook_share_url = 'https://www.facebook.com/sharer/sharer.php?' . 
                          http_build_query($share_params);
    
    return $facebook_share_url;
}

/**
 * Generate a compelling quote for Facebook share
 * @param array $item - The item data array
 * @param string $item_type - Either 'lost' or 'found'
 * @return string - The share quote
 */
function generateShareQuote($item, $item_type) {
    $type_text = ($item_type === 'lost') ? '🔍 LOST ITEM' : '📦 FOUND ITEM';
    
    $quote = $type_text . ": {$item['item_name']}\n";
    $quote .= "📂 Category: {$item['category']}\n";
    $quote .= "📍 Location: {$item['location']}\n";
    
    if (!empty($item['date_lost'])) {
        $date = new DateTime($item['date_lost']);
        $quote .= "📅 Date: " . $date->format('M d, Y') . "\n";
    } elseif (!empty($item['date_found'])) {
        $date = new DateTime($item['date_found']);
        $quote .= "📅 Date Found: " . $date->format('M d, Y') . "\n";
    }
    
    $quote .= "\n🔗 Help reunite lost items - Check RELINK Lost & Found System";
    
    return $quote;
}

/**
 * Get the default placeholder image for sharing
 * @param string $item_type - Either 'lost' or 'found'
 * @return string - The path to the placeholder image
 */
function getPlaceholderImage($item_type) {
    if ($item_type === 'lost') {
        return '/lostfound_relink/assets/images/placeholder-lost.png';
    } else {
        return '/lostfound_relink/assets/images/placeholder-found.png';
    }
}

