<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
require_once '../../engine/SuggestionsAgent.php';
header('Access-Control-Allow-Origin: *');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit; }

$ctx = Kernel::handle(['auth' => 'optional']);
$u = $ctx['user'];
$uid = (int)($u['id'] ?? 0);
$b = json_decode(file_get_contents('php://input'), true) ?? [];

// Rate limit: 2/day free, 5/day plus, unlimited pro
$planKey = $u['plan_key'] ?? $u['subscription_tier'] ?? 'free';
$dailyMax = ['free'=>2,'plus'=>5,'pro'=>999,'corp'=>999][$planKey] ?? 2;
if ($uid > 0) {
    try {
        $todayCount = db()->prepare(
            "SELECT COUNT(*) FROM user_suggestions WHERE user_id=? AND DATE(created_at)=CURDATE()"
        );
        $todayCount->execute([$uid]);
        if ((int)$todayCount->fetchColumn() >= $dailyMax) {
            http_response_code(429);
            die(json_encode(['error'=>'rate_limit','message'=>"حد اليوم: {$dailyMax} اقتراحات"]));
        }
    } catch (Throwable $ignored) {}
}

// Validate
$type  = in_array($b['type']??'',['improvement','bug','solution','new_service','positive'])
       ? $b['type'] : 'improvement';
$title = mb_substr(trim($b['title'] ?? ''), 0, 300);
$desc  = mb_substr(trim($b['description'] ?? ''), 0, 2000);
$svc   = mb_substr(trim($b['service'] ?? 'platform'), 0, 50);
$bene  = mb_substr(trim($b['expected_benefit'] ?? ''), 0, 500);

if (mb_strlen($title) < 5) { http_response_code(400); die(json_encode(['error'=>'title_too_short'])); }
if (mb_strlen($desc)  < 20){ http_response_code(400); die(json_encode(['error'=>'description_too_short','message'=>'يرجى وصف الاقتراح بتفصيل أكثر (20 حرف على الأقل)'])); }

$ref = SuggestionsAgent::generateRef();
$ipHash = hash('sha256', $_SERVER['REMOTE_ADDR'] ?? '');
$convLog = json_encode($b['conversation_log'] ?? []);

try {
    db()->prepare(
        "INSERT INTO user_suggestions
         (ref_no,user_id,session_id,type,service,title,description,
          expected_benefit,conversation_log,user_plan,ip_hash,status)
         VALUES (?,?,?,?,?,?,?,?,?,?,'pending')"
    )->execute([
        $ref, $uid ?: null, session_id() ?: null,
        $type, $svc, $title, $desc, $bene, $convLog,
        $planKey, $ipHash,
    ]);
    $suggestionId = (int)db()->lastInsertId();

    // Auto-analyze in background (quick analysis)
    $suggestion = ['id'=>$suggestionId,'type'=>$type,'service'=>$svc,
                   'title'=>$title,'description'=>$desc,'user_plan'=>$planKey,'votes_count'=>0];
    $analysis = SuggestionsAgent::analyze($suggestion);

    // Save analysis
    db()->prepare(
        "UPDATE user_suggestions SET
         priority_score=?,priority_label=?,ai_summary=?,ai_recommendation=?,
         affected_estimate=?,effort_level=?,effort_hours=?,revenue_impact=?,
         team_responsible=?,risk_level=?,roadmap_quarter=?,similar_ids=?,category_tag=?
         WHERE id=?"
    )->execute([
        $analysis['priority_score'],$analysis['priority_label'],
        $analysis['ai_summary'],$analysis['ai_recommendation'],
        $analysis['affected_estimate'],$analysis['effort_level'],
        $analysis['effort_hours'],$analysis['revenue_impact'],
        $analysis['team_responsible'],$analysis['risk_level'],
        $analysis['roadmap_quarter'],json_encode($analysis['similar_ids']),
        $analysis['category_tag'],$suggestionId,
    ]);

    // If bug → auto-create support ticket
    if ($type === 'bug' && $uid > 0) {
        try {
            db()->prepare(
                "INSERT INTO support_tickets (user_id,category,priority,subject,description,related_type,related_id)
                 VALUES (?,'bug','high',?,?,'suggestion',?)"
            )->execute([$uid, "[Bug] $title", $desc, $suggestionId]);
            db()->prepare("UPDATE user_suggestions SET linked_ticket_id=LAST_INSERT_ID() WHERE id=?")
               ->execute([$suggestionId]);
        } catch (Throwable $ignored) {}
    }

    // Award points
    if ($uid > 0) SuggestionsAgent::awardPoints($uid, 'suggestion_submitted');

    // Notify admin if urgent
    if ($analysis['priority_label'] === 'urgent') {
        try {
            db()->prepare("INSERT INTO notifications (user_id,type,title,body,data) VALUES (1,'suggestion_urgent',?,?,?)")
               ->execute(["🔴 اقتراح عاجل: $title","من مستخدم {$planKey}",json_encode(['ref'=>$ref])]);
        } catch (Throwable $ignored) {}
    }

    echo json_encode([
        'ok'       => true,
        'ref'      => $ref,
        'analysis' => ['priority' => $analysis['priority_label'], 'score' => $analysis['priority_score']],
        'message'  => 'شكراً! تم استلام اقتراحك وسيُراجَع من فريقنا.',
    ], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    error_log("[suggestions/create] " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);
}
