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

function handleFileUpload($uploadDir, $fileInputName) {
    if (!empty($_FILES[$fileInputName]["name"])) {
        $fileName = time() . "_" . basename($_FILES[$fileInputName]["name"]);
        $targetPath = $uploadDir . $fileName;
        if (move_uploaded_file($_FILES[$fileInputName]["tmp_name"], $targetPath)) {
            return $fileName;
        } else {
            echo "Error uploading file: " . $_FILES[$fileInputName]["name"];
            exit();
        }
    }
    return null;
}

function deleteOldImage($conn, $id, $columnName, $uploadDir) {
    $sql = "SELECT $columnName FROM appstores WHERE id = ?";
    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->bind_result($oldImage);
        $stmt->fetch();
        $stmt->close();
        
        if (!empty($oldImage)) {
            $oldImagePath = $uploadDir . $oldImage;
            if (file_exists($oldImagePath)) {
                unlink($oldImagePath);
            }
        }
    }
}

// Function to Generate Short URL
function shortenURL($long_url) {
    if (empty($long_url)) {
        return null;
    }
    return substr(md5(uniqid($long_url, true)), 0, 6); // Generate a 6-character short URL
}

if (isset($_POST['updateEvent'])) {
    // Get the data from the POST request
    $id = $_POST['id'];
    $name = $_POST['name'];
    $advertiser = $_POST['advertiser'];
    $description = $_POST['description'];

    // Fetch existing long URLs from the database
    $query = "SELECT image1_long_url, image2_long_url, image1, image2 FROM appstores WHERE id=?";
    $stmt = $conn->prepare($query);
    if (!$stmt) {
        die('MySQL prepare error: ' . $conn->error);
    }
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    
    if (!$row) {
        die('Record not found');
    }

    // Use existing long URLs or new ones from the form
    $image1_long_url = !empty($_POST['image1_long_url']) ? $_POST['image1_long_url'] : $row['image1_long_url'];
    $image2_long_url = !empty($_POST['image2_long_url']) ? $_POST['image2_long_url'] : $row['image2_long_url'];

    // Generate short URLs
    $image1_link = shortenURL($image1_long_url);
    $image2_link = shortenURL($image2_long_url);

    // Handling image uploads
    $uploadDir = "upload/";
    $image1 = !empty($_FILES['image1']['name']) ? $uploadDir . basename($_FILES['image1']['name']) : $row['image1'];
    $image2 = !empty($_FILES['image2']['name']) ? $uploadDir . basename($_FILES['image2']['name']) : $row['image2'];

    // Debug: Check the file paths
    if (empty($image1) || empty($image2)) {
        echo "No image uploaded, retaining existing image paths.";
    } else {
        echo "Image 1 path: " . $image1 . "<br>";
        echo "Image 2 path: " . $image2 . "<br>";
    }

    // Move uploaded files if new images are uploaded
    if (!empty($_FILES['image1']['name']) && move_uploaded_file($_FILES['image1']['tmp_name'], $image1)) {
        $image1 = basename($_FILES['image1']['name']);  // Get the filename after upload
    } else {
        $image1 = $row['image1'];  // Retain the existing image if no new upload
    }

    if (!empty($_FILES['image2']['name']) && move_uploaded_file($_FILES['image2']['tmp_name'], $image2)) {
        $image2 = basename($_FILES['image2']['name']);  // Get the filename after upload
    } else {
        $image2 = $row['image2'];  // Retain the existing image if no new upload
    }

    // Debug: Check if images are correctly set
    echo "Updated Image 1: " . $image1 . "<br>";
    echo "Updated Image 2: " . $image2 . "<br>";

    // Update Query
    $sql = "UPDATE appstores SET name=?, advertiser_name=?, description=?, image1=?, image2=?, image1_link=?, image2_link=?, image1_long_url=?, image2_long_url=? WHERE id=?";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        die('MySQL prepare error: ' . $conn->error);
    }
    $stmt->bind_param("sssssssssi", $name, $advertiser, $description, $image1, $image2, $image1_link, $image2_link, $image1_long_url, $image2_long_url, $id);

    if ($stmt->execute()) {
        echo "<script>alert('Updated Successfully!'); window.location.href='app.php';</script>";
    } else {
        echo "Error: " . $stmt->error;
    }
    
    $stmt->close();
    $conn->close();
}

// Fetch advertiser data for editing
if (isset($_GET['id'])) {
    $id = $_GET['id'];
    $sql = "SELECT * FROM advertiser WHERE id = $id";
    $result = $conn->query($sql);
    $row = $result->fetch_assoc();
?>
    <form action="edit.php?id=<?php echo $id; ?>" method="POST" enctype="multipart/form-data">
        <div class="form-group">
            <label for="name">Advertiser Name:</label>
            <input type="text" class="form-control" id="name" name="name" value="<?php echo $row['name']; ?>" required>
        </div>
        <div class="form-group">
            <label for="image">Image:</label>
            <input type="file" class="form-control" id="image" name="image">
            <img src="<?php echo $row['image']; ?>" style="width:100px;">
        </div>
        <button type="submit" class="btn btn-primary" name="update">Update</button>
    </form>
<?php
}

// Update the advertiser data
if (isset($_POST['update'])) {
    $name = $_POST['name'];
    $image = $_FILES['image']['name'];
    $image_tmp = $_FILES['image']['tmp_name'];

    if ($image) {
        $target_dir = "uploads/";
        $target_file = $target_dir . basename($image);
        move_uploaded_file($image_tmp, $target_file);
        $image_path = $target_file;
    } else {
        $image_path = $row['image'];
    }

    $sql = "UPDATE advertiser SET name='$name', image='$image_path' WHERE id=$id";
    if ($conn->query($sql) === TRUE) {
        echo "<script>alert('Record updated successfully');window.location='admin.php';</script>";
    } else {
        echo "Error: " . $conn->error;
    }
}

?>
