<?php
// Backfill deal failure reasons from activities (stage failed).

require __DIR__ . '/../../vendor/autoload.php';
$app = require __DIR__ . '/../../app/bootstrap.php';

$pdo = $app->db->getPdo();

$sql = "
    SELECT d.id, d.didar_deal_id, a.failure_reason_code, a.failure_reason_description
    FROM deals d
    INNER JOIN activities a ON a.deal_didar_id = d.didar_deal_id
    WHERE d.status = 'Lost'
      AND (d.failure_reason_code IS NULL OR TRIM(d.failure_reason_code) = '')
      AND (a.failure_reason_code IS NOT NULL AND TRIM(a.failure_reason_code) <> '')
    ORDER BY a.register_date DESC
";

$stmt = $pdo->query($sql);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

$map = [
    'no_financial_ability' => 'عدم توان مالی',
    'no_purchase_intent' => 'فعلا قصد خرید ندارد',
    'competitor_purchase' => 'خرید از رقبا',
    'wrong_number' => 'شماره اشتباه',
    'irrelevant_lead' => 'لید نامرتبط',
    'other' => 'سایر'
];

$updated = 0;
foreach ($rows as $row) {
    $code = trim((string)$row['failure_reason_code']);
    if ($code === '') {
        continue;
    }
    $text = $map[$code] ?? $code;
    $desc = trim((string)($row['failure_reason_description'] ?? '')) ?: null;

    $update = $pdo->prepare("
        UPDATE deals
        SET failure_reason_code = ?,
            failure_reason_text = ?,
            failure_reason_description = COALESCE(?, failure_reason_description),
            last_sync = NOW()
        WHERE id = ?
    ");
    $update->execute([$code, $text, $desc, $row['id']]);
    $updated++;
}

echo "Backfill completed from activities. Updated rows: {$updated}" . PHP_EOL;
