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

try {
    if (!isset($_GET['query'])) {
        throw new Exception('Search query is required');
    }

    $mailbox = getMailboxConnection();
    $connection = $mailbox['connection'];
    
    $query = trim($_GET['query']);
    $folder = isset($_GET['folder']) ? $_GET['folder'] : 'INBOX';
    $searchType = isset($_GET['type']) ? $_GET['type'] : 'all';
    
    $folderPath = '{' . $mailbox['config']['imap_host'] . ':' . $mailbox['config']['imap_port'] . '/imap/ssl}' . $folder;
    imap_reopen($connection, $folderPath);

    $searchCriteria = '';
    switch ($searchType) {
        case 'subject':
            $searchCriteria = 'SUBJECT "' . $query . '"';
            break;
        case 'from':
            $searchCriteria = 'FROM "' . $query . '"';
            break;
        case 'to':
            $searchCriteria = 'TO "' . $query . '"';
            break;
        case 'body':
            $searchCriteria = 'BODY "' . $query . '"';
            break;
        default:
            $searchCriteria = 'TEXT "' . $query . '"';
    }

    $results = imap_search($connection, $searchCriteria, SE_UID, 'UTF-8');
    
    if (!$results) {
        echo json_encode([
            'success' => true,
            'messages' => [],
            'count' => 0
        ]);
        exit;
    }

    $messages = [];
    foreach ($results as $uid) {
        $header = imap_fetchheader($connection, $uid, FT_UID);
        $overview = imap_fetch_overview($connection, $uid, FT_UID)[0];
        $structure = imap_fetchstructure($connection, $uid, FT_UID);
        
        $hasAttachments = false;
        if (isset($structure->parts)) {
            foreach ($structure->parts as $part) {
                if ($part->ifdisposition && strtolower($part->disposition) == 'attachment') {
                    $hasAttachments = true;
                    break;
                }
            }
        }

        $from = isset($overview->from) ? imap_utf8($overview->from) : 'Unknown';
        if (preg_match('/^(.*?)\s*<(.+?)>$/', $from, $matches)) {
            $fromName = trim($matches[1]);
            $fromEmail = trim($matches[2]);
        } else {
            $fromName = '';
            $fromEmail = $from;
        }

        $messages[] = [
            'uid' => $uid,
            'subject' => isset($overview->subject) ? imap_utf8($overview->subject) : 'No Subject',
            'from' => [
                'name' => $fromName,
                'email' => $fromEmail
            ],
            'date' => date('Y-m-d H:i:s', strtotime($overview->date)),
            'size' => $structure->bytes,
            'seen' => $overview->seen,
            'flagged' => $overview->flagged,
            'hasAttachments' => $hasAttachments,
            'folder' => $folder,
            'preview' => mb_substr(strip_tags(imap_fetchbody($connection, $uid, 1, FT_UID)), 0, 150) . '...'
        ];
    }

    usort($messages, function($a, $b) {
        return strtotime($b['date']) - strtotime($a['date']);
    });

    echo json_encode([
        'success' => true,
        'messages' => $messages,
        'count' => count($messages),
        'query' => $query,
        'type' => $searchType,
        'folder' => $folder
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

if (isset($connection)) {
    imap_close($connection);
}