<?php
require __DIR__ . '/../src/auth.php';
require_login();
require __DIR__ . '/../src/db.php';

$msg = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $prov = trim($_POST['provider_name']);
    $txt = trim($_POST['custom_message']);
    if ($prov) {
        $stmt = $pdo->prepare("INSERT INTO provider_settings (provider_name, custom_message) VALUES (?, ?) ON DUPLICATE KEY UPDATE custom_message = VALUES(custom_message)");
        $stmt->execute([$prov, $txt]);
        $msg = "Saved for $prov";
    }
}

$found = $pdo->query("SELECT DISTINCT service_provider FROM raw_reports WHERE service_provider != ''")->fetchAll(PDO::FETCH_COLUMN);
$settingsRaw = $pdo->query("SELECT * FROM provider_settings")->fetchAll(PDO::FETCH_ASSOC);
$settings = [];
foreach($settingsRaw as $s) $settings[$s['provider_name']] = $s['custom_message'];
$all = array_unique(array_merge($found, array_keys($settings)));
sort($all);
?>
<!doctype html>
<html>
<head><title>Provider Settings</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"></head>
<body>
<nav class="navbar navbar-light bg-white border-bottom"><div class="container"><a class="navbar-brand" href="dashboard.php">Report System</a><a href="dashboard.php" class="btn btn-sm btn-outline-secondary">Back</a></div></nav>
<div class="container py-4">
    <h3>Provider Custom Text</h3>
    <?php if($msg): ?><div class="alert alert-success"><?=$msg?></div><?php endif; ?>
    <div class="row">
        <?php foreach($all as $p): ?>
        <div class="col-md-6 mb-3">
            <div class="card">
                <div class="card-header fw-bold"><?=htmlspecialchars($p)?></div>
                <div class="card-body">
                    <form method="post">
                        <input type="hidden" name="provider_name" value="<?=htmlspecialchars($p)?>">
                        <textarea class="form-control mb-2" name="custom_message" rows="3" placeholder="Enter notes here..."><?=htmlspecialchars($settings[$p]??'')?></textarea>
                        <button class="btn btn-sm btn-primary">Save</button>
                    </form>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>
</body>
</html>