<?php
session_start();
include('config.php');

if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit;
}

$id = $_GET['id'] ?? null;
if (!$id || !is_numeric($id)) {
    echo "<div class='alert alert-danger'>Invalid broker ID.</div>";
    exit;
}

$stmt = $dbh->prepare("SELECT * FROM blackbrokers WHERE id = ?");
$stmt->execute([$id]);
$broker = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$broker) {
    echo "<div class='alert alert-warning'>Broker not found.</div>";
    exit;
}

function normalize_blackbroker_image_url(string $imagePath): string {
    if ($imagePath === '') {
        return '';
    }

    // Keep absolute URLs untouched.
    if (preg_match('#^(https?:)?//#i', $imagePath)) {
        return $imagePath;
    }

    $normalized = str_replace('\\', '/', trim($imagePath));

    if (strpos($normalized, '/admin/uploads/') === 0) {
        return $normalized;
    }

    if (strpos($normalized, 'admin/uploads/') === 0) {
        return '/' . ltrim($normalized, '/');
    }

    if (strpos($normalized, 'uploads/') === 0) {
        return '/admin/' . ltrim($normalized, '/');
    }

    if (strpos($normalized, '/') === 0) {
        return $normalized;
    }

    return '/admin/uploads/' . ltrim($normalized, '/');
}

$pageError = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $score = $_POST['score'] ?? null;
    $regulation_status = trim($_POST['regulation_status'] ?? '');
    $risk_labels = trim($_POST['risk_labels'] ?? '');
    $years_in_business = trim($_POST['years_in_business'] ?? '');
    $flag_url = trim($_POST['flag_url'] ?? '');
    $detail_url = trim($_POST['detail_url'] ?? '');

    // Keep old image by default unless a new file upload succeeds.
    $image_url = $broker['image_url'] ?? '';

    if (!empty($_FILES['image_url']['name'])) {
        $uploadDir = __DIR__ . '/uploads/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $filename = uniqid() . '_' . basename($_FILES['image_url']['name']);
        $targetPath = $uploadDir . $filename;
        $savedPath = '/admin/uploads/' . $filename;

        if (move_uploaded_file($_FILES['image_url']['tmp_name'], $targetPath)) {
            $image_url = $savedPath;
        } else {
            $pageError = 'Image upload failed!';
        }
    }

    $stmt = $dbh->prepare("UPDATE blackbrokers SET
        name = ?,
        image_url = ?,
        score = ?,
        regulation_status = ?,
        risk_labels = ?,
        years_in_business = ?,
        flag_url = ?,
        detail_url = ?
        WHERE id = ?");

    $success = $stmt->execute([
        $name,
        $image_url,
        $score,
        $regulation_status,
        $risk_labels,
        $years_in_business,
        $flag_url,
        $detail_url,
        $id
    ]);

    if ($success) {
        header("Location: list_blackbrokers.php?updated=1");
        exit;
    }

    $pageError = 'Failed to update broker.';
}

$brokerImagePreview = normalize_blackbroker_image_url($broker['image_url'] ?? '');
?>

<style>
@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700&family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap');

.admin-main-content {
    /* margin-left: var(--sw, 255px); */
    padding: 100px 40px 32px;
    transition: all 0.3s ease;
    position: relative;
    z-index: 1;
}

.blackbroker-container {
    max-width: 1100px;
    margin: 0 auto;
    background: var(--dark-700, #161a20);
    border: 1px solid rgba(255,255,255,0.04);
    border-radius: 18px;
    overflow: hidden;
    box-shadow: 0 22px 45px rgba(0,0,0,0.25);
}

.blackbroker-hero {
    display: grid;
    grid-template-columns: 146px minmax(0, 1fr) 220px;
    gap: 24px;
    align-items: center;
    padding: 28px 30px;
    background: linear-gradient(140deg, var(--dark-800, #101214), var(--dark-700, #161a20));
    border-bottom: 1px solid rgba(255,255,255,0.06);
}

.hero-logo-wrap {
    width: 146px;
    height: 110px;
    border-radius: 20px;
    background: rgba(255,255,255,0.03);
    border: 1px solid rgba(255,255,255,0.07);
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
}

.hero-logo {
    max-height: 68px;
    max-width: 120px;
    object-fit: contain;
}

.hero-logo-fallback {
    font-family: 'Playfair Display', serif;
    font-size: 54px;
    color: var(--yellow);
}

.hero-kicker {
    display: inline-block;
    margin-bottom: 8px;
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.62rem;
    letter-spacing: 2.8px;
    text-transform: uppercase;
    color: var(--yellow-dim, #c9a010);
}

.hero-copy h1 {
    margin: 0 0 8px;
    font-family: 'Playfair Display', serif;
    font-size: 34px;
    color: var(--text-1);
}

.hero-copy p {
    margin: 0 0 14px;
    color: var(--text-2);
    font-size: 14px;
}

.hero-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.meta-pill {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 6px 12px;
    border-radius: 999px;
    font-size: 12px;
    font-weight: 700;
    color: var(--yellow);
    background: rgba(245,197,24,0.1);
    border: 1px solid rgba(245,197,24,0.2);
}

.meta-pill-soft {
    color: var(--text-2);
    background: rgba(255,255,255,0.03);
    border-color: rgba(255,255,255,0.06);
}

.hero-side {
    display: grid;
    gap: 10px;
}

.hero-side-box {
    background: rgba(255,255,255,0.03);
    border: 1px solid rgba(255,255,255,0.06);
    border-radius: 12px;
    padding: 12px 14px;
}

.hero-side-box span {
    display: block;
    font-size: 12px;
    color: var(--text-2);
    margin-bottom: 4px;
}

.hero-side-box strong {
    font-size: 14px;
    color: var(--text-1);
}

.blackbroker-body {
    padding: 26px 30px 30px;
}

.page-alert {
    border-radius: 10px;
    padding: 12px 14px;
    font-size: 14px;
    margin-bottom: 16px;
}

.page-alert-danger {
    color: #ffb4b2;
    border: 1px solid rgba(239,79,74,0.35);
    background: rgba(239,79,74,0.11);
}

.section-head {
    margin: 6px 0 14px;
}

.section-head h2 {
    margin: 0 0 5px;
    font-family: 'Playfair Display', serif;
    font-size: 22px;
    color: var(--text-1);
}

.section-head p {
    margin: 0;
    color: var(--text-2);
    font-size: 13px;
}

.form-grid {
    display: grid;
    gap: 16px;
}

.two-col {
    grid-template-columns: repeat(2, minmax(0, 1fr));
}

.field {
    display: flex;
    flex-direction: column;
    gap: 8px;
    margin-bottom: 14px;
}

.field-grow {
    flex: 1;
    margin-bottom: 0;
}

.field label {
    font-size: 13px;
    font-weight: 700;
    color: var(--text-2);
}

.input {
    width: 100%;
    min-height: 46px;
    border-radius: 12px;
    border: 1px solid rgba(255,255,255,0.07);
    background: var(--dark-600, #1c2028);
    color: var(--text-1);
    font-size: 14px;
    padding: 11px 14px;
}

.textarea {
    min-height: 118px;
    resize: vertical;
}

.input:focus {
    outline: none;
    border-color: rgba(245,197,24,0.34);
    box-shadow: 0 0 0 4px rgba(245,197,24,0.1);
}

.logo-uploader {
    display: flex;
    gap: 16px;
    align-items: flex-end;
    margin-bottom: 18px;
}

.logo-preview {
    width: 170px;
    flex-shrink: 0;
    background: rgba(255,255,255,0.03);
    border: 1px solid rgba(255,255,255,0.06);
    border-radius: 12px;
    padding: 10px;
}

.logo-preview span {
    display: block;
    font-size: 12px;
    color: var(--text-2);
    margin-bottom: 8px;
}

.logo-preview img {
    width: 100%;
    height: 66px;
    object-fit: contain;
}

.actions {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    align-items: center;
    border-top: 1px solid rgba(255,255,255,0.06);
    padding-top: 20px;
}

.btn-save,
.btn-cancel {
    min-height: 44px;
    padding: 10px 18px;
    border-radius: 12px;
    font-weight: 700;
    text-decoration: none;
    border: 1px solid transparent;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
}

.btn-save {
    background: linear-gradient(135deg, var(--yellow), var(--yellow-bright));
    color: var(--dark-900);
    box-shadow: 0 12px 22px rgba(245,197,24,0.2);
}

.btn-save:hover {
    transform: translateY(-1px);
    box-shadow: 0 16px 26px rgba(245,197,24,0.25);
}

.btn-cancel {
    background: var(--dark-600, #1c2028);
    color: var(--text-2);
    border-color: rgba(255,255,255,0.09);
}

.btn-cancel:hover {
    transform: translateY(-1px);
    color: var(--text-1);
    border-color: rgba(245,197,24,0.2);
}

@media (max-width: 1080px) {
    .blackbroker-hero {
        grid-template-columns: 110px minmax(0, 1fr);
    }

    .hero-logo-wrap {
        width: 110px;
        height: 90px;
    }

    .hero-side {
        grid-column: 1 / -1;
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }
}

@media (max-width: 900px) {
    .two-col {
        grid-template-columns: 1fr;
    }

    .logo-uploader {
        flex-direction: column;
        align-items: stretch;
    }

    .logo-preview {
        width: 100%;
    }
}

@media (max-width: 768px) {
    .admin-main-content {
        margin-left: 0;
        padding: 20px 14px;
    }

    .blackbroker-hero,
    .blackbroker-body {
        padding: 20px;
    }

    .blackbroker-hero {
        grid-template-columns: 1fr;
    }

    .hero-copy h1 {
        font-size: 28px;
    }

    .hero-side {
        grid-template-columns: 1fr;
    }

    .actions {
        flex-direction: column;
        align-items: stretch;
    }

    .btn-save,
    .btn-cancel {
        width: 100%;
    }
}
</style>


<?php include 'includes/header.php'; ?>
<?php include 'includes/sidebar.php'; ?>

<div class="admin-main-content">
    <div class="blackbroker-container">
        <div class="blackbroker-hero">
            <div class="hero-logo-wrap">
                <?php if (!empty($brokerImagePreview)): ?>
                    <img src="<?= htmlentities($brokerImagePreview) ?>" alt="<?= htmlentities($broker['name']) ?> logo" class="hero-logo">
                <?php else: ?>
                    <div class="hero-logo-fallback"><?= strtoupper(substr($broker['name'] ?? 'B', 0, 1)) ?></div>
                <?php endif; ?>
            </div>

            <div class="hero-copy">
                <span class="hero-kicker">Blacklist Management</span>
                <h1>Edit Blackbroker</h1>
                <p>Update risk profile, compliance status, and reference links for this flagged broker record.</p>
                <div class="hero-meta">
                    <span class="meta-pill">Score: <?= htmlentities($broker['score'] ?? '0') ?></span>
                    <span class="meta-pill meta-pill-soft"><?= !empty($broker['regulation_status']) ? htmlentities($broker['regulation_status']) : 'Status Unset' ?></span>
                    <span class="meta-pill meta-pill-soft"><?= !empty($broker['years_in_business']) ? htmlentities($broker['years_in_business']) . ' years' : 'Years Unset' ?></span>
                </div>
            </div>

            <div class="hero-side">
                <div class="hero-side-box">
                    <span>Record ID</span>
                    <strong>#<?= (int)$broker['id'] ?></strong>
                </div>
                <div class="hero-side-box">
                    <span>Profile Page</span>
                    <strong><?= !empty($broker['detail_url']) ? 'Linked' : 'Not Linked' ?></strong>
                </div>
            </div>
        </div>

        <div class="blackbroker-body">
            <?php if (!empty($pageError)): ?>
                <div class="page-alert page-alert-danger"><?= htmlentities($pageError) ?></div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data" class="blackbroker-form">
                <div class="section-head">
                    <h2>Core Identity</h2>
                    <p>Main broker details shown in the blacklist overview.</p>
                </div>

                <div class="form-grid two-col">
                    <div class="field">
                        <label for="name">Broker Name</label>
                        <input type="text" id="name" name="name" value="<?= htmlentities($broker['name']) ?>" class="input" required>
                    </div>

                    <div class="field">
                        <label for="score">Score</label>
                        <input type="number" id="score" step="0.01" name="score" value="<?= htmlentities($broker['score']) ?>" class="input" required>
                    </div>
                </div>

                <div class="form-grid two-col">
                    <div class="field">
                        <label for="regulation_status">Regulation Status</label>
                        <input type="text" id="regulation_status" name="regulation_status" value="<?= htmlentities($broker['regulation_status']) ?>" class="input" required>
                    </div>

                    <div class="field">
                        <label for="years_in_business">Years in Business</label>
                        <input type="text" id="years_in_business" name="years_in_business" value="<?= htmlentities($broker['years_in_business']) ?>" class="input" placeholder="e.g. 2">
                    </div>
                </div>

                <div class="section-head">
                    <h2>Risk & References</h2>
                    <p>Tags and links used for detailed risk disclosures.</p>
                </div>

                <div class="field">
                    <label for="risk_labels">Risk Labels (comma separated)</label>
                    <textarea id="risk_labels" name="risk_labels" class="input textarea" placeholder="fraud warning, clone entity, withdrawal issues"><?= htmlentities($broker['risk_labels']) ?></textarea>
                </div>

                <div class="form-grid two-col">
                    <div class="field">
                        <label for="flag_url">Flag URL</label>
                        <input type="text" id="flag_url" name="flag_url" value="<?= htmlentities($broker['flag_url']) ?>" class="input" placeholder="https://...">
                    </div>

                    <div class="field">
                        <label for="detail_url">Detail URL</label>
                        <input type="text" id="detail_url" name="detail_url" value="<?= htmlentities($broker['detail_url']) ?>" class="input" placeholder="https://...">
                    </div>
                </div>

                <div class="section-head">
                    <h2>Logo Asset</h2>
                    <p>Upload a new broker logo or keep the existing one.</p>
                </div>

                <div class="logo-uploader">
                    <div class="field field-grow">
                        <label for="image_url">Broker Logo</label>
                        <input type="file" id="image_url" name="image_url" class="input" accept="image/*">
                    </div>

                    <?php if (!empty($brokerImagePreview)): ?>
                        <div class="logo-preview">
                            <span>Current Logo</span>
                            <img src="<?= htmlentities($brokerImagePreview) ?>" alt="Current broker logo">
                        </div>
                    <?php endif; ?>
                </div>

                <div class="actions">
                    <button type="submit" class="btn-save">Update Blackbroker</button>
                    <a href="list_blackbrokers.php" class="btn-cancel">Back to List</a>
                </div>
            </form>
        </div>
    </div>
</div>


<?php include 'includes/footer.php'; ?>