<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth' => 'admin', 'public' => false]);
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
// session_start() removed — Kernel::handle manages sessions
if (empty($_SESSION['admin'])) { http_response_code(403); die(json_encode(['error'=>'unauthorized'])); }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit; }
$b = json_decode(file_get_contents('php://input'), true) ?? [];
$adminId = (int)($_SESSION['admin']['id'] ?? 0);
$inquiryId = (int)($b['inquiry_id'] ?? 0);
$action    = $b['action'] ?? '';
$note      = mb_substr(trim($b['note'] ?? ''), 0, 500);
$finalCost = (int)($b['final_cost_sdg'] ?? 0);
if (!$inquiryId) { http_response_code(400); die(json_encode(['error'=>'inquiry_id_required'])); }
try {
    $status = match($action) {
        'accept'  => 'negotiating',
        'reject'  => 'lost',
        'contact' => 'contact_attempted',
        'won'     => 'won',
        default   => null,
    };
    if ($status) {
        db()->prepare("UPDATE corporate_inquiries SET status=?,admin_notes=?,updated_at=NOW() WHERE id=?")
           ->execute([$status, $note, $inquiryId]);
    }
    if ($finalCost > 0) {
        db()->prepare("UPDATE corporate_proposals SET admin_final_cost_sdg=?,admin_notes=? WHERE inquiry_id=?")
           ->execute([$finalCost, $note, $inquiryId]);
    }
    // CRM log
    try {
        db()->prepare("INSERT INTO crm_timeline (user_id,event_type,summary) VALUES (0,?,?)")
           ->execute(["corporate_{$action}", "[Admin] $action on inquiry #{$inquiryId}: $note"]);
    } catch (Throwable $ignored) {}
    // Audit
    try {
        db()->prepare("INSERT INTO audit_logs (user_id,action,details) VALUES (?,?,?)")
           ->execute([$adminId,"corporate.$action",json_encode(['inquiry_id'=>$inquiryId,'note'=>$note])]);
    } catch (Throwable $ignored) {}
    echo json_encode(['ok'=>true,'action'=>$action,'inquiry_id'=>$inquiryId]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);
}
