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

if (strlen($_SESSION['clogin']) == 0) {
    echo "<script>window.location.href='login.php';</script>";
} 
?>
<?php

// Get the slave trade ID from the query parameter
$slavetradeid = $_GET['slavetradeid']; // Make sure to sanitize or validate this input

// SQL to delete a record from tbl_slave and tbl_copytrade
$sql1 = "DELETE FROM tbl_slave WHERE slavetrade = :slavetradeid";
$sql2 = "DELETE FROM tbl_copytrade WHERE copytrade = :slavetradeid";

// Path to the user.txt file
$userFile = 'user.txt';

try {
    // Prepare the first query to delete from tbl_slave
    $stmt1 = $dbh->prepare($sql1);
    // Bind the parameter for the first query
    $stmt1->bindParam(':slavetradeid', $slavetradeid, PDO::PARAM_STR);
    // Execute the first query
    $stmt1->execute();

    // Prepare the second query to delete from tbl_copytrade
    $stmt2 = $dbh->prepare($sql2);
    // Bind the parameter for the second query
    $stmt2->bindParam(':slavetradeid', $slavetradeid, PDO::PARAM_STR);
    // Execute the second query
    $stmt2->execute();

    // Check if any rows were affected in both queries
    if ($stmt1->rowCount() > 0 || $stmt2->rowCount() > 0) {
        // Remove the entire line containing the slave trade ID from user.txt
        if (file_exists($userFile)) {
            // Read the file into an array of lines
            $lines = file($userFile, FILE_IGNORE_NEW_LINES);
            $newLines = [];

            // Loop through the lines and add only those that don't contain the slavetradeid
            foreach ($lines as $line) {
                // If the slave trade ID is not in the line, add it to the new lines array
                if (strpos($line, $slavetradeid) === false) {
                    $newLines[] = $line;
                }
            }

            // Write the updated lines back to the file
            file_put_contents($userFile, implode(PHP_EOL, $newLines) . PHP_EOL);
        }

        echo "<script>alert('Deleted Successfully');</script>";
        echo "<script>window.location.href='master.php';</script>";
    } else {
        echo "<script>alert('No record found with the given criteria.');</script>";
        echo "<script>window.location.href='master.php';</script>";
    }
} catch (PDOException $e) {
    // Handle the exception properly
    echo "<script>alert('Error: " . $e->getMessage() . "');</script>";
    echo "<script>window.location.href='master.php';</script>";
}
?>
