<?php
session_start();
include('config.php');
include "includes/header.php"; include "includes/sidebar.php";

// Enable error reporting for PDO (for debugging)
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

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

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

$id = (int)$_GET['id'];

// Fetch broker data
$stmt = $dbh->prepare("SELECT * FROM brokers WHERE id = :id");
$stmt->execute([':id' => $id]);
$broker = $stmt->fetch(PDO::FETCH_ASSOC);

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

// Show POST data for debugging on submit
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // echo '<pre>POST DATA: ';
    // print_r($_POST);
    // echo '</pre>';

    $id_post = $_POST['id'] ?? null;
    if (!$id_post || !is_numeric($id_post)) {
        echo "<div class='alert alert-danger'>Invalid form submission: missing or invalid ID.</div>";
        include('includes/footer.php');
        exit;
    }

    // Sanitize and prepare all inputs
    $name = trim($_POST['name']);
    $score = is_numeric($_POST['score']) ? (float)$_POST['score'] : null;
    $spread = is_numeric($_POST['spread']) ? (float)$_POST['spread'] : null;
    $overall_rating = is_numeric($_POST['overall_rating']) ? (float)$_POST['overall_rating'] : null;
    $regulator = trim($_POST['regulator']);
    $broker_type = trim($_POST['broker_type']);
    $account_opening_charge = trim($_POST['account_opening_charge']);
    $account_maintenance_charge = trim($_POST['account_maintenance_charge']);
    $equity_delivery_brokerage = trim($_POST['equity_delivery_brokerage']);
    $equity_intraday_brokerage = trim($_POST['equity_intraday_brokerage']);
    $rank = is_numeric($_POST['rank']) ? (int)$_POST['rank'] : null;
    $assets = trim($_POST['assets']);
    $experience_years = is_numeric($_POST['experience_years']) ? (int)$_POST['experience_years'] : null;
    $risk_level = trim($_POST['risk_level']);
    $software = is_numeric($_POST['software']) ? (float)$_POST['software'] : null;
    $license = is_numeric($_POST['license']) ? (float)$_POST['license'] : null;
    $average_transaction = is_numeric($_POST['average_transaction']) ? (float)$_POST['average_transaction'] : null;
    $contact_no = trim($_POST['contact_no']);
    $operating_period = trim($_POST['operating_period']);
    $country = trim($_POST['country']);
    $regulation_level = trim($_POST['regulation_level']);
    $regulator_logo = trim($_POST['regulator_logo']);
    $equity = isset($_POST['equity']) ? 1 : 0;
    $commodity = isset($_POST['commodity']) ? 1 : 0;
    $currency = isset($_POST['currency']) ? 1 : 0;
    $futures = isset($_POST['futures']) ? 1 : 0;
    $options = isset($_POST['options']) ? 1 : 0;

    try {
        $dbh->beginTransaction();

        $stmt = $dbh->prepare("UPDATE brokers SET
            name = :name,
            score = :score,
            spread = :spread,
            overall_rating = :overall_rating,
            regulator = :regulator,
            broker_type = :broker_type,
            account_opening_charge = :account_opening_charge,
            account_maintenance_charge = :account_maintenance_charge,
            equity_delivery_brokerage = :equity_delivery_brokerage,
            equity_intraday_brokerage = :equity_intraday_brokerage,
            `rank` = :rank,
            assets = :assets,
            experience_years = :experience_years,
            risk_level = :risk_level,
            software = :software,
            license = :license,
            average_transaction = :average_transaction,
            contact_no = :contact_no,
            operating_period = :operating_period,
            country = :country,
            regulation_level = :regulation_level,
            regulator_logo = :regulator_logo,
            equity = :equity,
            commodity = :commodity,
            currency = :currency,
            futures = :futures,
            options = :options
            WHERE id = :id
        ");

        $stmt->execute([
            ':name' => $name,
            ':score' => $score,
            ':spread' => $spread,
            ':overall_rating' => $overall_rating,
            ':regulator' => $regulator,
            ':broker_type' => $broker_type,
            ':account_opening_charge' => $account_opening_charge,
            ':account_maintenance_charge' => $account_maintenance_charge,
            ':equity_delivery_brokerage' => $equity_delivery_brokerage,
            ':equity_intraday_brokerage' => $equity_intraday_brokerage,
            ':rank' => $rank,
            ':assets' => $assets,
            ':experience_years' => $experience_years,
            ':risk_level' => $risk_level,
            ':software' => $software,
            ':license' => $license,
            ':average_transaction' => $average_transaction,
            ':contact_no' => $contact_no,
            ':operating_period' => $operating_period,
            ':country' => $country,
            ':regulation_level' => $regulation_level,
            ':regulator_logo' => $regulator_logo,
            ':equity' => $equity,
            ':commodity' => $commodity,
            ':currency' => $currency,
            ':futures' => $futures,
            ':options' => $options,
            ':id' => $id_post
        ]);

        $dbh->commit();

        if ($stmt->rowCount() > 0) {
            echo "<div class='alert alert-success'>Broker details updated successfully.</div>";
        } else {
            echo "<div class='alert alert-info'>No changes detected or update did not affect any rows.</div>";
        }

        // Refresh broker data after update
        $stmt = $dbh->prepare("SELECT * FROM brokers WHERE id = :id");
        $stmt->execute([':id' => $id_post]);
        $broker = $stmt->fetch(PDO::FETCH_ASSOC);

    } catch (PDOException $e) {
        $dbh->rollBack();
        echo "<div class='alert alert-danger'>Update failed: " . htmlentities($e->getMessage()) . "</div>";
    }
}
?>

<form action="" method="post" style="color:white;">
<div class="admin-main-content">
    <div class="broker-container">
        <div class="broker-hero">
            <div class="broker-hero-media">
                <?php if (!empty($broker['regulator_logo'])): ?>
                    <img src="../uploads/<?= htmlentities($broker['logo']) ?>" alt="<?= htmlspecialchars($broker['name']) ?> logo">
                <?php else: ?>
                    <div class="broker-hero-fallback"><?= strtoupper(substr($broker['name'] ?? 'B', 0, 1)) ?></div>
                <?php endif; ?>
            </div>
            <div class="broker-hero-copy">
                <div class="broker-kicker">Broker Profile</div>
                <h1 class="broker-title"><?= htmlspecialchars($broker['name']) ?></h1>
                <p class="broker-subtitle">Update rankings, market access, pricing, and regulation details.</p>
                <div class="broker-meta-row">
                    <span class="meta-pill"><?= htmlspecialchars($broker['broker_type'] ?? 'Broker') ?></span>
                    <span class="meta-pill meta-pill-soft">Score: <?= htmlspecialchars($broker['score'] ?? '0') ?></span>
                    <span class="meta-pill meta-pill-soft">Rank: <?= htmlspecialchars($broker['rank'] ?? '-') ?></span>
                    <span class="meta-pill meta-pill-soft"><?= htmlspecialchars($broker['country'] ?? 'Global') ?></span>
                </div>
            </div>
            <div class="broker-hero-side">
                <div class="hero-side-box">
                    <span>Regulator</span>
                    <strong><?= htmlspecialchars($broker['regulator'] ?? 'N/A') ?></strong>
                </div>
                <div class="hero-side-box">
                    <span>Risk Level</span>
                    <strong><?= htmlspecialchars($broker['risk_level'] ?? 'Unspecified') ?></strong>
                </div>
            </div>
        </div>

        <div class="broker-body">
            <form action="" method="post" class="broker-form">
                <input type="hidden" name="id" value="<?= (int)$broker['id'] ?>">

                <div class="section-head">
                    <h2>Broker Details</h2>
                    <p>Primary identity and score values.</p>
                </div>

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

                <div class="form-grid three-col">
                    <div class="field">
                        <label for="score">Score</label>
                        <input type="number" step="0.01" name="score" id="score" class="input" required value="<?= htmlentities($broker['score']) ?>">
                    </div>
                    <div class="field">
                        <label for="spread">Spread</label>
                        <input type="number" step="0.01" name="spread" id="spread" class="input" required value="<?= htmlentities($broker['spread']) ?>">
                    </div>
                    <div class="field">
                        <label for="overall_rating">Overall Rating</label>
                        <input type="number" step="0.01" name="overall_rating" id="overall_rating" class="input" value="<?= htmlentities($broker['overall_rating']) ?>">
                    </div>
                </div>

                <div class="section-head">
                    <h2>Regulation & Exposure</h2>
                    <p>Regulator, risk, assets, and market access flags.</p>
                </div>

                <div class="form-grid two-col">
                    <div class="field">
                        <label for="regulator">Regulator</label>
                        <input type="text" name="regulator" id="regulator" class="input" required value="<?= htmlentities($broker['regulator']) ?>">
                    </div>
                    <div class="field">
                        <label for="risk_level">Risk Level</label>
                        <select id="risk_level" name="risk_level" class="input">
                            <option value="" <?= $broker['risk_level'] === null ? 'selected' : '' ?>>Select risk level</option>
                            <option value="Low" <?= $broker['risk_level'] === 'Low' ? 'selected' : '' ?>>Low</option>
                            <option value="Medium" <?= $broker['risk_level'] === 'Medium' ? 'selected' : '' ?>>Medium</option>
                            <option value="High" <?= $broker['risk_level'] === 'High' ? 'selected' : '' ?>>High</option>
                        </select>
                    </div>
                </div>

                <div class="chip-grid">
                    <label class="chip"><input type="checkbox" id="equity" name="equity" <?= $broker['equity'] ? 'checked' : '' ?>> <span>Equity</span></label>
                    <label class="chip"><input type="checkbox" id="commodity" name="commodity" <?= $broker['commodity'] ? 'checked' : '' ?>> <span>Commodity</span></label>
                    <label class="chip"><input type="checkbox" id="currency" name="currency" <?= $broker['currency'] ? 'checked' : '' ?>> <span>Currency</span></label>
                    <label class="chip"><input type="checkbox" id="futures" name="futures" <?= $broker['futures'] ? 'checked' : '' ?>> <span>Futures</span></label>
                    <label class="chip"><input type="checkbox" id="options" name="options" <?= $broker['options'] ? 'checked' : '' ?>> <span>Options</span></label>
                </div>

                <div class="form-grid two-col">
                    <div class="field">
                        <label for="assets">Assets</label>
                        <input type="text" id="assets" name="assets" class="input" value="<?= htmlentities($broker['assets']) ?>" placeholder="comma separated">
                    </div>
                    <div class="field">
                        <label for="country">Country</label>
                        <input type="text" id="country" name="country" class="input" value="<?= htmlentities($broker['country']) ?>">
                    </div>
                </div>

                <div class="section-head">
                    <h2>Pricing & Operations</h2>
                    <p>Charges, years, software, and transaction metrics.</p>
                </div>

                <div class="form-grid three-col">
                    <div class="field">
                        <label for="account_opening_charge">Account Opening Charge</label>
                        <input type="text" id="account_opening_charge" name="account_opening_charge" class="input" value="<?= htmlentities($broker['account_opening_charge']) ?>">
                    </div>
                    <div class="field">
                        <label for="account_maintenance_charge">Account Maintenance Charge</label>
                        <input type="text" id="account_maintenance_charge" name="account_maintenance_charge" class="input" value="<?= htmlentities($broker['account_maintenance_charge']) ?>">
                    </div>
                    <div class="field">
                        <label for="operating_period">Operating Period</label>
                        <input type="text" id="operating_period" name="operating_period" class="input" value="<?= htmlentities($broker['operating_period']) ?>" placeholder="e.g. 15-20 years">
                    </div>
                </div>

                <div class="form-grid three-col">
                    <div class="field">
                        <label for="equity_delivery_brokerage">Equity Delivery Brokerage</label>
                        <input type="text" id="equity_delivery_brokerage" name="equity_delivery_brokerage" class="input" value="<?= htmlentities($broker['equity_delivery_brokerage']) ?>">
                    </div>
                    <div class="field">
                        <label for="equity_intraday_brokerage">Equity Intraday Brokerage</label>
                        <input type="text" id="equity_intraday_brokerage" name="equity_intraday_brokerage" class="input" value="<?= htmlentities($broker['equity_intraday_brokerage']) ?>">
                    </div>
                    <div class="field">
                        <label for="rank">Rank</label>
                        <input type="number" min="1" id="rank" name="rank" class="input" value="<?= htmlentities($broker['rank']) ?>">
                    </div>
                </div>

                <div class="form-grid three-col">
                    <div class="field">
                        <label for="experience_years">Experience Years</label>
                        <input type="number" min="0" id="experience_years" name="experience_years" class="input" value="<?= htmlentities($broker['experience_years']) ?>">
                    </div>
                    <div class="field">
                        <label for="software">Software</label>
                        <input type="number" step="0.01" min="0" id="software" name="software" class="input" value="<?= htmlentities($broker['software']) ?>">
                    </div>
                    <div class="field">
                        <label for="license">License</label>
                        <input type="number" step="0.01" min="0" id="license" name="license" class="input" value="<?= htmlentities($broker['license']) ?>">
                    </div>
                </div>

                <div class="form-grid two-col">
                    <div class="field">
                        <label for="average_transaction">Average Transaction</label>
                        <input type="number" step="0.01" min="0" id="average_transaction" name="average_transaction" class="input" value="<?= htmlentities($broker['average_transaction']) ?>">
                    </div>
                    <div class="field">
                        <label for="contact_no">Contact Number</label>
                        <input type="text" id="contact_no" name="contact_no" class="input" value="<?= htmlentities($broker['contact_no']) ?>">
                    </div>
                </div>

                <div class="section-head">
                    <h2>Regulation Media</h2>
                    <p>Logo and regulatory-level details.</p>
                </div>

                <div class="form-grid two-col">
                    <div class="field">
                        <label for="regulation_level">Regulation Level</label>
                        <input type="text" id="regulation_level" name="regulation_level" class="input" value="<?= htmlentities($broker['regulation_level']) ?>">
                    </div>
                    <div class="field">
                        <label for="regulator_logo">Regulator Logo URL</label>
                        <input type="text" id="regulator_logo" name="regulator_logo" class="input" value="<?= htmlentities($broker['regulator_logo']) ?>">
                    </div>
                </div>

                <div class="actions">
                    <button type="submit" class="btn-save">Update Broker</button>
                    <a href="brokers.php" class="btn-cancel">Back to Brokers</a>
                </div>
            </form>
        </div>
    </div>
</div>

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

body {
    background: var(--dark-900, #0b0c0e);
    font-family: 'Plus Jakarta Sans', sans-serif;
    color: var(--text-1, #edf0f7);
    margin: 0;
    padding: 0;
}

.admin-main-content {
    margin-left: var(--sw, 260px);
    padding: 100px 40px 40px 40px;
    transition: all 0.3s ease;
}

.broker-container {
    max-width: 1100px;
    margin: 0 auto;
    background: var(--dark-700, #121212);
    border: 1px solid rgba(255,255,255,0.04);
    border-radius: 18px;
    overflow: hidden;
    box-shadow: 0 20px 40px rgba(0,0,0,0.25);
}

.broker-hero {
    display: grid;
    grid-template-columns: 160px minmax(0, 1fr) 250px;
    gap: 45px;
    align-items: center;
    padding: 30px 32px;
    background: linear-gradient(135deg, var(--dark-800, #101214), var(--dark-700, #121212));
    border-bottom: 1px solid rgba(255,255,255,0.04);
}

.broker-hero-media {
    width: 160px;
    height: 120px;
    border-radius: 24px;
    background: rgba(255,255,255,0.04);
    border: 1px solid rgba(255,255,255,0.06);
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
}

.broker-hero-media img {
    width: auto;
    height: 32%;
    object-fit: cover;
}

.broker-hero-fallback {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-family: 'Playfair Display', serif;
    font-size: 3rem;
    color: var(--yellow);
}

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

.broker-title {
    font-family: 'Playfair Display', serif;
    font-size: 34px;
    line-height: 1.15;
    margin: 0 0 10px;
    color: var(--text-1);
}

.broker-subtitle {
    margin: 0 0 18px;
    color: var(--text-2);
    font-size: 14px;
}

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

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

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

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

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

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

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

.broker-body {
    padding: 28px 32px 34px;
}

.section-head {
    margin: 0 0 18px;
    padding-top: 8px;
}

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

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

.broker-form {
    position: relative;
}

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

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

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

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

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

.input:focus, .form-select:focus {
    outline: none;
    border-color: var(--yellow-border);
    box-shadow: 0 0 0 4px var(--yellow-glass);
}

.chip-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin: 4px 0 18px;
}

.chip {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 10px 14px;
    border-radius: 999px;
    background: rgba(255,255,255,0.03);
    border: 1px solid rgba(255,255,255,0.06);
    color: var(--text-2);
    cursor: pointer;
}

.chip input { accent-color: var(--yellow); }

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

.btn-save,
.btn-cancel {
    min-height: 44px;
    padding: 11px 18px;
    border-radius: 12px;
    border: 1px solid transparent;
    font-weight: 700;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    transition: transform 0.2s ease, box-shadow 0.2s ease, background 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 24px rgba(245,197,24,0.18);
}

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

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

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

@media (max-width: 1080px) {
    .broker-hero {
        grid-template-columns: 100px 1fr;
    }

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

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

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

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

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

    .broker-hero-media {
        width: 92px;
        height: 92px;
    }

    .broker-title {
        font-size: 28px;
    }

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

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

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

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