<?php
session_start();
include('config.php');
ini_set('display_errors', 1);
error_reporting(E_ALL);

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

$success_message = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Retrieve and sanitize inputs
    $name = trim($_POST['name']);
    $score = $_POST['score'];
    $spread = $_POST['spread'];
    $overall_rating = $_POST['overall_rating'];
    $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']);

    // New fields from form
    $rank = isset($_POST['rank']) ? (int)$_POST['rank'] : null;
    $assets = isset($_POST['assets']) ? trim($_POST['assets']) : null;
    $experience_years = isset($_POST['experience_years']) ? (int)$_POST['experience_years'] : null;
    $risk_level = isset($_POST['risk_level']) ? trim($_POST['risk_level']) : null;
    $software = isset($_POST['software']) ? (float)$_POST['software'] : 0.00;
    $license = isset($_POST['license']) ? (float)$_POST['license'] : 0.00;
    $average_transaction = isset($_POST['average_transaction']) ? (float)$_POST['average_transaction'] : 0.00;
    $contact_no = isset($_POST['contact_no']) ? trim($_POST['contact_no']) : null;
    $operating_period = isset($_POST['operating_period']) ? trim($_POST['operating_period']) : null;
    $country = isset($_POST['country']) ? trim($_POST['country']) : null;
    $regulation_level = isset($_POST['regulation_level']) ? trim($_POST['regulation_level']) : null;
    $regulator_logo = isset($_POST['regulator_logo']) ? trim($_POST['regulator_logo']) : null;

    // Convert checkbox inputs to boolean values
    $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;

    // Handle logo upload
    $logo = null;
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = '../uploads/'; // Adjust path if needed
        $logo = basename($_FILES['logo']['name']);
        $uploadFile = $uploadDir . $logo;
        move_uploaded_file($_FILES['logo']['tmp_name'], $uploadFile);
    }

    // Prepare and execute the insert statement
    $stmt = $dbh->prepare("INSERT INTO brokers (
        name, overall_rating, score, spread, broker_type,
        equity, commodity, currency, futures, options,
        account_opening_charge, account_maintenance_charge,
        equity_delivery_brokerage, equity_intraday_brokerage,
        logo, regulator, country, regulation_level, regulator_logo,
        `rank`, assets, experience_years, risk_level,
        software, license, average_transaction,
        contact_no, operating_period
    ) VALUES (
        :name, :overall_rating, :score, :spread, :broker_type,
        :equity, :commodity, :currency, :futures, :options,
        :account_opening_charge, :account_maintenance_charge,
        :equity_delivery_brokerage, :equity_intraday_brokerage,
        :logo, :regulator, :country, :regulation_level, :regulator_logo,
        :rank, :assets, :experience_years, :risk_level,
        :software, :license, :average_transaction,
        :contact_no, :operating_period
    )");

    $stmt->execute([
        ':name' => $name,
        ':overall_rating' => $overall_rating,
        ':score' => $score,
        ':spread' => $spread,
        ':broker_type' => $broker_type,
        ':equity' => $equity,
        ':commodity' => $commodity,
        ':currency' => $currency,
        ':futures' => $futures,
        ':options' => $options,
        ':account_opening_charge' => $account_opening_charge,
        ':account_maintenance_charge' => $account_maintenance_charge,
        ':equity_delivery_brokerage' => $equity_delivery_brokerage,
        ':equity_intraday_brokerage' => $equity_intraday_brokerage,
        ':logo' => $logo,
        ':regulator' => $regulator,
        ':country' => $country,
        ':regulation_level' => $regulation_level,
        ':regulator_logo' => $regulator_logo,
        ':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
    ]);

    $success_message = "Broker added successfully.";
}

// Include Premium Admin Header & Sidebar
include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
  /* ── Layout & Page Header ── */
  .dash { max-width: 1200px; margin: 0 auto; padding: 30px 26px; z-index: 1; position: relative; }
  
  .page-header { display: flex; align-items: flex-end; justify-content: space-between; margin-bottom: 28px; flex-wrap: wrap; gap: 14px; }
  .ph-eyebrow { font-family: 'JetBrains Mono', monospace; font-size: 0.6rem; letter-spacing: 3.5px; text-transform: uppercase; color: var(--yellow-dim); margin-bottom: 6px; display: flex; align-items: center; gap: 7px; }
  .ph-eyebrow::before { content: ''; display: inline-block; width: 20px; height: 2px; background: var(--yellow); border-radius: 2px; }
  .ph-title { font-family: 'Syne', sans-serif; font-size: 2rem; font-weight: 800; color: var(--text-1); letter-spacing: -0.5px; line-height: 1.1; }

  /* ── Alerts ── */
  .custom-alert { background: rgba(62,203,119,0.1); border: 1px solid rgba(62,203,119,0.2); color: var(--green); padding: 14px 20px; border-radius: 10px; margin-bottom: 24px; display: flex; align-items: center; justify-content: space-between; font-weight: 500; font-size: 0.9rem; transition: opacity 0.5s ease; }
  .alert-close { background: none; border: none; color: var(--green); cursor: pointer; font-size: 1.1rem; opacity: 0.7; }
  .alert-close:hover { opacity: 1; }

  /* ── Form Panel ── */
  .form-panel { background: var(--dark-700); border: 1px solid rgba(255,255,255,0.05); border-radius: 14px; padding: 30px; }
  
  .section-title { font-family: 'Syne', sans-serif; font-size: 1.1rem; font-weight: 700; color: var(--text-1); border-bottom: 1px solid rgba(255,255,255,0.05); padding-bottom: 10px; margin-bottom: 20px; margin-top: 30px; }
  .section-title:first-child { margin-top: 0; }
  .section-title i { color: var(--yellow); margin-right: 8px; font-size: 1rem; }

  .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
  .grid-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; }
  .grid-4 { display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; }

  .form-group { margin-bottom: 18px; }
  .form-label { display: block; font-family: 'JetBrains Mono', monospace; font-size: 0.7rem; text-transform: uppercase; letter-spacing: 1px; color: var(--text-2); margin-bottom: 8px; font-weight: 600; }
  
  .form-control { width: 100%; padding: 12px 16px; background: var(--dark-800); border: 1px solid rgba(255,255,255,0.08); border-radius: 8px; color: var(--text-1); font-size: 0.9rem; transition: 0.3s; font-family: 'Manrope', sans-serif; }
  .form-control:focus { outline: none; border-color: var(--yellow); box-shadow: 0 0 0 3px var(--yellow-glass); }
  .form-control::placeholder { color: rgba(255,255,255,0.2); }
  
  input[type="file"].form-control { padding: 9px 16px; color: var(--text-2); }
  input[type="file"]::file-selector-button { background: var(--dark-600); color: var(--text-1); border: 1px solid rgba(255,255,255,0.1); padding: 5px 12px; border-radius: 6px; margin-right: 15px; cursor: pointer; font-family: 'JetBrains Mono', monospace; font-size: 0.7rem; transition: 0.2s; }
  input[type="file"]::file-selector-button:hover { background: var(--yellow-glass); color: var(--yellow); border-color: var(--yellow); }

  .form-select { appearance: none; background-image: url('data:image/svg+xml;charset=US-ASCII,<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="%238a90a6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"></polyline></svg>'); background-repeat: no-repeat; background-position: right 15px center; background-size: 14px; cursor: pointer; }

  /* Custom Checkboxes */
  .checkbox-group { display: flex; flex-wrap: wrap; gap: 20px; margin-top: 10px; background: var(--dark-800); padding: 15px; border-radius: 8px; border: 1px solid rgba(255,255,255,0.05); }
  .custom-checkbox { display: flex; align-items: center; gap: 10px; cursor: pointer; color: var(--text-1); font-size: 0.9rem; font-weight: 500; user-select: none; }
  .custom-checkbox input { appearance: none; width: 20px; height: 20px; border: 2px solid rgba(255,255,255,0.2); border-radius: 5px; background: var(--dark-700); cursor: pointer; transition: 0.2s; position: relative; }
  .custom-checkbox input:checked { background: var(--yellow); border-color: var(--yellow); }
  .custom-checkbox input:checked::after { content: '\2714'; position: absolute; color: var(--dark-900); font-size: 14px; left: 3px; top: -1px; }

  /* Action Buttons */
  .form-actions { display: flex; gap: 15px; margin-top: 40px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.05); }
  .btn-submit { background: var(--yellow); color: var(--dark-900); padding: 12px 28px; border: none; border-radius: 8px; font-weight: 700; font-size: 0.95rem; cursor: pointer; transition: 0.2s; display: flex; align-items: center; gap: 8px; }
  .btn-submit:hover { background: var(--yellow-bright); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(245,197,24,0.3); }
  .btn-cancel { background: rgba(255,255,255,0.05); color: var(--text-1); padding: 12px 28px; border: 1px solid rgba(255,255,255,0.1); border-radius: 8px; font-weight: 600; font-size: 0.95rem; cursor: pointer; text-decoration: none; transition: 0.2s; display: flex; align-items: center; gap: 8px; }
  .btn-cancel:hover { background: rgba(255,255,255,0.1); }

  @media (max-width: 768px) {
      .grid-2, .grid-3, .grid-4 { grid-template-columns: 1fr; gap: 10px; }
      .form-actions { flex-direction: column; }
      .btn-submit, .btn-cancel { width: 100%; justify-content: center; }
  }
</style>

<main class="dash">
    <!-- Page Header -->
    <div class="page-header">
        <div>
            <div class="ph-eyebrow">Inventory</div>
            <div class="ph-title">Add New <strong>Broker</strong></div>
        </div>
    </div>

    <!-- Alert -->
    <?php if ($success_message): ?>
        <div class="custom-alert" id="auto-alert">
            <div><i class="fas fa-check-circle"></i> &nbsp; <?= $success_message ?></div>
            <button class="alert-close" onclick="closeAlert()"><i class="fas fa-times"></i></button>
        </div>
    <?php endif; ?>

    <div class="form-panel">
        <form action="" method="post" enctype="multipart/form-data">
            
            <!-- Section 1: Basic Information -->
            <h3 class="section-title"><i class="fas fa-info-circle"></i> Basic Information</h3>
            <div class="grid-2">
                <div class="form-group">
                    <label class="form-label" for="name">Broker Name</label>
                    <input type="text" name="name" id="name" class="form-control" placeholder="e.g. FOREX.com" required>
                </div>
                <div class="form-group">
                    <label class="form-label" for="broker_type">Broker Type</label>
                    <input type="text" name="broker_type" id="broker_type" class="form-control" placeholder="e.g. ECN, STP, Market Maker">
                </div>
            </div>

            <div class="grid-3">
                <div class="form-group">
                    <label class="form-label" for="score">Score</label>
                    <input type="number" step="0.01" name="score" id="score" class="form-control" placeholder="0.00" required>
                </div>
                <div class="form-group">
                    <label class="form-label" for="overall_rating">Overall Rating</label>
                    <input type="number" step="0.01" name="overall_rating" id="overall_rating" class="form-control" placeholder="0.00">
                </div>
                <div class="form-group">
                    <label class="form-label" for="spread">Spread</label>
                    <input type="number" step="0.01" name="spread" id="spread" class="form-control" placeholder="0.00" required>
                </div>
            </div>

            <div class="grid-3">
                <div class="form-group">
                    <label class="form-label" for="rank">Global Rank</label>
                    <input type="number" name="rank" id="rank" class="form-control" min="1" max="100" placeholder="e.g. 1">
                </div>
                <div class="form-group">
                    <label class="form-label" for="experience_years">Experience Years</label>
                    <input type="number" name="experience_years" id="experience_years" class="form-control" min="0" placeholder="e.g. 15">
                </div>
                <div class="form-group">
                    <label class="form-label" for="risk_level">Risk Level</label>
                    <select name="risk_level" id="risk_level" class="form-control form-select">
                        <option value="" selected disabled>Select risk level</option>
                        <option value="Low">Low</option>
                        <option value="Medium">Medium</option>
                        <option value="High">High</option>
                    </select>
                </div>
            </div>

            <!-- Section 2: Services Offered -->
            <h3 class="section-title"><i class="fas fa-layer-group"></i> Services Offered</h3>
            <div class="checkbox-group">
                <label class="custom-checkbox">
                    <input type="checkbox" name="equity" id="equity"> Equity
                </label>
                <label class="custom-checkbox">
                    <input type="checkbox" name="commodity" id="commodity"> Commodity
                </label>
                <label class="custom-checkbox">
                    <input type="checkbox" name="currency" id="currency"> Currency
                </label>
                <label class="custom-checkbox">
                    <input type="checkbox" name="futures" id="futures"> Futures
                </label>
                <label class="custom-checkbox">
                    <input type="checkbox" name="options" id="options"> Options
                </label>
            </div>

            <!-- Section 3: Fees & Charges -->
            <h3 class="section-title"><i class="fas fa-hand-holding-usd"></i> Fees & Charges</h3>
            <div class="grid-2">
                <div class="form-group">
                    <label class="form-label" for="account_opening_charge">Account Opening Charge</label>
                    <input type="text" name="account_opening_charge" id="account_opening_charge" class="form-control" placeholder="e.g. Free or $50">
                </div>
                <div class="form-group">
                    <label class="form-label" for="account_maintenance_charge">Account Maintenance Charge</label>
                    <input type="text" name="account_maintenance_charge" id="account_maintenance_charge" class="form-control" placeholder="e.g. $10/month">
                </div>
                <div class="form-group">
                    <label class="form-label" for="equity_delivery_brokerage">Equity Delivery Brokerage</label>
                    <input type="text" name="equity_delivery_brokerage" id="equity_delivery_brokerage" class="form-control" placeholder="e.g. 0.1%">
                </div>
                <div class="form-group">
                    <label class="form-label" for="equity_intraday_brokerage">Equity Intraday Brokerage</label>
                    <input type="text" name="equity_intraday_brokerage" id="equity_intraday_brokerage" class="form-control" placeholder="e.g. $2 per lot">
                </div>
            </div>

            <!-- Section 4: Regulation & Company Info -->
            <h3 class="section-title"><i class="fas fa-shield-alt"></i> Regulation & Company Info</h3>
            <div class="grid-3">
                <div class="form-group">
                    <label class="form-label" for="regulator">Primary Regulator</label>
                    <input type="text" name="regulator" id="regulator" class="form-control" placeholder="e.g. FCA, ASIC">
                </div>
                <div class="form-group">
                    <label class="form-label" for="regulation_level">Regulation Level</label>
                    <input type="text" name="regulation_level" id="regulation_level" class="form-control" placeholder="e.g. Tier 1">
                </div>
                <div class="form-group">
                    <label class="form-label" for="country">Country</label>
                    <input type="text" name="country" id="country" class="form-control" placeholder="e.g. United Kingdom">
                </div>
            </div>

            <div class="grid-2">
                <div class="form-group">
                    <label class="form-label" for="contact_no">Contact Number</label>
                    <input type="text" name="contact_no" id="contact_no" class="form-control" placeholder="e.g. +1-555-555-5555">
                </div>
                <div class="form-group">
                    <label class="form-label" for="operating_period">Operating Period</label>
                    <input type="text" name="operating_period" id="operating_period" class="form-control" placeholder="e.g. 15-20 years">
                </div>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="assets">Assets (Comma Separated)</label>
                <input type="text" name="assets" id="assets" class="form-control" placeholder="e.g. Forex, Oil, Crypto, Metals">
            </div>

            <!-- Section 5: Technical Ratings & Media -->
            <h3 class="section-title"><i class="fas fa-laptop-code"></i> Technical Ratings & Media</h3>
            <div class="grid-3">
                <div class="form-group">
                    <label class="form-label" for="software">Software Rating</label>
                    <input type="number" step="0.01" name="software" id="software" class="form-control" min="0" placeholder="0.00">
                </div>
                <div class="form-group">
                    <label class="form-label" for="license">License Rating</label>
                    <input type="number" step="0.01" name="license" id="license" class="form-control" min="0" placeholder="0.00">
                </div>
                <div class="form-group">
                    <label class="form-label" for="average_transaction">Average Transaction Rating</label>
                    <input type="number" step="0.01" name="average_transaction" id="average_transaction" class="form-control" min="0" placeholder="0.00">
                </div>
            </div>

            <div class="grid-2">
                <div class="form-group">
                    <label class="form-label" for="logo">Upload Broker Logo</label>
                    <input type="file" name="logo" id="logo" class="form-control">
                </div>
                <div class="form-group">
                    <label class="form-label" for="regulator_logo">Regulator Logo URL (Optional)</label>
                    <input type="text" name="regulator_logo" id="regulator_logo" class="form-control" placeholder="https://example.com/fca-logo.png">
                </div>
            </div>

            <!-- Action Buttons -->
            <div class="form-actions">
                <button type="submit" class="btn-submit">
                    <i class="fas fa-save"></i> Add Broker
                </button>
                <a href="brokers.php" class="btn-cancel">
                    <i class="fas fa-times"></i> Cancel
                </a>
            </div>

        </form>
    </div>
</main>

<script>
    function closeAlert() {
        const alertBox = document.getElementById('auto-alert');
        if (alertBox) {
            alertBox.style.opacity = '0';
            setTimeout(() => alertBox.remove(), 500);
        }
    }

    // Auto dismiss alert after 5 seconds
    document.addEventListener("DOMContentLoaded", function() {
        setTimeout(closeAlert, 5000);
    });
</script>

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