<?php
require("db_config.php");

if (isset($_GET['id'])) {
    $id = intval($_GET['id']);

    // Fetch both image filenames from the database
    $sql = "SELECT image1, image2 FROM appstores WHERE id = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            $stmt->bind_result($image1, $image2);
            if ($stmt->fetch()) {
                // Store file paths securely
                $filePath1 = 'upload/' . basename($image1);
                $filePath2 = 'upload/' . basename($image2);

                // Close the statement before running a new query
                $stmt->close();

                // Delete the record from the database
                $sqlDelete = "DELETE FROM appstores WHERE id = ?";
                if ($deleteStmt = $conn->prepare($sqlDelete)) {
                    $deleteStmt->bind_param("i", $id);
                    if ($deleteStmt->execute()) {
                        // Check if files exist and delete them
                        if (!empty($image1) && file_exists($filePath1)) {
                            unlink($filePath1);
                        }
                        if (!empty($image2) && file_exists($filePath2)) {
                            unlink($filePath2);
                        }
                        header('Location: app.php'); // Redirect after deletion
                        exit();
                    } else {
                        echo 'Error deleting record: ' . $deleteStmt->error;
                    }
                    $deleteStmt->close();
                } else {
                    echo 'Error preparing delete query: ' . $conn->error;
                }
            } else {
                echo 'No record found with the given ID.';
            }
        } else {
            echo 'Error executing query to fetch images: ' . $stmt->error;
        }
        $stmt->close();
    } else {
        echo 'Error preparing query: ' . $conn->error;
    }
} else {
    echo 'Invalid request: ID missing.';
}


  /*  ---------------Deleting Advertiser --- */   

if (isset($_GET['id']) && isset($_GET['action']) && $_GET['action'] == 'delete') {
    $id = $_GET['id'];

    // Prevent SQL injection
    $id = intval($id);

    $sql = "DELETE FROM advertiser WHERE id = $id";
    if ($conn->query($sql) === TRUE) {
        echo "<script>
                Swal.fire({
                    title: 'Deleted!',
                    text: 'Record has been deleted successfully.',
                    icon: 'success'
                }).then(() => {
                    window.location='advertiser.php';
                });
              </script>";
    } else {
        echo "<script>
                Swal.fire({
                    title: 'Error!',
                    text: 'Failed to delete record.',
                    icon: 'error'
                });
              </script>";
    }
}
$conn->close();
?>
