<?php
//ini_set("display_errors",1);
//error_reporting(E_ALL);

define('TOKENS_FILE', 'tokens.json');
define('JOBS_CACHE_FILE', 'jobs_cache.json');
define('PROMPT_CONFIG_FILE', 'prompt_config.json');

require __DIR__ . '/vendor/autoload.php';

$client_id = "85ccd1109e8d9b4ff2b57a8881e234f1";
$client_secret = "1c5fbf61c3091e52";
$openai_api_key = "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";

// Load prompt configuration from JSON file
function loadPromptConfig() {
    $defaultConfig = [
        'temperature' => 0.6,
        'max_tokens' => 800,
        'model' => 'gpt-4o',
        'prompt' => '',
        'system_message' => 'You are Mohammad, a freelance developer writing Upwork proposals. Write like a real person - casual, confident, direct.'
    ];

    if (file_exists(PROMPT_CONFIG_FILE)) {
        $config = json_decode(file_get_contents(PROMPT_CONFIG_FILE), true);
        if ($config) {
            return array_merge($defaultConfig, $config);
        }
    }
    return $defaultConfig;
}

// Save prompt configuration to JSON file
function savePromptConfig($config) {
    return file_put_contents(PROMPT_CONFIG_FILE, json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

// Handle save config AJAX request
if (isset($_POST['action']) && $_POST['action'] === 'save_config') {
    header('Content-Type: application/json');

    $config = [
        'temperature' => floatval($_POST['temperature'] ?? 0.6),
        'max_tokens' => intval($_POST['max_tokens'] ?? 800),
        'model' => $_POST['model'] ?? 'gpt-4o',
        'prompt' => $_POST['prompt'] ?? '',
        'system_message' => $_POST['system_message'] ?? ''
    ];

    if (savePromptConfig($config)) {
        echo json_encode(['success' => true, 'message' => 'Settings saved successfully!']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to save settings.']);
    }
    exit;
}

// Load current config
$promptConfig = loadPromptConfig();

$coverLetterPrompt = <<<PROMPT
Write an Upwork proposal that sounds like a real person wrote it.

STEP 1 - ANALYZE THE JOB FIRST:
Before writing, identify:
- Any geographic/market indicators (country, region, timezone)
- Any pain points or frustrations mentioned
- The core technical requirements
- Industry or business type

STEP 2 - CHOOSE YOUR OPENING (pick ONE based on your analysis):

A) DIRECT QUESTION - Use when job mentions problems, frustrations, or goals:
   Open with a question that hits their pain point.
   Examples: "Ever felt like your CRM setup is holding back your team?" or "What if your Zoho workflows actually worked the way you expected?"

B) CONFIDENT CLAIM - Use for clear technical tasks with specific requirements:
   Open with direct confidence.
   Examples: "This is exactly the kind of work I handle regularly." or "I've reviewed your requirements and this is a solid fit."

C) RELEVANCE HOOK - Use when job mentions specific market, region, or industry:
   Open with specific relevance.
   Example: "Would you like to connect with someone who has delivered similar solutions for [their market/industry]?"

NEVER open with: "It sounds like...", "You're looking for...", "You need...", "You want...", or by restating/summarizing their job description.

STEP 3 - BODY (2-3 short paragraphs):
- Reference ONLY the experience that's relevant to THIS specific job
- If industry matches, mention 1-2 similar clients I've worked with
- Keep paragraphs 2-3 lines max
- No bullet points, emojis, or asterisks
- Skip greetings like "Hi there"

STEP 4 - CLOSE:
- One simple question inviting a reply
- Sign off with "Thanks, Mohammad" on a new line

MY BACKGROUND (only mention what's RELEVANT to this job - don't list everything):

Primary expertise:
- Zoho platform: CRM, Creator, Books, Desk, Flow, Analytics, Zoho One
- Advanced Zoho widgets (React.js based)

Backend & Development:
- Node.js, API integrations, AI automation
- Databases: MySQL, PostgreSQL, MongoDB
- PHP background
- AWS / Linux VPS infrastructure

Past clients (mention 1-2 if industry matches):
Prime Dumpster, ParcelPlanet, Avison Young, Montevista Homes, Harlem Property Management, NJ Solar, Casper Street, HD Ships, Rapid Surplus Funds

Industries: real estate, logistics, construction, solar, healthcare, automotive, e-commerce

CRITICAL WRITING RULES:
- Write like a real person having a casual professional conversation
- Sound confident but not salesy
- Each proposal must feel UNIQUE - vary sentence structure, word choice, and flow
- Don't use: unleash, leverage, tailored, transform, game-changer, seamless, robust, cutting-edge, innovative, revolutionary, passionate, chaos, thrilled, excited
- No car/driving metaphors or dramatic opening lines
- No template placeholders or brackets
- Say "I specialize in..." or "I've been doing this work for companies like..." instead of mentioning specific years of experience
- Avoid starting multiple sentences the same way
- Mix up paragraph lengths
- The reader should NOT feel like they're reading a template

Here is the job description:
PROMPT;

function loadTokens()
{
    if (!file_exists(TOKENS_FILE)) {
        die("ERROR: tokens.json not found. Please run 'php setup.php' first.");
    }
    
    $data = json_decode(file_get_contents(TOKENS_FILE), true);
    if (!$data || !isset($data['access_token']) || !isset($data['refresh_token']) || !isset($data['expires_in'])) {
        die("ERROR: Invalid tokens.json file.");
    }
    
    return $data;
}

function saveTokens($tokenInfo)
{
    file_put_contents(TOKENS_FILE, json_encode($tokenInfo, JSON_PRETTY_PRINT));
}

function getJobDetails($jobId)
{
    if (!file_exists(JOBS_CACHE_FILE)) {
        return null;
    }
    
    $cache = json_decode(file_get_contents(JOBS_CACHE_FILE), true);
    
    if (!$cache || !isset($cache[$jobId])) {
        return null;
    }
    
    $jobData = $cache[$jobId];
    $job = (object) [
        'id' => $jobData['id'] ?? $jobId,
        'title' => $jobData['title'] ?? 'Untitled Job',
        'description' => $jobData['description'] ?? '',
        'createdDateTime' => $jobData['createdDateTimeUtc'] ?? $jobData['createdDateTime'] ?? null,
        'skills' => [],
        'category' => $jobData['category'] ?? null,
        'specialty' => $jobData['specialty'] ?? null,
        'occupations' => $jobData['occupations'] ?? [],
        'contract' => json_decode(json_encode($jobData['contract'] ?? new stdClass()), false),
        'client' => json_decode(json_encode($jobData['client'] ?? new stdClass()), false),
        'activity' => json_decode(json_encode($jobData['activity'] ?? new stdClass()), false),
    ];

    $skills = $jobData['skills'] ?? [];
    if ($skills && is_array($skills)) {
        $normalized = array_map(function ($skill) {
            if (is_string($skill)) {
                return (object)['name' => $skill];
            }
            if (is_array($skill)) {
                return (object)$skill;
            }
            return (object)['name' => $skill->name ?? $skill->preferredLabel ?? ''];
        }, $skills);
        $job->skills = array_filter($normalized, fn($skill) => !empty($skill->name));
    }

    return $job;
}

function formatTimeline(?string $isoString): ?string
{
    if (!$isoString) {
        return null;
    }

    try {
        $utc = new DateTime($isoString, new DateTimeZone('UTC'));
        $utc->setTimezone(new DateTimeZone('Asia/Karachi'));
        return $utc->format('Y-m-d h:i A') . ' PKT';
    } catch (Exception $e) {
        return $isoString;
    }
}

function formatMoneyFromCache(?array $money, string $suffix = ''): ?string
{
    if (!$money) {
        return null;
    }

    $display = $money['display'] ?? null;
    if (!$display && isset($money['raw'])) {
        $display = number_format((float)$money['raw'], 2);
    }

    if (isset($money['raw']) && (float)$money['raw'] <= 0) {
        return null;
    }

    if (!$display) {
        return null;
    }

    if (!empty($money['currency']) && strpos($display, $money['currency']) !== 0) {
        $display = $money['currency'] . ' ' . $display;
    }

    if ($suffix) {
        $display .= $suffix;
    }

    return $display;
}

function formatBudgetSummary($contract): ?string
{
    if (!$contract) {
        return null;
    }

    $type = $contract->type ?? null;

    if (in_array($type, ['FIXED_PRICE', 'FIXED'], true) && !empty($contract->fixedAmount)) {
        return formatMoneyFromCache((array)$contract->fixedAmount);
    }

    if ($type === 'HOURLY') {
        $min = !empty($contract->hourlyMin) ? formatMoneyFromCache((array)$contract->hourlyMin, '/hr') : null;
        $max = !empty($contract->hourlyMax) ? formatMoneyFromCache((array)$contract->hourlyMax, '/hr') : null;

        if ($min && $max && $min !== $max) {
            return $min . ' - ' . $max;
        }

        return $min ?? $max;
    }

    if (!empty($contract->weeklyBudget)) {
        return formatMoneyFromCache((array)$contract->weeklyBudget, ' /week');
    }

    return null;
}

function formatContractLabelForView($contract): ?string
{
    if (!$contract) {
        return null;
    }

    $parts = [];

    if (!empty($contract->type)) {
        $parts[] = ucwords(strtolower(str_replace('_', ' ', $contract->type)));
    }

    if (!empty($contract->experienceLevel)) {
        $parts[] = ucwords(strtolower(str_replace('_', ' ', $contract->experienceLevel)));
    }

    return $parts ? implode(' • ', $parts) : null;
}

function generateCoverLetter($jobDescription, $prompt)
{
    global $openai_api_key, $promptConfig;

    $fullPrompt = $prompt . "\n\n" . $jobDescription;

    $data = [
        'model' => $promptConfig['model'] ?? 'gpt-4o',
        'messages' => [
            [
                'role' => 'system',
                'content' => $promptConfig['system_message'] ?? 'You are Mohammad, a freelance developer writing Upwork proposals. Write like a real person - casual, confident, direct.'
            ],
            [
                'role' => 'user',
                'content' => $fullPrompt
            ]
        ],
        'temperature' => floatval($promptConfig['temperature'] ?? 0.6),
        'max_tokens' => intval($promptConfig['max_tokens'] ?? 800)
    ];
    
    $ch = curl_init('https://api.openai.com/v1/chat/completions');
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $openai_api_key
    ]);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    
    $response = curl_exec($ch);
    $curlError = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($curlError) {
        return "Error: Network timeout or connection failed. Please try again.\n\nDetails: {$curlError}";
    }
    
    if ($response === false) {
        return "Error: Failed to get response from OpenAI. Please try again.";
    }
    
    if ($httpCode !== 200) {
        $errorMsg = "API Error (HTTP {$httpCode})";
        $result = json_decode($response, true);
        if (isset($result['error']['message'])) {
            $errorMsg .= ": " . $result['error']['message'];
        }
        return $errorMsg;
    }
    
    $result = json_decode($response, true);
    
    if (!isset($result['choices'][0]['message']['content'])) {
        return "Error: Invalid response from OpenAI. Please try again.";
    }
    
    return $result['choices'][0]['message']['content'];
}

$jobId = $_GET['job_id'] ?? null;
$coverLetter = null;
$job = null;
$error = null;
$isGenerating = false;

if ($jobId) {
    $job = getJobDetails($jobId);

    if (!$job) {
        $error = "Could not fetch job details. The job may not exist or the API failed.";
    } else {
        // Check if client is from India or Pakistan
        $clientCountry = strtolower(trim($job->client->country ?? ''));
        $clientCity = strtolower(trim($job->client->city ?? ''));
        $clientState = strtolower(trim($job->client->state ?? ''));

        // Check if India or Pakistan appears in any location field
        $locationString = $clientCountry . ' ' . $clientCity . ' ' . $clientState;
        $isBlocked = false;
        $blockedCountry = '';

        if (stripos($locationString, 'india') !== false) {
            $isBlocked = true;
            $blockedCountry = 'India';
        } elseif (stripos($locationString, 'pakistan') !== false) {
            $isBlocked = true;
            $blockedCountry = 'Pakistan';
        }

        if ($isBlocked) {
            $error = "⚠️ Skipping this job - Client location is " . $blockedCountry . ". You've configured the system to skip jobs from India and Pakistan.";
        } elseif (!isset($_GET['generate']) && !isset($_POST['generate'])) {
            $isGenerating = false;
        } else {
            $isGenerating = true;
            set_time_limit(60);
            $jobDescription = $_POST['job_description'] ?? $job->description;
            $refinementInstructions = $_POST['refinement_instructions'] ?? '';

            $finalPrompt = $coverLetterPrompt;
            if (!empty($refinementInstructions)) {
                $finalPrompt .= "\n\nADDITIONAL INSTRUCTIONS FOR THIS PROPOSAL:\n" . $refinementInstructions;
            }

            $coverLetter = generateCoverLetter($jobDescription, $finalPrompt);
        }
    }
} else {
    $error = "No job ID provided.";
}

$initialInstructions = $_POST['refinement_instructions'] ?? '';
$contractLabel = null;
$budgetSummary = null;
$clientSpend = null;
$clientRatingSummary = null;
$clientLocationSummary = null;
$paymentStatusSummary = null;
$avgBidSummary = null;
$lastActivitySummary = null;
$totalApplicantsSummary = null;
$totalHiresSummary = null;

if ($job) {
    $contractLabel = formatContractLabelForView($job->contract ?? null);
    $budgetSummary = formatBudgetSummary($job->contract ?? null);

    if (!empty($job->client->totalSpent)) {
        $clientSpend = formatMoneyFromCache((array)$job->client->totalSpent);
    }

    if (!empty($job->client->totalFeedback)) {
        $rating = number_format((float)$job->client->totalFeedback, 1);
        $reviews = $job->client->totalReviews ?? 0;
        $clientRatingSummary = $rating . '/5';
        if ($reviews) {
            $clientRatingSummary .= ' (' . $reviews . ' reviews)';
        }
    }

    $locationParts = array_filter([
        $job->client->city ?? null,
        $job->client->state ?? null,
        $job->client->country ?? null,
    ]);
    if ($locationParts) {
        $clientLocationSummary = implode(', ', $locationParts);
        if (!empty($job->client->timezone)) {
            $clientLocationSummary .= ' (' . $job->client->timezone . ')';
        }
    }

    $verificationParts = [];
    if (!empty($job->client->verificationStatus)) {
        $verificationParts[] = str_replace('_', ' ', ucfirst(strtolower($job->client->verificationStatus)));
    }
    if (isset($job->client->paymentVerified)) {
        $verificationParts[] = $job->client->paymentVerified ? 'Payment verified' : 'Payment unverified';
    }
    if ($verificationParts) {
        $paymentStatusSummary = implode(' • ', $verificationParts);
    }

    if (!empty($job->activity->avgBid)) {
        $avgBidSummary = formatMoneyFromCache((array)$job->activity->avgBid, '/hr');
    }

    if (!empty($job->activity->totalApplicants)) {
        $totalApplicantsSummary = (string)$job->activity->totalApplicants;
    }

    if (!empty($job->client->totalHires)) {
        $totalHiresSummary = (string)$job->client->totalHires;
    }

    if (!empty($job->activity->lastClientActivity)) {
        $lastActivitySummary = formatTimeline($job->activity->lastClientActivity);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upwork Cover Letter Generator</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 10px;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            overflow: hidden;
        }

        @media (max-width: 768px) {
            body {
                padding: 5px;
            }

            .container {
                border-radius: 8px;
            }
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }

        .header h1 {
            font-size: 24px;
            margin-bottom: 8px;
        }

        .header p {
            opacity: 0.9;
            font-size: 13px;
        }

        .content {
            padding: 15px;
        }

        @media (min-width: 768px) {
            .header {
                padding: 30px;
            }

            .header h1 {
                font-size: 28px;
                margin-bottom: 10px;
            }

            .header p {
                font-size: 14px;
            }

            .content {
                padding: 30px;
            }
        }
        
        .job-section {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            border-left: 4px solid #667eea;
        }

        .job-title {
            font-size: 18px;
            color: #2d3748;
            margin-bottom: 12px;
            font-weight: 600;
            line-height: 1.4;
        }

        @media (min-width: 768px) {
            .job-section {
                border-radius: 12px;
                padding: 25px;
                margin-bottom: 30px;
            }

            .job-title {
                font-size: 22px;
                margin-bottom: 15px;
            }
        }
        
        .job-meta {
            display: flex;
            gap: 8px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }

        .meta-item {
            background: white;
            padding: 6px 10px;
            border-radius: 6px;
            font-size: 11px;
            color: #4a5568;
        }

        @media (min-width: 768px) {
            .job-meta {
                gap: 15px;
                margin-bottom: 20px;
            }

            .meta-item {
                padding: 8px 15px;
                font-size: 13px;
            }
        }
        
        .job-description {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-top: 15px;
            max-height: 300px;
            overflow-y: auto;
            line-height: 1.6;
            color: #4a5568;
            font-size: 14px;
        }
        
        .job-description-edit {
            width: 100%;
            min-height: 200px;
            max-height: 400px;
            padding: 15px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            font-family: inherit;
            font-size: 14px;
            line-height: 1.6;
            color: #4a5568;
            resize: vertical;
            margin-top: 15px;
        }
        
        .job-description-edit:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .edit-hint {
            font-size: 12px;
            color: #718096;
            margin-top: 8px;
            font-style: italic;
        }
        
        .refinement-box {
            background: #fffbeb;
            border: 2px solid #fbbf24;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
        }

        .refinement-title {
            font-size: 14px;
            font-weight: 600;
            color: #92400e;
            margin-bottom: 8px;
        }

        @media (min-width: 768px) {
            .refinement-box {
                padding: 20px;
                margin-bottom: 20px;
            }

            .refinement-title {
                font-size: 16px;
                margin-bottom: 10px;
            }
        }
        
        .refinement-input {
            width: 100%;
            min-height: 80px;
            padding: 12px;
            border: 2px solid #fbbf24;
            border-radius: 6px;
            font-family: inherit;
            font-size: 14px;
            line-height: 1.5;
            color: #1f2937;
            resize: vertical;
        }
        
        .refinement-input:focus {
            outline: none;
            border-color: #f59e0b;
        }
        
        .refinement-hint {
            font-size: 12px;
            color: #92400e;
            margin-top: 8px;
        }
        
        .cover-letter-section {
            background: #fff;
            border-radius: 8px;
            padding: 15px;
            border: 2px solid #667eea;
        }

        .section-title {
            font-size: 18px;
            color: #2d3748;
            margin-bottom: 15px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        @media (min-width: 768px) {
            .cover-letter-section {
                border-radius: 12px;
                padding: 25px;
            }

            .section-title {
                font-size: 20px;
                margin-bottom: 20px;
                gap: 10px;
            }
        }
        
        .cover-letter-text {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            line-height: 1.8;
            color: #2d3748;
            white-space: pre-wrap;
            font-size: 15px;
            min-height: 200px;
        }
        
        .actions {
            margin-top: 20px;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .btn {
            padding: 10px 18px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            border: none;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }

        @media (min-width: 768px) {
            .actions {
                margin-top: 25px;
                gap: 15px;
            }

            .btn {
                padding: 12px 25px;
                font-size: 15px;
            }
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .btn-secondary {
            background: #e2e8f0;
            color: #4a5568;
        }
        
        .btn-secondary:hover {
            background: #cbd5e0;
        }
        
        .error {
            background: #fed7d7;
            color: #c53030;
            padding: 20px;
            border-radius: 8px;
            border-left: 4px solid #c53030;
        }

        .warning {
            background: #fef3c7;
            color: #92400e;
            padding: 20px;
            border-radius: 8px;
            border-left: 4px solid #f59e0b;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #667eea;
        }
        
        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* Header layout */
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            flex-wrap: wrap;
            gap: 15px;
        }

        .header-text {
            flex: 1;
        }

        .btn-settings {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px 16px;
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            white-space: nowrap;
        }

        .btn-settings:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: translateY(-1px);
        }

        /* Modal styles */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
            z-index: 1000;
            justify-content: center;
            align-items: center;
            padding: 20px;
            box-sizing: border-box;
        }

        .modal-overlay.active {
            display: flex;
        }

        .modal {
            background: white;
            border-radius: 12px;
            width: 100%;
            max-width: 800px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 25px;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            border-radius: 12px 12px 0 0;
        }

        .modal-header h2 {
            margin: 0;
            font-size: 20px;
            color: #1a202c;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 28px;
            cursor: pointer;
            color: #718096;
            padding: 0;
            line-height: 1;
        }

        .modal-close:hover {
            color: #e53e3e;
        }

        .modal-body {
            padding: 25px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            margin-bottom: 8px;
            color: #2d3748;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            font-family: inherit;
            box-sizing: border-box;
            transition: border-color 0.3s ease;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .form-group textarea {
            min-height: 300px;
            resize: vertical;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            font-size: 13px;
            line-height: 1.5;
        }

        .form-group small {
            display: block;
            margin-top: 5px;
            color: #718096;
            font-size: 12px;
        }

        .form-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
        }

        .modal-footer {
            padding: 20px 25px;
            border-top: 1px solid #e2e8f0;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            background: #f8fafc;
            border-radius: 0 0 12px 12px;
        }

        .btn-cancel {
            padding: 10px 20px;
            background: #e2e8f0;
            color: #4a5568;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
        }

        .btn-cancel:hover {
            background: #cbd5e0;
        }

        .btn-save {
            padding: 10px 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
        }

        .btn-save:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        .toast {
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 15px 25px;
            border-radius: 8px;
            color: white;
            font-weight: 500;
            z-index: 1001;
            transform: translateY(100px);
            opacity: 0;
            transition: all 0.3s ease;
        }

        .toast.show {
            transform: translateY(0);
            opacity: 1;
        }

        .toast.success {
            background: #48bb78;
        }

        .toast.error {
            background: #e53e3e;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="header-content">
                <div class="header-text">
                    <h1>Upwork Cover Letter Generator</h1>
                    <p>AI-powered proposal writing for your Upwork jobs</p>
                </div>
                <button type="button" class="btn-settings" onclick="openSettingsModal()">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <circle cx="12" cy="12" r="3"></circle>
                        <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
                    </svg>
                    Change Prompt
                </button>
            </div>
        </div>
        
        <div class="content">
            <?php if ($error): ?>
                <?php
                // Check if it's a location-based skip (warning) or actual error
                $isWarning = strpos($error, '⚠️') !== false || stripos($error, 'skipping') !== false;
                $cssClass = $isWarning ? 'warning' : 'error';
                $label = $isWarning ? 'Notice:' : 'Error:';
                ?>
                <div class="<?php echo $cssClass; ?>">
                    <strong><?php echo $label; ?></strong> <?php echo htmlspecialchars($error); ?>
                </div>
            <?php elseif ($job): ?>
                <form id="coverLetterForm" method="POST">
                    <input type="hidden" name="generate" value="1">
                    <div class="job-section">
                        <div class="job-title"><?php echo htmlspecialchars($job->title); ?></div>
                        <div class="job-meta">
                            <span class="meta-item">Job ID: <?php echo htmlspecialchars($job->id); ?></span>
                            <?php if ($job->createdDateTime): ?>
                                <span class="meta-item">Posted: <?php echo htmlspecialchars(formatTimeline($job->createdDateTime)); ?></span>
                            <?php endif; ?>
                            <?php if ($contractLabel): ?>
                                <span class="meta-item">Contract: <?php echo htmlspecialchars($contractLabel); ?></span>
                            <?php endif; ?>
                            <?php if ($budgetSummary): ?>
                                <span class="meta-item">Budget: <?php echo htmlspecialchars($budgetSummary); ?></span>
                            <?php endif; ?>
                            <?php if ($clientSpend): ?>
                                <span class="meta-item">Client Spend: <?php echo htmlspecialchars($clientSpend); ?></span>
                            <?php endif; ?>
                            <?php if ($clientRatingSummary): ?>
                                <span class="meta-item">Client Rating: <?php echo htmlspecialchars($clientRatingSummary); ?></span>
                            <?php endif; ?>
                            <?php if ($totalHiresSummary): ?>
                                <span class="meta-item">Client Hires: <?php echo htmlspecialchars($totalHiresSummary); ?></span>
                            <?php endif; ?>
                            <?php if ($clientLocationSummary): ?>
                                <span class="meta-item">Location: <?php echo htmlspecialchars($clientLocationSummary); ?></span>
                            <?php endif; ?>
                            <?php if ($paymentStatusSummary): ?>
                                <span class="meta-item">Verification: <?php echo htmlspecialchars($paymentStatusSummary); ?></span>
                            <?php endif; ?>
                            <?php if ($avgBidSummary): ?>
                                <span class="meta-item">Avg Bid: <?php echo htmlspecialchars($avgBidSummary); ?></span>
                            <?php endif; ?>
                            <?php if ($totalApplicantsSummary): ?>
                                <span class="meta-item">Applicants: <?php echo htmlspecialchars($totalApplicantsSummary); ?></span>
                            <?php endif; ?>
                            <?php if ($lastActivitySummary): ?>
                                <span class="meta-item">Last Client Activity: <?php echo htmlspecialchars($lastActivitySummary); ?></span>
                            <?php endif; ?>
                            <?php if (isset($job->skills) && count($job->skills) > 0): ?>
                                <span class="meta-item">Skills: <?php echo htmlspecialchars(implode(', ', array_slice(array_map(fn($s) => $s->name, $job->skills), 0, 5))); ?></span>
                            <?php endif; ?>
                        </div>
                        <details open>
                            <summary style="cursor: pointer; color: #667eea; font-weight: 600; margin-top: 10px;">Job Description (Editable)</summary>
                            <textarea class="job-description-edit" name="job_description" id="jobDescription"><?php echo htmlspecialchars($_POST['job_description'] ?? $job->description); ?></textarea>
                            <div class="edit-hint">You can edit the job description above to refine specific parts before generating the cover letter.</div>
                        </details>
                    </div>
                    
                    <?php if ($coverLetter): ?>
                        <div class="refinement-box">
                            <div class="refinement-title">Refinement Instructions (Optional)</div>
                            <textarea class="refinement-input" name="refinement_instructions" placeholder="Example: Don't use the word 'struggling', make it more concise, focus on automation experience, etc."><?php echo htmlspecialchars($_POST['refinement_instructions'] ?? ''); ?></textarea>
                            <div class="refinement-hint">Add specific instructions here to refine the cover letter, then click Regenerate.</div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($coverLetter): ?>
                        <div class="cover-letter-section">
                            <div class="section-title">
                                Generated Cover Letter
                            </div>
                            <div class="cover-letter-text" id="coverLetter"><?php echo htmlspecialchars($coverLetter); ?></div>
                            <div class="actions">
                                <button class="btn btn-primary" type="button" onclick="copyToClipboard(event)">Copy to Clipboard</button>
                                <a href="https://www.upwork.com/jobs/~02<?php echo $job->id; ?>" target="_blank" class="btn btn-secondary">Open Job on Upwork</a>
                                <button class="btn btn-secondary" type="button" onclick="regenerateCoverLetter()">Regenerate</button>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="refinement-box" style="<?php echo $initialInstructions ? '' : 'display: none;'; ?>" id="initialRefinementBox">
                            <div class="refinement-title">Custom Instructions (Optional)</div>
                            <textarea class="refinement-input" name="refinement_instructions" placeholder="Example: Focus on real-estate experience, keep it under 150 words, emphasize API skills, etc."><?php echo htmlspecialchars($initialInstructions); ?></textarea>
                            <div class="refinement-hint">Add any specific instructions for the initial generation (optional).</div>
                        </div>
                        
                        <div class="cover-letter-section" style="text-align: center;">
                            <div class="section-title" style="text-align: center;">
                                Ready to Generate Your Cover Letter
                            </div>
                            <p style="color: #4a5568; margin-bottom: 30px;">Click the button below to generate an AI-powered cover letter tailored to this job. This takes about 5-10 seconds.</p>
                            <button class="btn btn-primary" type="button" onclick="generateCoverLetter()" style="font-size: 16px; padding: 15px 40px;">
                                Generate Cover Letter
                            </button>
                            <div style="margin-top: 15px;">
                                <a href="#" onclick="document.getElementById('initialRefinementBox').style.display='block'; return false;" style="color: #667eea; font-size: 13px; text-decoration: underline;">Add custom instructions</a>
                            </div>
                        </div>
                    <?php endif; ?>
                </form>
            <?php endif; ?>
            
            <div id="loadingOverlay" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 9999; justify-content: center; align-items: center;">
                <div style="background: white; padding: 40px; border-radius: 16px; text-align: center;">
                    <div class="spinner"></div>
                    <h3 style="color: #2d3748; margin: 0;">Generating Your Cover Letter...</h3>
                    <p style="color: #4a5568; margin-top: 10px;">Using AI to craft the perfect proposal</p>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        function generateCoverLetter() {
            document.getElementById('loadingOverlay').style.display = 'flex';
            document.getElementById('coverLetterForm').submit();
        }
        
        function regenerateCoverLetter() {
            document.getElementById('loadingOverlay').style.display = 'flex';
            document.getElementById('coverLetterForm').submit();
        }
        
        function copyToClipboard(event) {
            const coverLetterDiv = document.getElementById('coverLetter');
            const text = coverLetterDiv.innerText || coverLetterDiv.textContent;

            // Try modern clipboard API first
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(text).then(() => {
                    const btn = event.target;
                    const originalText = btn.textContent;
                    btn.textContent = 'Copied!';
                    btn.style.background = '#48bb78';
                    setTimeout(() => {
                        btn.textContent = originalText;
                        btn.style.background = '';
                    }, 2000);
                }).catch(err => {
                    // Fallback to execCommand
                    fallbackCopyToClipboard(text, event.target);
                });
            } else {
                // Use fallback for older browsers or non-secure contexts
                fallbackCopyToClipboard(text, event.target);
            }
        }

        function fallbackCopyToClipboard(text, btn) {
            const textarea = document.createElement('textarea');
            textarea.value = text;
            textarea.style.position = 'fixed';
            textarea.style.top = '0';
            textarea.style.left = '0';
            textarea.style.width = '2em';
            textarea.style.height = '2em';
            textarea.style.padding = '0';
            textarea.style.border = 'none';
            textarea.style.outline = 'none';
            textarea.style.boxShadow = 'none';
            textarea.style.background = 'transparent';
            document.body.appendChild(textarea);
            textarea.focus();
            textarea.select();

            try {
                const successful = document.execCommand('copy');
                if (successful) {
                    const originalText = btn.textContent;
                    btn.textContent = 'Copied!';
                    btn.style.background = '#48bb78';
                    setTimeout(() => {
                        btn.textContent = originalText;
                        btn.style.background = '';
                    }, 2000);
                } else {
                    alert('Failed to copy text. Please copy manually.');
                }
            } catch (err) {
                alert('Failed to copy: ' + err);
            }

            document.body.removeChild(textarea);
        }
    </script>

    <!-- Settings Modal -->
    <div id="settingsModal" class="modal-overlay" style="display: none;">
        <div class="modal">
            <div class="modal-header">
                <h2>Prompt Settings</h2>
                <button type="button" class="modal-close" onclick="closeSettingsModal()">&times;</button>
            </div>
            <form id="settingsForm" onsubmit="return saveSettings(event)">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="config_prompt">Prompt Template</label>
                        <textarea id="config_prompt" name="prompt" rows="12"><?php echo htmlspecialchars($promptConfig['prompt'] ?? ''); ?></textarea>
                        <small>The main instructions sent to the AI. Use this to define your proposal style.</small>
                    </div>

                    <div class="form-group">
                        <label for="config_system_message">System Message</label>
                        <textarea id="config_system_message" name="system_message" rows="3"><?php echo htmlspecialchars($promptConfig['system_message'] ?? ''); ?></textarea>
                        <small>Defines the AI's persona and overall behavior.</small>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="config_model">Model</label>
                            <select id="config_model" name="model">
                                <option value="gpt-4o" <?php echo ($promptConfig['model'] ?? '') === 'gpt-4o' ? 'selected' : ''; ?>>GPT-4o</option>
                                <option value="gpt-4o-mini" <?php echo ($promptConfig['model'] ?? '') === 'gpt-4o-mini' ? 'selected' : ''; ?>>GPT-4o Mini</option>
                                <option value="gpt-4-turbo" <?php echo ($promptConfig['model'] ?? '') === 'gpt-4-turbo' ? 'selected' : ''; ?>>GPT-4 Turbo</option>
                                <option value="gpt-3.5-turbo" <?php echo ($promptConfig['model'] ?? '') === 'gpt-3.5-turbo' ? 'selected' : ''; ?>>GPT-3.5 Turbo</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="config_temperature">Temperature</label>
                            <input type="number" id="config_temperature" name="temperature" min="0" max="2" step="0.1" value="<?php echo htmlspecialchars($promptConfig['temperature'] ?? '0.6'); ?>">
                            <small>0 = focused, 2 = creative</small>
                        </div>

                        <div class="form-group">
                            <label for="config_max_tokens">Max Tokens</label>
                            <input type="number" id="config_max_tokens" name="max_tokens" min="100" max="4000" step="50" value="<?php echo htmlspecialchars($promptConfig['max_tokens'] ?? '800'); ?>">
                            <small>Maximum response length</small>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-cancel" onclick="closeSettingsModal()">Cancel</button>
                    <button type="submit" class="btn-save">Save Settings</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Toast notification -->
    <div id="toast" class="toast"></div>

    <script>
        function openSettingsModal() {
            document.getElementById('settingsModal').style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }

        function closeSettingsModal() {
            document.getElementById('settingsModal').style.display = 'none';
            document.body.style.overflow = '';
        }

        function showToast(message, type) {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.className = 'toast ' + type + ' show';
            setTimeout(() => {
                toast.className = 'toast';
            }, 3000);
        }

        function saveSettings(event) {
            event.preventDefault();

            const form = document.getElementById('settingsForm');
            const formData = new FormData(form);
            formData.append('action', 'save_config');

            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('Settings saved successfully!', 'success');
                    closeSettingsModal();
                } else {
                    showToast('Error: ' + (data.error || 'Failed to save'), 'error');
                }
            })
            .catch(error => {
                showToast('Error saving settings: ' + error.message, 'error');
            });

            return false;
        }

        // Close modal when clicking outside
        document.getElementById('settingsModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeSettingsModal();
            }
        });

        // Close modal with Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeSettingsModal();
            }
        });
    </script>
</body>
</html>

