<?php
require_once '../../config.php';
require_once '../../functions.php';
require_once '../includes/ai_helper.php';

check_admin_auth();

$message = '';
$error = '';

// Handle AI Provider Save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_provider'])) {
    $provider = $_POST['provider'];
    $api_key = $_POST['api_key'];
    $model_name = $_POST['model_name'] ?? '';
    $status = $_POST['status'] ?? 'active';

    try {
        $stmt = $pdo->prepare("INSERT INTO ai_settings (provider, api_key, model_name, status) 
            VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE api_key=VALUES(api_key), model_name=VALUES(model_name), status=VALUES(status)");
        $stmt->execute([$provider, $api_key, $model_name, $status]);
        $message = "AI Provider '$provider' saved successfully!";
    } catch (PDOException $e) {
        $error = "Error: " . $e->getMessage();
    }
}

// Handle Training Data Save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_training'])) {
    $fields = [
        'business_name' => $_POST['business_name'] ?? '',
        'business_description' => $_POST['business_description'] ?? '',
        'business_type' => $_POST['business_type'] ?? '',
        'target_audience' => $_POST['target_audience'] ?? '',
        'brand_tone' => $_POST['brand_tone'] ?? 'professional',
        'key_products' => $_POST['key_products'] ?? '',
        'special_instructions' => $_POST['special_instructions'] ?? ''
    ];

    try {
        // Deactivate existing
        $pdo->exec("UPDATE ai_training SET status = 'inactive'");

        $stmt = $pdo->prepare("INSERT INTO ai_training (business_name, business_description, business_type, target_audience, brand_tone, key_products, special_instructions) VALUES (?,?,?,?,?,?,?)");
        $stmt->execute(array_values($fields));
        $message = "AI Training data saved! AI will now use this business context.";
    } catch (PDOException $e) {
        $error = "Error: " . $e->getMessage();
    }
}

// Fetch current settings
$providers = [];
try {
    $stmt = $pdo->query("SELECT * FROM ai_settings ORDER BY provider");
    $providers = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (PDOException $e) {
}

$gemini = null;
$chatgpt = null;
foreach ($providers as $p) {
    if ($p['provider'] === 'gemini')
        $gemini = $p;
    if ($p['provider'] === 'chatgpt')
        $chatgpt = $p;
}

$training = get_ai_training_data();

$pageTitle = "AI Settings - SMS Admin";
include '../includes/header.php';
include '../includes/sidebar.php';
include '../includes/navbar.php';
?>

<div class="page-header">
    <h1 class="page-title">🤖 AI Settings</h1>
    <div>
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
            <li class="breadcrumb-item active">AI Settings</li>
        </ol>
    </div>
</div>

<?php if ($message): ?>
    <div class="alert alert-success alert-dismissible fade show"><i
            class="fe fe-check-circle me-2"></i><?php echo htmlspecialchars($message); ?><button class="btn-close"
            data-bs-dismiss="alert"></button></div>
<?php endif; ?>
<?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show"><i
            class="fe fe-alert-triangle me-2"></i><?php echo htmlspecialchars($error); ?><button class="btn-close"
            data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<div class="row">
    <!-- Gemini Config -->
    <div class="col-xl-6 fade-in-up">
        <div class="card mb-4">
            <div class="card-header d-flex align-items-center">
                <span class="me-2" style="font-size:1.25rem;">💎</span>
                <h3 class="card-title mb-0">Google Gemini</h3>
                <?php if ($gemini && $gemini['status'] === 'active'): ?>
                    <span class="health-indicator health-good ms-auto">● Active</span>
                <?php else: ?>
                    <span class="health-indicator health-warn ms-auto">○ Inactive</span>
                <?php endif; ?>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="save_provider" value="1">
                    <input type="hidden" name="provider" value="gemini">
                    <div class="mb-3">
                        <label class="form-label">API Key</label>
                        <input type="password" name="api_key" class="form-control"
                            value="<?php echo htmlspecialchars($gemini['api_key'] ?? ''); ?>" placeholder="AIza...">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Model</label>
                        <select name="model_name" class="form-select">
                            <option value="gemini-2.0-flash" <?php echo ($gemini['model_name'] ?? '') === 'gemini-2.0-flash' ? 'selected' : ''; ?>>Gemini 2.0 Flash (Fast)</option>
                            <option value="gemini-2.5-pro" <?php echo ($gemini['model_name'] ?? '') === 'gemini-2.5-pro' ? 'selected' : ''; ?>>Gemini 2.5 Pro (Best)</option>
                            <option value="gemini-2.5-flash" <?php echo ($gemini['model_name'] ?? '') === 'gemini-2.5-flash' ? 'selected' : ''; ?>>Gemini 2.5 Flash</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="active" <?php echo ($gemini['status'] ?? '') === 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="inactive" <?php echo ($gemini['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-modern-primary flex-grow-1">Save Gemini</button>
                        <button type="button" class="btn btn-outline-primary test-btn"
                            data-provider="gemini">Test</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- ChatGPT Config -->
    <div class="col-xl-6 fade-in-up">
        <div class="card mb-4">
            <div class="card-header d-flex align-items-center">
                <span class="me-2" style="font-size:1.25rem;">🧠</span>
                <h3 class="card-title mb-0">OpenAI ChatGPT</h3>
                <?php if ($chatgpt && $chatgpt['status'] === 'active'): ?>
                    <span class="health-indicator health-good ms-auto">● Active</span>
                <?php else: ?>
                    <span class="health-indicator health-warn ms-auto">○ Inactive</span>
                <?php endif; ?>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="save_provider" value="1">
                    <input type="hidden" name="provider" value="chatgpt">
                    <div class="mb-3">
                        <label class="form-label">API Key</label>
                        <input type="password" name="api_key" class="form-control"
                            value="<?php echo htmlspecialchars($chatgpt['api_key'] ?? ''); ?>" placeholder="sk-...">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Model</label>
                        <select name="model_name" class="form-select">
                            <option value="gpt-4o-mini" <?php echo ($chatgpt['model_name'] ?? '') === 'gpt-4o-mini' ? 'selected' : ''; ?>>GPT-4o Mini (Fast)</option>
                            <option value="gpt-4o" <?php echo ($chatgpt['model_name'] ?? '') === 'gpt-4o' ? 'selected' : ''; ?>>GPT-4o (Best)</option>
                            <option value="gpt-4.1-mini" <?php echo ($chatgpt['model_name'] ?? '') === 'gpt-4.1-mini' ? 'selected' : ''; ?>>GPT-4.1 Mini</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="active" <?php echo ($chatgpt['status'] ?? '') === 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="inactive" <?php echo ($chatgpt['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-modern-primary flex-grow-1">Save ChatGPT</button>
                        <button type="button" class="btn btn-outline-primary test-btn"
                            data-provider="chatgpt">Test</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- AI Training Data -->
<div class="row">
    <div class="col-12 fade-in-up">
        <div class="card mb-4">
            <div class="card-header d-flex align-items-center">
                <span class="me-2" style="font-size:1.25rem;">🎓</span>
                <h3 class="card-title mb-0">AI Training — Business Context</h3>
                <span class="ai-badge ms-auto">AI BRAIN</span>
            </div>
            <div class="card-body">
                <div class="ai-panel mb-3">
                    <div class="ai-header">
                        <i class="fe fe-info"></i> Tell AI about your business so it can create better SMS templates
                        automatically
                    </div>
                </div>
                <form method="POST">
                    <input type="hidden" name="save_training" value="1">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Business Name *</label>
                            <input type="text" name="business_name" class="form-control"
                                value="<?php echo htmlspecialchars($training['business_name'] ?? ''); ?>" required
                                placeholder="e.g. KhatiFoodBazar">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Business Type</label>
                            <select name="business_type" class="form-select">
                                <option value="">Select...</option>
                                <?php
                                $types = ['Food & Beverage', 'E-commerce', 'Healthcare', 'Education', 'Retail', 'Fashion', 'Technology', 'Real Estate', 'Finance', 'Travel', 'Other'];
                                foreach ($types as $t): ?>
                                    <option value="<?php echo $t; ?>" <?php echo ($training['business_type'] ?? '') === $t ? 'selected' : ''; ?>><?php echo $t; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Brand Tone</label>
                            <select name="brand_tone" class="form-select">
                                <?php
                                $tones = ['professional', 'friendly', 'casual', 'urgent', 'luxurious', 'playful', 'formal', 'inspirational'];
                                foreach ($tones as $t): ?>
                                    <option value="<?php echo $t; ?>" <?php echo ($training['brand_tone'] ?? 'professional') === $t ? 'selected' : ''; ?>><?php echo ucfirst($t); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Business Description * <small class="text-muted">(Explain what your
                                business does in detail)</small></label>
                        <textarea name="business_description" class="form-control" rows="4" required
                            placeholder="We are a food delivery and catering service based in Dhaka..."><?php echo htmlspecialchars($training['business_description'] ?? ''); ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Target Audience</label>
                        <textarea name="target_audience" class="form-control" rows="2"
                            placeholder="Young professionals aged 25-40 in Dhaka city..."><?php echo htmlspecialchars($training['target_audience'] ?? ''); ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Key Products/Services</label>
                        <textarea name="key_products" class="form-control" rows="2"
                            placeholder="Biriyani, Naan, Kebab, Home delivery, Catering..."><?php echo htmlspecialchars($training['key_products'] ?? ''); ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Special Instructions for AI</label>
                        <textarea name="special_instructions" class="form-control" rows="3"
                            placeholder="Always mention free delivery for orders above 500tk. Use Bengali language for promotions..."><?php echo htmlspecialchars($training['special_instructions'] ?? ''); ?></textarea>
                    </div>
                    <button type="submit" class="btn btn-modern-success"><i class="fe fe-save me-2"></i>Save Training
                        Data</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Quick AI Test -->
<div class="row">
    <div class="col-12 fade-in-up">
        <div class="card mb-4">
            <div class="card-header d-flex align-items-center">
                <span class="me-2">✨</span>
                <h3 class="card-title mb-0">Quick AI Template Generator</h3>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label">What should the SMS be about?</label>
                            <input type="text" id="ai-quick-prompt" class="form-control"
                                placeholder="e.g. Eid special discount on all items">
                        </div>
                        <div class="row">
                            <div class="col-6 mb-3">
                                <label class="form-label">Language</label>
                                <select id="ai-quick-lang" class="form-select">
                                    <option value="English">English</option>
                                    <option value="Bengali">Bengali</option>
                                    <option value="Banglish">Banglish</option>
                                </select>
                            </div>
                            <div class="col-6 mb-3">
                                <label class="form-label">Max Characters</label>
                                <select id="ai-quick-limit" class="form-select">
                                    <option value="160">160 (1 SMS)</option>
                                    <option value="320">320 (2 SMS)</option>
                                    <option value="480">480 (3 SMS)</option>
                                </select>
                            </div>
                        </div>
                        <button type="button" id="ai-quick-gen" class="btn btn-ai-generate w-100">
                            <i class="fe fe-zap"></i> Generate SMS Template
                        </button>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Preview</label>
                        <div class="ai-preview-box" id="ai-quick-preview">
                            <span class="text-muted">AI-generated SMS will appear here...</span>
                        </div>
                        <div class="d-flex gap-2 mt-3">
                            <button type="button" id="ai-quick-save" class="btn btn-modern-success flex-grow-1"
                                disabled>
                                <i class="fe fe-save me-1"></i>Save as Template
                            </button>
                            <button type="button" id="ai-quick-regen" class="btn btn-outline-primary" disabled>
                                <i class="fe fe-refresh-cw"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
$extra_scripts = '
<script>
$(document).ready(function() {
    var lastGenerated = "";
    
    // Test Connection
    $(".test-btn").click(function() {
        var provider = $(this).data("provider");
        var form = $(this).closest("form");
        var apiKey = form.find("input[name=api_key]").val();
        var model = form.find("select[name=model_name]").val();
        var btn = $(this);
        
        btn.html("<i class=\"fe fe-loader spin\"></i>").prop("disabled", true);
        
        $.post("' . base_url('public/api/ai_generate.php') . '", {
            action: "test", provider: provider, api_key: apiKey, model: model
        }, function(r) {
            if (r.success) {
                btn.html("✅ Connected!").removeClass("btn-outline-primary").addClass("btn-success");
            } else {
                btn.html("❌ Failed").removeClass("btn-outline-primary").addClass("btn-danger");
                alert("Error: " + r.error);
            }
            setTimeout(function() {
                btn.html("Test").removeClass("btn-success btn-danger").addClass("btn-outline-primary").prop("disabled", false);
            }, 3000);
        }, "json").fail(function() {
            btn.html("❌ Error").prop("disabled", false);
        });
    });
    
    // Quick Generate
    function quickGenerate() {
        var prompt = $("#ai-quick-prompt").val();
        if (!prompt) { alert("Enter a topic first!"); return; }
        
        var btn = $("#ai-quick-gen");
        btn.html("<i class=\"fe fe-loader spin\"></i> Generating...").prop("disabled", true);
        
        $.post("' . base_url('public/api/ai_generate.php') . '", {
            action: "generate", prompt: prompt,
            language: $("#ai-quick-lang").val(),
            char_limit: $("#ai-quick-limit").val()
        }, function(r) {
            if (r.success) {
                lastGenerated = r.text;
                $("#ai-quick-preview").html("<p style=\"white-space:pre-wrap;margin:0;\">" + r.text + "</p><small class=\"text-muted mt-2 d-block\">via " + r.provider + " • " + r.text.length + " chars</small>");
                $("#ai-quick-save, #ai-quick-regen").prop("disabled", false);
            } else {
                $("#ai-quick-preview").html("<span class=\"text-danger\">" + r.error + "</span>");
            }
            btn.html("<i class=\"fe fe-zap\"></i> Generate SMS Template").prop("disabled", false);
        }, "json").fail(function() {
            btn.html("<i class=\"fe fe-zap\"></i> Generate SMS Template").prop("disabled", false);
            $("#ai-quick-preview").html("<span class=\"text-danger\">Network error</span>");
        });
    }
    
    $("#ai-quick-gen, #ai-quick-regen").click(quickGenerate);
    
    // Save as Template
    $("#ai-quick-save").click(function() {
        if (!lastGenerated) return;
        var title = prompt("Template title:", "AI: " + $("#ai-quick-prompt").val().substring(0, 40));
        if (!title) return;
        
        $.post("' . base_url('public/api/ai_save_template.php') . '", {
            title: title, message: lastGenerated
        }, function(r) {
            if (r.success) {
                alert("✅ Template saved!");
                lastGenerated = "";
                $("#ai-quick-preview").html("<span class=\"text-success\">Template saved successfully!</span>");
                $("#ai-quick-save").prop("disabled", true);
            } else {
                alert("Error: " + r.error);
            }
        }, "json");
    });
});
</script>
<style>.spin { animation: spin 1s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } }</style>
';
include '../includes/footer.php';
?>