<?php 
session_start();
require_once("header.php");

if (!isset($_SESSION['SESS_ADMINLOGGEDIN'])) {
    header("Location: " . $config_basedir . "../admin/adminlogin.php");
    exit();
}

// ✅ Ensure PDO exists
if (!isset($pdo)) {
    include '../config/db.php'; // adjust path if needed
}

if (!$pdo) {
    die("<div style='color:red;font-weight:bold;'>❌ Database not connected. Check your db.php</div>");
}

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

<style>
.button-group {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}
.button-group button {
  padding: 10px 20px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f5f5f5;
  cursor: pointer;
  transition: background-color 0.3s ease;
}
.button-group button:hover {
  background-color: #ddd;
}
.button-group button:active {
  background-color: #bbb;
}
</style>

<?php
// ================= ADD NEW INVESTMENT ==================
if (isset($_POST['action_plan'])) {
    $plan        = $_POST['plan'] ?? '';
    $percentage  = $_POST['percentage'] ?? '';
    $min_amt     = $_POST['min_amt'] ?? '';
    $max_amt     = $_POST['max_amt'] ?? '';
    $duration    = $_POST['duration'] ?? '';
    $status      = $_POST['status'] ?? '';
    $cat         = $_POST['cat'] ?? '';
    $pack_id     = $_POST['pack_id'] ?? '';
    $amount      = $_POST['amount'] ?? '';
    $note        = $_POST['note'] ?? '';
    $options     = $_POST['options'] ?? '';
    $app_id      = $_POST['app_id'] ?? '';

    $Pack_location = '';
    $upload_dir = "../accounts/upload/invest/";
    $db_path = "accounts/upload/invest/";

    if (!empty($_FILES['imgfile2']['name'])) {
        $filename = basename($_FILES["imgfile2"]["name"]);
        $targetpath = $upload_dir . $filename;
        if (move_uploaded_file($_FILES["imgfile2"]["tmp_name"], $targetpath)) {
            $Pack_location = $db_path . $filename;
        }
    }

    try {
        $sql = "INSERT INTO stocks (
            amount, note, plan, percentage, min_amt, max_amt, duration, Pack_location, app_id, status, cat, options, pack_id
        ) VALUES (
            :amount, :note, :plan, :percentage, :min_amt, :max_amt, :duration, :Pack_location, :app_id, :status, :cat, :options, :pack_id
        )";

        $stmt = $pdo->prepare($sql);
        $ok = $stmt->execute([
            ':amount' => $amount,
            ':note' => $note,
            ':plan' => $plan,
            ':percentage' => $percentage,
            ':min_amt' => $min_amt,
            ':max_amt' => $max_amt,
            ':duration' => $duration,
            ':Pack_location' => $Pack_location,
            ':app_id' => $app_id,
            ':status' => $status,
            ':cat' => $cat,
            ':options' => $options,
            ':pack_id' => $pack_id
        ]);

        if ($ok) {
            echo "<script>alert('✅ Investment plan added successfully!');window.location.href='invest.php';</script>";
            exit;
        } else {
            $err = $stmt->errorInfo();
            echo "<div style='color:red;'>Insert error: {$err[2]}</div>";
        }
    } catch (PDOException $e) {
        echo "<div style='color:red;'>Exception: {$e->getMessage()}</div>";
    }
}
?>

<?php
// ================= UPDATE INVESTMENT ==================
if (isset($_POST['edit_plan'])) {
    $id          = $_POST['id'] ?? '';
    $plan        = $_POST['plan'] ?? '';
    $percentage  = $_POST['percentage'] ?? '';
    $min_amt     = $_POST['min_amt'] ?? '';
    $max_amt     = $_POST['max_amt'] ?? '';
    $duration    = $_POST['duration'] ?? '';
    $status      = $_POST['status'] ?? '';
    $cat         = $_POST['cat'] ?? '';
    $pack_id     = $_POST['pack_id'] ?? '';
    $amount      = $_POST['amount'] ?? '';
    $note        = $_POST['note'] ?? '';
    $options     = $_POST['options'] ?? '';
    $app_id      = $_POST['app_id'] ?? '';

    $Pack_location = '';
    $upload_dir = "../accounts/upload/invest/";
    $db_path = "accounts/upload/invest/";

    if (!empty($_FILES['imgfile']['name'])) {
        $filename = basename($_FILES["imgfile"]["name"]);
        $targetpath = $upload_dir . $filename;
        if (move_uploaded_file($_FILES["imgfile"]["tmp_name"], $targetpath)) {
            $Pack_location = $db_path . $filename;
        }
    }

    try {
        $sql = "UPDATE stocks SET 
            amount=:amount,
            note=:note,
            plan=:plan,
            percentage=:percentage,
            min_amt=:min_amt,
            max_amt=:max_amt,
            duration=:duration,
            app_id=:app_id,
            status=:status,
            cat=:cat,
            options=:options,
            pack_id=:pack_id";

        if ($Pack_location != '') {
            $sql .= ", Pack_location=:Pack_location";
        }

        $sql .= " WHERE id=:id";

        $stmt = $pdo->prepare($sql);

        $params = [
            ':amount' => $amount,
            ':note' => $note,
            ':plan' => $plan,
            ':percentage' => $percentage,
            ':min_amt' => $min_amt,
            ':max_amt' => $max_amt,
            ':duration' => $duration,
            ':app_id' => $app_id,
            ':status' => $status,
            ':cat' => $cat,
            ':options' => $options,
            ':pack_id' => $pack_id,
            ':id' => $id
        ];

        if ($Pack_location != '') {
            $params[':Pack_location'] = $Pack_location;
        }

        $ok = $stmt->execute($params);

        if ($ok) {
            echo "<script>alert('✅ Investment plan updated successfully!');window.location.href='invest.php';</script>";
            exit;
        } else {
            $err = $stmt->errorInfo();
            echo "<div style='color:red;'>Update error: {$err[2]}</div>";
        }
    } catch (PDOException $e) {
        echo "<div style='color:red;'>Exception: {$e->getMessage()}</div>";
    }
}
?>

<?php
// ================= UPDATE PHOTO ONLY ==================
if (isset($_POST['update_photo'])) {
    $id = $_POST['id'] ?? '';
    if (!empty($_FILES['imgfile']['name'])) {
        $upload_dir = "../accounts/upload/invest/";
        $db_path = "accounts/upload/invest/";
        $filename = basename($_FILES["imgfile"]["name"]);
        $targetpath = $upload_dir . $filename;
        if (move_uploaded_file($_FILES["imgfile"]["tmp_name"], $targetpath)) {
            $Pack_location = $db_path . $filename;
            $stmt = $pdo->prepare("UPDATE stocks SET Pack_location=:Pack_location WHERE id=:id");
            $stmt->execute([':Pack_location' => $Pack_location, ':id' => $id]);
            echo "<script>alert('✅ Investment photo updated successfully!');window.location.href='invest.php';</script>";
            exit;
        }
    }
}
?>




   



        <div wire:id="0ho7JEz65LVMGIzD4ceZ" wire:initial-data="{&quot;fingerprint&quot;:{&quot;id&quot;:&quot;0ho7JEz65LVMGIzD4ceZ&quot;,&quot;name&quot;:&quot;admin.manage-users&quot;,&quot;locale&quot;:&quot;en&quot;,&quot;path&quot;:&quot;admin\/dashboard\/manageusers&quot;,&quot;method&quot;:&quot;GET&quot;,&quot;v&quot;:&quot;acj&quot;},&quot;effects&quot;:{&quot;listeners&quot;:[],&quot;path&quot;:&quot;https:\/\/xtbtrading.live\/trade\/admin\/dashboard\/manageusers&quot;},&quot;serverMemo&quot;:{&quot;children&quot;:[],&quot;errors&quot;:[],&quot;htmlHash&quot;:&quot;ed570425&quot;,&quot;data&quot;:{&quot;pagenum&quot;:10,&quot;searchvalue&quot;:&quot;&quot;,&quot;orderby&quot;:&quot;id&quot;,&quot;orderdirection&quot;:&quot;desc&quot;,&quot;selectPage&quot;:false,&quot;selectAll&quot;:false,&quot;checkrecord&quot;:[],&quot;selected&quot;:&quot;&quot;,&quot;action&quot;:&quot;Delete&quot;,&quot;username&quot;:null,&quot;fullname&quot;:null,&quot;email&quot;:null,&quot;password&quot;:null,&quot;message&quot;:null,&quot;subject&quot;:null,&quot;plan&quot;:null,&quot;datecreated&quot;:null,&quot;topamount&quot;:null,&quot;toptype&quot;:null,&quot;topcolumn&quot;:&quot;Bonus&quot;,&quot;page&quot;:1,&quot;paginators&quot;:{&quot;page&quot;:1}},&quot;dataMeta&quot;:[],&quot;checksum&quot;:&quot;9e82a6adabccc53607a584c57da8f89b4130352eb62c7aa9cc50f9455ca3c494&quot;}}">
    <div class="main-panel">
        <div class="content bg-light">
            <div class="page-inner">
                <div class="mt-2 mb-4">
                    <h1 class="title1 text-dark">INVESTMENT PACK</h1>
                </div>
                <div>
    </div>                <div>
    </div>                
               
               
               
               
                    <div class="mb-5 row">
                    <div class="col-md-12 ">
                 <!--<div class="card shadow p-4 bg-light">-->
                           
                           
                  
<?php 
if(isset($edit_success)){
    echo $edit_success;
}
?>

   
      
            <?php 
if(isset($plan_success)){
    echo $plan_success;
}
?>
      




            <?php 
if(isset($edit_photo)){
    echo $edit_photo;
}
?>
       
      
                         
                            
                            
                            
                            
                            
                            
                          


        
            
            
            
             
         
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            padding: 0;
            box-sizing: border-box;
        }

        .message {
            background-color: #f0f0f0;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 10px;
            max-width: 100%;
            word-wrap: break-word;
            position: relative;
        }

        .hidden-text {
            display: none;
        }

        .view-more {
            color: #007bff;
            cursor: pointer;
            font-size: 14px;
        }

        .view-more:hover {
            text-decoration: underline;
        }
        
        .view-more-label {
    color: blue;
}
    </style>

    
<?php

// Check for delete message
if (isset($delete)) {
    echo "<span style='color:red'>Successfully deleted<br>
    <meta http-equiv='refresh' content='2; url=invest.php'/>
    ";
}

try {
    // Get all stock records
    $stmt = $pdo->query("SELECT * FROM stocks ORDER BY id ASC");
    $stocks = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($stocks as $row) {
        $plan = htmlspecialchars($row['plan']);
        $percentage = htmlspecialchars($row['percentage']);
        $duration = htmlspecialchars($row['duration']);
        $min_amt = htmlspecialchars($row['min_amt']);
        $max_amt = htmlspecialchars($row['max_amt']);
        $status = $row['status'];
        $cat = $row['cat'];
        $date = htmlspecialchars($row['date']);
        $Pack_location = htmlspecialchars($row['Pack_location']);

        echo "
        <div class='message'>
            <span class='visible-text'>
                <div class='form-group'>
                    <label for='plan' class='view-more-label' style='color:blue'>PLAN</label>
                    <input type='text' class='form-control bg-light text-dark' name='plan' value='$plan' readonly/>
                </div>
            </span>

            <span class='hidden-text'>
                <form method='POST' enctype='multipart/form-data'>
                    <input type='hidden' name='id' value='{$row['id']}'>
                    <div class='form-group'>
                        <label for='plan' class='view-more-label'>PLAN</label>
                        <input type='text' class='form-control bg-light text-dark' name='plan' value='$plan' required/>
                    </div>

                    <div class='form-group'>
                        <label for='percentage' class='view-more-label'>% ROI</label>
                        <input type='text' class='form-control bg-light text-dark' name='percentage' value='$percentage' required/>
                    </div>

                    <div class='form-group'>
                        <label for='duration' class='view-more-label'>TRADE/DURATION</label>
                        <select class='form-control bg-light text-dark' name='duration' required>
                            <option value='$duration'>" . getDurationText($duration) . "</option>
                            " . getDurationOptions($duration) . "
                        </select>
                    </div>

                    <div class='form-group'>
                        <label for='min_amt' class='view-more-label'>MIN PRICE</label>
                        <input type='text' class='form-control bg-light text-dark' name='min_amt' value='$min_amt' required/>
                    </div>

                    <div class='form-group'>
                        <label for='max_amt' class='view-more-label'>MAX PRICE</label>
                        <input type='text' class='form-control bg-light text-dark' name='max_amt' value='$max_amt' required/>
                    </div>

                    <div class='form-group'>
                        <label for='status' class='view-more-label'>STATUS</label>
                        <select name='status' class='form-control bg-light text-dark' required>
                            <option value='$status' selected>" . ($status == 0 ? 'PACKAGE NOT ACTIVE' : 'PACKAGE IS ACTIVE') . "</option>
                            <option value='1'>ACTIVATE PACKAGE</option>
                            <option value='0'>DEACTIVATE PACKAGE</option>
                        </select>
                    </div>

                    <div class='form-group'>
                        <label for='cat' class='view-more-label'>CATEGORY</label>
                        <select name='cat' class='form-control bg-light text-dark' required>
                            <option value='$cat' selected>" . getCategoryText($cat) . "</option>
                            " . getCategoryOptions() . "
                        </select>
                    </div>

                    <div class='form-group'>
                        <label for='date' class='view-more-label'>DATE</label>
                        <input type='text' class='form-control bg-light text-dark' name='date' value='$date' required/>
                    </div>

                    <div class='button-group'>
                        <a href='invest.php?del={$row['id']}' class='btn btn-danger'>DELETE</a>
                        <button type='submit' class='btn btn-success' name='edit_plan'>UPDATE</button>
                    </div>
                </form>
                <hr>

                <form method='POST' enctype='multipart/form-data'>
                    <div class='form-group'>
                        <input type='file' class='form-control bg-light text-dark' name='imgfile' accept='image/*' required/>
                        <input type='hidden' name='id' value='{$row['id']}'>
                        <label class='view-more-label'>INVEST PHOTO <img src='../$Pack_location' width='40px' height='40px' class='rounded-circle'>
                        <button type='submit' class='btn btn-info' name='update_photo'>CHANGE</button>
                        </label>
                    </div>
                </form>
                <hr>
            </span>
            <span class='btn btn-primary' onclick='toggleViewMore(this)'>View More</span>
        </div>";
    }
} catch (PDOException $e) {
    echo "<div class='alert alert-danger'>Error fetching data: " . $e->getMessage() . "</div>";
}

function getDurationText($duration) {
    $durations = [
        5 => '5 minutes', 30 => '30 minutes', 60 => '1 Hour', 720 => '12 Hours', 
        1440 => '24 Hours', 10080 => '1 Week', 20160 => '2 Weeks', 30240 => '3 Weeks', 
        40320 => '1 Month', 80640 => '2 Months', 120960 => '3 Months', 161280 => '4 Months', 
        201600 => '5 Months', 241920 => '6 Months', 282240 => '7 Months', 322560 => '8 Months', 
        362880 => '9 Months', 403200 => '10 Months', 443520 => '11 Months', 483840 => '12 Months'
    ];
    return $durations[$duration] ?? 'Unknown';
}

function getDurationOptions($selectedDuration) {
    $durations = [
        5 => '5 minutes', 30 => '30 minutes', 60 => '1 Hour', 720 => '12 Hours', 
        1440 => '24 Hours', 10080 => '1 Week', 20160 => '2 Weeks', 30240 => '3 Weeks', 
        40320 => '1 Month', 80640 => '2 Months', 120960 => '3 Months', 161280 => '4 Months', 
        201600 => '5 Months', 241920 => '6 Months', 282240 => '7 Months', 322560 => '8 Months', 
        362880 => '9 Months', 403200 => '10 Months', 443520 => '11 Months', 483840 => '12 Months'
    ];
    $options = '';
    foreach ($durations as $value => $label) {
        $options .= "<option value='$value'" . ($value == $selectedDuration ? ' selected' : '') . ">$label</option>";
    }
    return $options;
}

function getCategoryText($cat) {
    $categories = [1 => 'STANDARD', 2 => 'ADVANCED', 3 => 'NFP', 4 => 'CHAMBERS'];
    return $categories[$cat] ?? 'Unknown';
}

function getCategoryOptions() {
    return "<option value='1'>STANDARD</option>
            <option value='2'>ADVANCED</option>
            <option value='3'>NFP</option>
            <option value='4'>CHAMBERS</option>";
}
?>










<script>
    function toggleViewMore(element) {
        const message = element.parentElement;
        const hiddenText = message.querySelector('.hidden-text');
        const visibleText = message.querySelector('.visible-text');

        if (hiddenText.style.display === 'none' || hiddenText.style.display === '') {
            hiddenText.style.display = 'inline';
            visibleText.style.display = 'none';
            element.textContent = 'View Less';
        } else {
            hiddenText.style.display = 'none';
            visibleText.style.display = 'inline';
            element.textContent = 'View More';
        }
    }
</script>

            
            
            
            
            
            
          
   
    
    
    
    
    
      <hr>
      

     
     

    
    
                    <center>ADD MORE INVESTMENT</center>
            
            <form method='POST'  enctype='multipart/form-data' action=''> 
            
          
           <input type="hidden" id="date" name="date" value="<?php
          echo(date("jS F Y g.iA")); ?>" required/>
          
          
          <?php  $pack_id = rand(1000000000000,10000000000000); ?>
                      
        <input class="form-control border-primary" type="hidden" name="pack_id" value="<?php echo $pack_id; ?>" readonly>   
     
     
     
 
             
              <div class='form-group'>
                <label for='address' class='form-control'>PLAN</label>
              <input type='text' class='form-control bg-light text-dark' name='plan' placeholder='' required/><br>
              </div>
                       
            
             
             
             <div class='form-group'>
             <label for='address' class='form-control'>TRADE DAILY(%)</label>
              <input type='text' class='form-control bg-light text-dark' name='percentage'  placeholder='' require><br>     
             </div>
                       
              
              
              
              <div class='form-group'>
               <label for='address' class='form-control'>TIME PER TRADE</label>
                <select class='form-control bg-light text-dark' name='calendar'>
			      
			       <option value='5'>5 minutes</option>
			      <option value='30'>30 Minutes</option>
			      <option value='60'>1 Hour</option>
				  <option value='720'>12 Hours</option>
				  <option value='1440'>24 Hours</option>
				  
				  
			     <option value='10080'>1 Week</option>
			     <option value='20160'>2 Weeks</option>
			     <option value='30240'>3 Weeks</option>
			      <option value='40320'>1 Month</option>
				 
				 
				 
				  <option value='80640'>2 Months</option>
				  <option value='120960'>3 Months</option>
				   <option value='161280'>4 Months</option>
				    <option value='201600'>5 Months</option>
				  <option value='241920'>6 Months</option>
				  <option value='282240'>7 Months</option>
				  <option value='322560'>8 Months</option>
				  <option value='362880'>9 Months</option>
				  <option value='403200'>10 Months</option>
				  <option value='443520'>11 Months</option>
				  <option value='483840'>12 Months</option>
				  
				  </select>    
              </div>
                       
            
             <div class='form-group'>
                     <label for='address' class='form-control'>DAYS PER DURATION</label> 
             <select class='form-control bg-light text-dark' name='duration'>
			     <!--<option value='1440'>1 Day</option>-->
			     
			     
			     
			     <option value='5'>5 minutes</option>
			      <option value='30'>30 Minutes</option>
			      <option value='60'>1 Hour</option>
				  <option value='720'>12 Hours</option>
				  <option value='1440'>24 Hours</option>
				  
				  
			     <option value='10080'>1 Week</option>
			     <option value='20160'>2 Weeks</option>
			     <option value='30240'>3 Weeks</option>
			      <option value='40320'>1 Month</option>
				 
				 
				 
				  <option value='80640'>2 Months</option>
				  <option value='120960'>3 Months</option>
				   <option value='161280'>4 Months</option>
				    <option value='201600'>5 Months</option>
				  <option value='241920'>6 Months</option>
				  <option value='282240'>7 Months</option>
				  <option value='322560'>8 Months</option>
				  <option value='362880'>9 Months</option>
				  <option value='403200'>10 Months</option>
				  <option value='443520'>11 Months</option>
				  <option value='483840'>12 Months</option>
				  </select>
           </div>
           
           
            <div class='form-group'>
               <label for='address' class='form-control'>LOW INVESTMENT</label>
            <input type='number' class='form-control bg-light text-dark' name='min_amt' placeholder=''  required/><br>     
            </div>
                    
            
            
            <div class='form-group'>
           <label for='address' class='form-control'>HIGH INVESTMENT</label>
            <input type='number' class='form-control bg-light text-dark' name='max_amt' placeholder='' required/><br>     
            </div>
                        
            
             <div class='form-group'>
<label for='address' class='form-control'>INVESTMENT GATEGORIES</label>
           <select name='cat' class='form-control bg-light text-dark' >
                <!--<option value=''>SELECT CATEGORY</option>-->
                <option value='2' select='selected'>CRYPTO</option>
                <!--<option value='2'>CRYPTO-CURRENCY</option>-->
            </select>
            </div> 
 
            <div class='form-group'>
<label for='address' class='form-control'>STATUS</label>
           <select name='status' class='form-control bg-light text-dark' required/>
                <option value=''>SELECT STATUS</option>
                <option value='1'>ACTIVATE</option>
                <option value='0'>DI-ACTIVATE</option>
            </select>
            </div>
            
            
            






<div class='form-group'>
<label for='address' class='form-control'>CATEGORY</label>
           <select name='cat' class='form-control bg-light text-dark' required/>
                <option value=''>SELECT CATEGORY</option>
                <option value='1'>STANDARD</option>
                <option value='2'>ADVANCED</option>
                <option value='3'>NFP</option>
                <option value='4'>CHAMBERS</option>
            </select>
            </div>
            
            
            
            
             <div class='form-group'>
                        <label class='form-control' >UPLOAD EXPERT PIX </label>
             <input type='file' class='form-control bg-light text-dark' name='imgfile2' accept='image/*'  />   
            </div> 
             
                        
 <button type='submit' class='btn btn-success btn-block btn-theme-colored2 text-red btn-lg btn-flat' name='action_plan'>ADD INVESTMENT</button>

            </form>           
            
            
            

 
            
        </div></div></div>
<!--=====================================-->

</div>

 <?php
require ("footer.php")
?>

