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

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

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

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

try {
    // Begin transaction
    $dbh->beginTransaction();

    // Delete from tbl_slave
    $sql1 = "DELETE FROM tbl_slave WHERE mastertrade = :tradeid";
    $stmt1 = $dbh->prepare($sql1);
    $stmt1->bindParam(':tradeid', $tradeid, PDO::PARAM_STR);
    $stmt1->execute();

    // Delete from tbl_copytrade
    $sql2 = "DELETE FROM tbl_copytrade WHERE mastertrade = :tradeid";
    $stmt2 = $dbh->prepare($sql2);
    $stmt2->bindParam(':tradeid', $tradeid, PDO::PARAM_STR);
    $stmt2->execute();

    // Delete from tbl_master
    $sql3 = "DELETE FROM tbl_master WHERE tradeid = :tradeid";
    $stmt3 = $dbh->prepare($sql3);
    $stmt3->bindParam(':tradeid', $tradeid, PDO::PARAM_STR);
    $stmt3->execute();

    // Commit the transaction
    $dbh->commit();

    // Remove lines containing master ID or slave ID from user.txt
    if (file_exists($userFile)) {
        $lines = file($userFile, FILE_IGNORE_NEW_LINES);
        $newLines = [];

        foreach ($lines as $line) {
            // If the line contains the master ID or slave ID, exclude it
            if (strpos($line, $tradeid) === false) {
                $newLines[] = $line;
            }
        }

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

    echo "<script>alert('Deleted Successfully');</script>";
} catch (PDOException $e) {
    // Rollback transaction on error
    $dbh->rollBack();
    echo "<script>alert('Error: " . addslashes($e->getMessage()) . "');</script>";
}

// Redirect to master.php
echo "<script>window.location.href='master.php';</script>";
?>
