<?php
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_login();
require_role(['admin', 'production_manager', 'store_user']);

verify_csrf();

$user = current_user();
$userId = (int)$user['id'];
$role = $user['role'];
$userStoreId = $user['store_id'] ?? null;

$logId = (int)($_POST['log_id'] ?? 0);
$action = $_POST['action'] ?? '';

if (!in_array($action, ['approve', 'skip'], true)) {
    $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Geçersiz işlem.'];
    redirect($logId > 0 ? 'csv_preview.php?log_id=' . $logId : 'csv_upload.php');
}

$selected = array_unique(array_map('intval', $_POST['selected_rows'] ?? []));
$notes = $_POST['store_notes'] ?? [];

if (!$selected) {
    $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Hiç satır seçilmedi.'];
    redirect($logId > 0 ? 'csv_preview.php?log_id=' . $logId : 'csv_upload.php');
}

$placeholders = implode(',', array_fill(0, count($selected), '?'));
$params = $selected;
$sql = "SELECT id, store_id FROM csv_import_rows WHERE id IN ($placeholders) AND row_status = 'store_pending'";
if ($role === 'store_user') {
    $sql .= " AND store_id = ?";
    $params[] = (int)$userStoreId;
}
$stmt = db()->prepare($sql);
$stmt->execute($params);
$allowedRows = $stmt->fetchAll();
$allowedIds = array_map(fn($r) => (int)$r['id'], $allowedRows);

if (!$allowedIds) {
    $_SESSION['flash'] = ['type' => 'error', 'msg' => 'İşleme alınabilecek satır bulunamadı.'];
    redirect($logId > 0 ? 'csv_preview.php?log_id=' . $logId : 'csv_upload.php');
}

$storeDecision = $action === 'approve' ? 'approved' : 'skipped';
$rowStatus = $action === 'approve' ? 'admin_pending' : 'store_skipped';

$pdo = db();
$pdo->beginTransaction();

try {
    $update = $pdo->prepare("
        UPDATE csv_import_rows
        SET store_decision = :store_decision,
            store_decided_by = :store_decided_by,
            store_decided_at = NOW(),
            store_note = :store_note,
            admin_decision = CASE WHEN :admin_pending_status = 'admin_pending' THEN 'pending' ELSE admin_decision END,
            row_status = :row_status,
            updated_at = NOW()
        WHERE id = :id
          AND row_status = 'store_pending'
    ");

    foreach ($allowedIds as $id) {
        $storeNote = trim((string)($notes[$id] ?? ''));
        $update->execute([
            'store_decision' => $storeDecision,
            'store_decided_by' => $userId,
            'store_note' => $storeNote ?: null,
            'admin_pending_status' => $rowStatus,
            'row_status' => $rowStatus,
            'id' => $id,
        ]);
    }

    if ($logId > 0) {
        $updLog = $pdo->prepare("
            UPDATE csv_import_logs
            SET status = :status,
                inserted_rows = (
                    SELECT COUNT(*) FROM csv_import_rows
                    WHERE last_seen_import_log_id = :log_id_a
                      AND row_status IN ('admin_pending','converted_to_order')
                )
            WHERE id = :log_id_b
        ");
        $updLog->execute([
            'status' => $action === 'approve' ? 'store_approved_partial' : 'store_skipped_partial',
            'log_id_a' => $logId,
            'log_id_b' => $logId,
        ]);
    }

    $pdo->commit();

    $_SESSION['flash'] = [
        'type' => 'success',
        'msg' => $action === 'approve'
            ? count($allowedIds) . ' satır admin onayına gönderildi.'
            : count($allowedIds) . ' satır şimdilik bekletildi.'
    ];

    if ($logId > 0) {
        redirect('csv_preview.php?log_id=' . $logId);
    }
    redirect('csv_upload.php');
} catch (Throwable $e) {
    $pdo->rollBack();
    http_response_code(500);
    echo 'CSV onay kaydı sırasında hata: ' . htmlspecialchars($e->getMessage());
}
