<?php
// Start output buffering
ob_start();

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Include database configuration
require("db_config.php");

// Check if the database connection is working
if (!$conn) {
    die("Database connection failed: " . mysqli_connect_error());
}

// Function to handle file upload
function handleFileUpload($file, $uploadDir) {
    if ($file['error'] === UPLOAD_ERR_OK) {
        $fileTmpPath = $file['tmp_name'];
        $fileName = time() . "_" . basename($file['name']);
        $fileSize = $file['size'];
        $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        $allowedExts = ['jpg', 'jpeg', 'png', 'gif'];

        if (!in_array($fileExtension, $allowedExts)) {
            return "Invalid file type.";
        }

        if ($fileSize > 3000000) {
            return "File is too large.";
        }

        $destPath = $uploadDir . $fileName;
        if (move_uploaded_file($fileTmpPath, $destPath)) {
            return $fileName;
        } else {
            return "Error moving file.";
        }
    } else {
        return "File upload error: " . $file['error'];
    }
}

// Check if Add Ads form was submitted
if (isset($_POST["addads"])) {
    // Sanitize input data
    $name = htmlspecialchars(trim($_POST["name"]));
    $advertiser_name = htmlspecialchars(trim($_POST["advertiser"]));

    // Upload Image 1
    $image1 = handleFileUpload($_FILES["image1"], "upload/");
    if (strpos($image1, "Error") !== false) {
        die("File upload failed for image1: $image1");
    }

    // Insert into the database
    $sql = "INSERT INTO appstores (name, image1, advertiser_name) 
            VALUES (?, ?, ?)";

    if ($stmt = $conn->prepare($sql)) {
        // Bind parameters
        $stmt->bind_param("sss", $name, $image1, $advertiser_name);

        // Execute the query
        if ($stmt->execute()) {
            header("Location: app.php");
            exit();
        } else {
            die("Error: " . $stmt->error);
        }
    } else {
        die("Failed to prepare the SQL statement: " . $conn->error);
    }
}
?>