<?php 
session_start();
if(isset($_SESSION['SESS_ADMINLOGGEDIN']) == FALSE) {
    header("Location: " . $config_basedir."../admin/adminlogin.php");
}
require_once("header.php");

// ====== FETCH COPY DATA FOR SELECT OPTIONS ======
$copyStmt = $pdo->query("SELECT id, name, Pack_location FROM copy ORDER BY id ASC");
$copyOptions = $copyStmt->fetchAll(PDO::FETCH_ASSOC);

// ===== DELETE HANDLER =====
if (isset($_GET['del']) && is_numeric($_GET['del'])) {
    $delId = (int) $_GET['del'];
    $stmt = $pdo->prepare("DELETE FROM signals WHERE id = ?");
    $stmt->execute([$delId]);
    if ($stmt->rowCount() > 0) {
        echo "<script>alert('Signal deleted successfully!');window.location.href='signals.php';</script>";
    }
}

// ===== INSERT HANDLER =====
if (isset($_POST['action_signal'])) {
    $name      = trim($_POST['name']);
    $amount    = trim($_POST['amount']);
    $signal_id = trim($_POST['signal_id']);
    $signal_p  = trim($_POST['signal_p']);
    $status    = trim($_POST['status']);
    $min       = trim($_POST['min']);
    $max       = trim($_POST['max']);
    $NPrate    = trim($_POST['NPrate']);
    $Prate     = trim($_POST['Prate']);
    $Pfee      = trim($_POST['Pfee']);
    $Wrate     = trim($_POST['Wrate']);
    $riskL     = trim($_POST['riskL']);
    $strategy  = trim($_POST['strategy']);

    $owner       = trim($_POST['owner']);
    $owner_photo = trim($_POST['owner_photo']);

    try {
        $stmt = $pdo->prepare("INSERT INTO signals 
            (name, amount, signal_id, signal_p, status, min, max, NPrate, Prate, Pfee, Wrate, riskL, strategy, owner, owner_photo) 
            VALUES 
            (:name, :amount, :signal_id, :signal_p, :status, :min, :max, :NPrate, :Prate, :Pfee, :Wrate, :riskL, :strategy, :owner, :owner_photo)");
        $stmt->execute([
            ':name'      => $name,
            ':amount'    => $amount,
            ':signal_id' => $signal_id,
            ':signal_p'  => $signal_p,
            ':status'    => $status,
            ':min'       => $min,
            ':max'       => $max,
            ':NPrate'    => $NPrate,
            ':Prate'     => $Prate,
            ':Pfee'      => $Pfee,
            ':Wrate'     => $Wrate,
            ':riskL'     => $riskL,
            ':strategy'  => $strategy,
            ':owner'     => $owner,
            ':owner_photo' => $owner_photo
        ]);
        echo "<script>alert('Signal uploaded successfully!');window.location.href='signals.php';</script>";
    } catch (PDOException $e) {
        echo "<div class='alert alert-danger'>Error: " . $e->getMessage() . "</div>";
    }
}

// ===== UPDATE HANDLER =====
if (isset($_POST['update_signal'])) {
    $id        = trim($_POST['id']);
    $name      = trim($_POST['name']);
    $amount    = trim($_POST['amount']);
    $signal_id = trim($_POST['signal_id']);
    $signal_p  = trim($_POST['signal_p']);
    $status    = trim($_POST['status']);
    $min       = trim($_POST['min']);
    $max       = trim($_POST['max']);
    $NPrate    = trim($_POST['NPrate']);
    $Prate     = trim($_POST['Prate']);
    $Pfee      = trim($_POST['Pfee']);
    $Wrate     = trim($_POST['Wrate']);
    $riskL     = trim($_POST['riskL']);
    $strategy  = trim($_POST['strategy']);

    $owner       = trim($_POST['owner']);
    $owner_photo = trim($_POST['owner_photo']);

    try {
        $stmt = $pdo->prepare("UPDATE signals SET 
            name = :name,
            amount = :amount,
            signal_id = :signal_id,
            signal_p = :signal_p,
            status = :status,
            min = :min,
            max = :max,
            NPrate = :NPrate,
            Prate = :Prate,
            Pfee = :Pfee,
            Wrate = :Wrate,
            riskL = :riskL,
            strategy = :strategy,
            owner = :owner,
            owner_photo = :owner_photo
            WHERE id = :id");
        $stmt->execute([
            ':name'      => $name,
            ':amount'    => $amount,
            ':signal_id' => $signal_id,
            ':signal_p'  => $signal_p,
            ':status'    => $status,
            ':min'       => $min,
            ':max'       => $max,
            ':NPrate'    => $NPrate,
            ':Prate'     => $Prate,
            ':Pfee'      => $Pfee,
            ':Wrate'     => $Wrate,
            ':riskL'     => $riskL,
            ':strategy'  => $strategy,
            ':owner'     => $owner,
            ':owner_photo' => $owner_photo,
            ':id'        => $id
        ]);
        echo "<script>alert('Signal updated successfully!');window.location.href='signals.php';</script>";
    } catch (PDOException $e) {
        echo "<div class='alert alert-danger'>Error: " . $e->getMessage() . "</div>";
    }
}
?>

<style>
    .button-group { display:flex;justify-content:center;align-items:center;gap:10px; }
    .message { background:#f0f0f0;border-radius:10px;padding:15px;margin-bottom:10px; }
    .hidden-text { display:none; }
</style>

<div class="main-panel">
    <div class="content bg-light">
        <div class="page-inner">
            <div class="mt-2 mb-4">
                <h1 class="title1 text-dark">SIGNAL PLANS</h1>
            </div>

<?php
// ===== LIST SIGNALS =====
$stmt = $pdo->query("SELECT * FROM signals ORDER BY id ASC");
$signals = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($signals as $row) {
    echo "
    <div class='message'>
        <span class='visible-text'>
            <div><strong>Signal ID:</strong> ".htmlspecialchars($row['signal_id'])."</div>
            <div><strong>Name:</strong> ".htmlspecialchars($row['name'])."</div>
            <div><strong>Amount:</strong> ".htmlspecialchars($row['amount'])."</div>
            <div><strong>Owner:</strong> ".htmlspecialchars($row['owner'])."</div>
            <div><strong>Owner Photo:</strong> ".htmlspecialchars($row['owner_photo'])."</div>
            <div><strong>Min:</strong> ".htmlspecialchars($row['min'])."</div>
            <div><strong>Max:</strong> ".htmlspecialchars($row['max'])."</div>
            <div><strong>Signal %:</strong> ".htmlspecialchars($row['signal_p'])."%</div>
            <div><strong>Net Profit Rate:</strong> ".htmlspecialchars($row['NPrate'])."</div>
            <div><strong>Profit Rate:</strong> ".htmlspecialchars($row['Prate'])."</div>
            <div><strong>Profit Fee:</strong> ".htmlspecialchars($row['Pfee'])."</div>
            <div><strong>Win Rate:</strong> ".htmlspecialchars($row['Wrate'])."</div>
            <div><strong>Risk Level:</strong> ".htmlspecialchars($row['riskL'])."</div>
            <div><strong>Strategy:</strong> ".htmlspecialchars($row['strategy'])."</div>
        </span>

        <span class='hidden-text'>
            <form method='POST'>
                <input type='hidden' name='id' value='".$row['id']."'>
                <div class='form-group'><label class='form-control'>Name</label>
                    <input type='text' class='form-control bg-light text-dark' name='name' value='".htmlspecialchars($row['name'])."' required>
                </div>
                <div class='form-group'><label class='form-control'>Amount</label>
                    <input type='text' class='form-control bg-light text-dark' name='amount' value='".htmlspecialchars($row['amount'])."' required>
                </div>

                <!-- Dropdown for Owner -->
                <div class='form-group'><label class='form-control'>Assign Copy Owner</label>
                    <select name='copy_id' class='form-control bg-light text-dark' onchange=\"
                        const opt=this.options[this.selectedIndex];
                        this.form.owner.value=opt.getAttribute('data-name');
                        this.form.owner_photo.value=opt.getAttribute('data-pack');
                    \">
                        <option value=''>-- Select from Copy Table --</option>";
                        foreach($copyOptions as $c){
                            $sel = ($row['owner']==$c['name'] && $row['owner_photo']==$c['Pack_location'])?'selected':'';
                            echo "<option value='".$c['id']."' data-name='".htmlspecialchars($c['name'])."' data-pack='".htmlspecialchars($c['Pack_location'])."' $sel>"
                                .htmlspecialchars($c['name'])." (".htmlspecialchars($c['Pack_location']).")</option>";
                        }
                    echo "</select>
                </div>
                <input type='hidden' name='owner' value='".htmlspecialchars($row['owner'])."'>
                <input type='hidden' name='owner_photo' value='".htmlspecialchars($row['owner_photo'])."'>

                <div class='form-group'><label class='form-control'>Min</label>
                    <input type='text' class='form-control bg-light text-dark' name='min' value='".htmlspecialchars($row['min'])."'>
                </div>
                <div class='form-group'><label class='form-control'>Max</label>
                    <input type='text' class='form-control bg-light text-dark' name='max' value='".htmlspecialchars($row['max'])."'>
                </div>
                <div class='form-group'><label class='form-control'>Signal %</label>
                    <input type='text' class='form-control bg-light text-dark' name='signal_p' value='".htmlspecialchars($row['signal_p'])."' required>
                </div>
                <div class='form-group'><label class='form-control'>Status</label>
                    <select name='status' class='form-control bg-light text-dark'>
                        <option value='1' ".($row['status']==1?'selected':'').">Active</option>
                        <option value='0' ".($row['status']==0?'selected':'').">Inactive</option>
                    </select>
                </div>
                <div class='form-group'><label class='form-control'>Net Profit Rate</label>
                    <input type='text' class='form-control bg-light text-dark' name='NPrate' value='".htmlspecialchars($row['NPrate'])."'>
                </div>
                <div class='form-group'><label class='form-control'>Profit Rate</label>
                    <input type='text' class='form-control bg-light text-dark' name='Prate' value='".htmlspecialchars($row['Prate'])."'>
                </div>
                <div class='form-group'><label class='form-control'>Profit Fee</label>
                    <input type='text' class='form-control bg-light text-dark' name='Pfee' value='".htmlspecialchars($row['Pfee'])."'>
                </div>
                <div class='form-group'><label class='form-control'>Win Rate</label>
                    <input type='text' class='form-control bg-light text-dark' name='Wrate' value='".htmlspecialchars($row['Wrate'])."'>
                </div>
                <div class='form-group'><label class='form-control'>Risk Level</label>
                    <input type='text' class='form-control bg-light text-dark' name='riskL' value='".htmlspecialchars($row['riskL'])."'>
                </div>
                <div class='form-group'><label class='form-control'>Strategy</label>
                    <textarea class='form-control bg-light text-dark' name='strategy'>".htmlspecialchars($row['strategy'])."</textarea>
                </div>
                <div class='button-group'>
                    <a href='signals.php?del=".$row['id']."' class='btn btn-danger'>DELETE</a>
                    <button type='submit' class='btn btn-success' name='update_signal'>UPDATE</button>
                </div>
            </form>
        </span>
        <span class='btn btn-primary' onclick='toggleViewMore(this)'>View More</span>
    </div>";
}
?>

<script>
function toggleViewMore(el) {
    const msg = el.parentElement;
    const hidden = msg.querySelector('.hidden-text');
    const visible = msg.querySelector('.visible-text');
    if (hidden.style.display === 'none' || hidden.style.display === '') {
        hidden.style.display = 'block'; visible.style.display='none'; el.textContent='View Less';
    } else {
        hidden.style.display='none'; visible.style.display='block'; el.textContent='View More';
    }
}
</script>

<hr>
<center>ADD MORE SIGNALS</center>
<form method='POST'>
    <div class='form-group'><label class='form-control'>Name</label>
        <input type='text' class='form-control bg-light text-dark' name='name' required>
    </div>
    <div class='form-group'><label class='form-control'>Signal Power %</label>
        <input type='number' class='form-control bg-light text-dark' name='signal_p' required>
    </div>
    <div class='form-group'><label class='form-control'>Amount</label>
        <input type='number' class='form-control bg-light text-dark' name='amount' required>
    </div>

    <!-- NEW DROPDOWN TO PICK FROM COPY -->
    <div class='form-group'><label class='form-control'>Assign Copy Owner</label>
        <select name='copy_id' class='form-control bg-light text-dark' onchange="
            const opt=this.options[this.selectedIndex];
            document.getElementById('owner').value=opt.getAttribute('data-name');
            document.getElementById('owner_photo').value=opt.getAttribute('data-pack');
        ">
            <option value=''>-- Select from Copy Table --</option>
            <?php foreach($copyOptions as $c): ?>
                <option value='<?= $c['id'] ?>' data-name='<?= htmlspecialchars($c['name']) ?>' data-pack='<?= htmlspecialchars($c['Pack_location']) ?>'>
                    <?= htmlspecialchars($c['name']).' ('.$c['Pack_location'].')' ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>

    <input type='hidden' id='owner' name='owner'>
    <input type='hidden' id='owner_photo' name='owner_photo'>

    <div class='form-group'><label class='form-control'>Min</label>
        <input type='number' class='form-control bg-light text-dark' name='min'>
    </div>
    <div class='form-group'><label class='form-control'>Max</label>
        <input type='number' class='form-control bg-light text-dark' name='max'>
    </div>
    <div class='form-group'><label class='form-control'>Status</label>
        <select name='status' class='form-control bg-light text-dark' required>
            <option value='1'>Activate</option>
            <option value='0'>Deactivate</option>
        </select>
    </div>
    <div class='form-group'><label class='form-control'>Net Profit Rate</label>
        <input type='text' class='form-control bg-light text-dark' name='NPrate'>
    </div>
    <div class='form-group'><label class='form-control'>Profit Rate</label>
        <input type='text' class='form-control bg-light text-dark' name='Prate'>
    </div>
    <div class='form-group'><label class='form-control'>Profit Fee</label>
        <input type='text' class='form-control bg-light text-dark' name='Pfee'>
    </div>
    <div class='form-group'><label class='form-control'>Win Rate</label>
        <input type='text' class='form-control bg-light text-dark' name='Wrate'>
    </div>
    <div class='form-group'><label class='form-control'>Risk Level</label>
        <input type='text' class='form-control bg-light text-dark' name='riskL'>
    </div>
    <div class='form-group'><label class='form-control'>Strategy</label>
        <textarea class='form-control bg-light text-dark' name='strategy'></textarea>
    </div>

    <?php $pack_id = rand(1000,10000); ?>
    <input type='hidden' name='signal_id' value='SGL<?php echo $pack_id; ?>'>
    <button type='submit' class='btn btn-success' name='action_signal'>ADD SIGNAL</button>
</form>

</div></div></div>
<?php require("footer.php"); ?>
