<?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 sendAccountApprovedEmail($conn, $to_email, $to_name) {
    $smtp_host = getSettingValue($conn, 'smtp_host') ?: 'smtp.gmail.com';
    $smtp_port = (int)(getSettingValue($conn, 'smtp_port') ?: 587);
    $smtp_user = getSettingValue($conn, 'smtp_user');
    $smtp_pass = getSettingValue($conn, 'smtp_pass');
    $from_name = getSettingValue($conn, 'site_name') ?: 'RELINK';

    if (empty($smtp_user) || empty($smtp_pass)) return false;

    $subject = "Your RELINK Account is Now Active!";
    $body = "
<!DOCTYPE html>
<html>
<body style='font-family:Arial,sans-serif;background:#f8fafc;margin:0;padding:0'>
<div style='max-width:520px;margin:40px auto;background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 4px 16px rgba(0,0,0,.08)'>
  <div style='background:linear-gradient(135deg,#1c3d00,#4f9d1c);padding:32px 24px;text-align:center'>
    <h1 style='color:#d4f06a;margin:0;font-size:28px;letter-spacing:1px'>🔗 RELINK</h1>
    <p style='color:rgba(255,255,255,.8);margin:6px 0 0;font-size:13px'>Cauayan City Hall Lost &amp; Found System</p>
  </div>
  <div style='padding:32px 28px'>
    <h2 style='color:#1e293b;margin:0 0 12px'>✅ Account Approved!</h2>
    <p style='color:#475569;font-size:15px;line-height:1.7'>Hi <strong>" . htmlspecialchars($to_name) . "</strong>,</p>
    <p style='color:#475569;font-size:15px;line-height:1.7'>Great news! Your RELINK account has been reviewed and <strong style='color:#4f9d1c'>approved by the administrator</strong>. You can now log in and start using the system.</p>
    <div style='text-align:center;margin:28px 0'>
      <a href='http://" . $_SERVER['HTTP_HOST'] . BASE_URL . "/auth/login.php' style='background:#4f9d1c;color:#fff;padding:14px 32px;border-radius:8px;text-decoration:none;font-weight:700;font-size:15px;display:inline-block'>Sign In Now →</a>
    </div>
    <p style='color:#94a3b8;font-size:12px;line-height:1.6'>If you did not register for this account, please ignore this email.</p>
  </div>
  <div style='background:#f1f5f9;padding:16px 28px;text-align:center'>
    <p style='color:#94a3b8;font-size:11px;margin:0'>© " . date('Y') . " RELINK — Cauayan City Hall. All rights reserved.</p>
  </div>
</div>
</body>
</html>";

    // SMTP send via stream (supports both port 465 SSL and port 587 STARTTLS)
    $errno = 0; $errstr = '';
    if ($smtp_port == 465) {
        $socket = fsockopen('ssl://' . $smtp_host, $smtp_port, $errno, $errstr, 10);
    } else {
        $socket = fsockopen($smtp_host, $smtp_port, $errno, $errstr, 10);
    }
    if (!$socket) return false;

    $read = function() use ($socket) {
        $data = '';
        while ($line = fgets($socket, 512)) {
            $data .= $line;
            if (substr($line, 3, 1) === ' ') break;
        }
        return $data;
    };
    $send = function($cmd) use ($socket) { fwrite($socket, $cmd . "\r\n"); };

    $read(); // 220 greeting
    $send('EHLO ' . ($_SERVER['HTTP_HOST'] ?? 'localhost'));
    $read();

    // Upgrade to TLS for port 587
    if ($smtp_port == 587) {
        $send('STARTTLS');
        $read();
        stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
        $send('EHLO ' . ($_SERVER['HTTP_HOST'] ?? 'localhost'));
        $read();
    }

    $send('AUTH LOGIN');
    $read();
    $send(base64_encode($smtp_user));
    $read();
    $send(base64_encode($smtp_pass));
    $r = $read();
    if (strpos($r, '235') === false) { fclose($socket); return false; }

    $send('MAIL FROM:<' . $smtp_user . '>');
    $read();
    $send('RCPT TO:<' . $to_email . '>');
    $read();
    $send('DATA');
    $read();

    $headers  = "From: {$from_name} <{$smtp_user}>\r\n";
    $headers .= "To: {$to_name} <{$to_email}>\r\n";
    $headers .= "Subject: {$subject}\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    $send($headers . "\r\n" . $body . "\r\n.");
    $read();
    $send('QUIT');
    fclose($socket);
    return true;
}

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 . BASE_URL . '/' . $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';
    }
}

