<?php
// Ensure error reporting is enabled for development
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);

// Include your database connection file.
// Assumes 'databaseconnect.php' is in the parent directory of the 'addrow' folder.
include '../databaseconnect.php';

$message = ''; // Variable to store feedback messages

// Function to convert a string into a URL-friendly slug
function createSlug($string) {
    // Convert to lowercase and trim whitespace
    $string = strtolower(trim($string));
    // Replace non-alphanumeric characters (except spaces and hyphens) with nothing
    $string = preg_replace('/[^a-z0-9\s-]/', '', $string);
    // Replace spaces with a single hyphen
    $string = preg_replace('/\s+/', '-', $string);
    // Replace multiple hyphens with a single hyphen
    $string = preg_replace('/-+/', '-', $string);
    return $string;
}

// Define the upload directory.
// __DIR__ is the directory of the current script (e.g., /path/to/webroot/addrow/).
// So, the images will be uploaded to /path/to/webroot/addrow/images/sitemap/.
$upload_dir = __DIR__ . '/images/sitemap/';

// Create the directory if it doesn't exist
if (!is_dir($upload_dir)) {
    if (!mkdir($upload_dir, 0777, true)) { // 0777 grants full permissions, adjust for production if needed
        $message .= "Error: Could not create upload directory: " . $upload_dir . ". Please check folder permissions. ";
    }
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Collect and sanitize form data
    $user_input_urlslist = $_POST['urlslist'];
    $urlslist = createSlug($user_input_urlslist); // Convert user input to slug

    $desc1 = mysqli_real_escape_string($con, $_POST['desc1']);
    $tracklist = mysqli_real_escape_string($con, $_POST['tracklist']);
    $musicstyle = mysqli_real_escape_string($con, $_POST['musicstyle']);
    $lyrics = mysqli_real_escape_string($con, $_POST['lyrics']);
    $tags = mysqli_real_escape_string($con, $_POST['tags']);
    $album = mysqli_real_escape_string($con, $_POST['album']);
    $industry = mysqli_real_escape_string($con, $_POST['industry']);
    // Convert year to int or NULL if empty
    $year = !empty($_POST['year']) ? (int)$_POST['year'] : NULL;
    $language = mysqli_real_escape_string($con, $_POST['language']);
    $stars = mysqli_real_escape_string($con, $_POST['stars']);
    $musicdirectors = mysqli_real_escape_string($con, $_POST['musicdirectors']);
    $seotitle = mysqli_real_escape_string($con, $_POST['seotitle']);

    $image_path_for_db = NULL; // Default to NULL for image

    // Handle image upload
    if (isset($_FILES['image_upload']) && $_FILES['image_upload']['error'] === UPLOAD_ERR_OK) {
        $file_tmp = $_FILES['image_upload']['tmp_name'];
        $file_name = $_FILES['image_upload']['name'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        // Generate a unique filename to prevent overwrites
        $unique_file_name = uniqid('img_', true) . '.' . $file_ext;
        $destination_path = $upload_dir . $unique_file_name;

        // Ensure the filename is safe for the filesystem and URL
        // (uniqid already provides a safe base, just ensuring it's not tampered with)
        $safe_unique_file_name = filter_var($unique_file_name, FILTER_SANITIZE_URL);
        $destination_path = $upload_dir . $safe_unique_file_name;

        if (move_uploaded_file($file_tmp, $destination_path)) {
            // Store the path in the database as 'addrow/images/sitemap/filename.ext'
            // This is relative to the web root if 'addrow' is at the web root.
            $image_path_for_db = 'addrow/images/sitemap/' . $safe_unique_file_name;
        } else {
            $message .= "Error uploading file. ";
        }
    }

    // Construct the INSERT query, handling NULL values explicitly
    $sql = "INSERT INTO sitemapcomio (URLSLIST, desc1, tracklist, musicstyle, lyrics, tags, album, industry, year, language, stars, musicdirectors, image, seotitle) VALUES (
        " . ($urlslist ? "'" . $urlslist . "'" : "NULL") . ",
        " . ($desc1 ? "'" . $desc1 . "'" : "NULL") . ",
        " . ($tracklist ? "'" . $tracklist . "'" : "NULL") . ",
        " . ($musicstyle ? "'" . $musicstyle . "'" : "NULL") . ",
        " . ($lyrics ? "'" . $lyrics . "'" : "NULL") . ",
        " . ($tags ? "'" . $tags . "'" : "NULL") . ",
        " . ($album ? "'" . $album . "'" : "NULL") . ",
        " . ($industry ? "'" . $industry . "'" : "NULL") . ",
        " . ($year !== NULL ? $year : "NULL") . ",
        " . ($language ? "'" . $language . "'" : "NULL") . ",
        " . ($stars ? "'" . $stars . "'" : "NULL") . ",
        " . ($musicdirectors ? "'" . $musicdirectors . "'" : "NULL") . ",
        " . ($image_path_for_db ? "'" . $image_path_for_db . "'" : "NULL") . ",
        " . ($seotitle ? "'" . $seotitle . "'" : "NULL") . "
    )";

    // Execute the query
    if (mysqli_query($con, $sql)) {
        $message .= "New record added successfully!";
    } else {
        $message .= "Error: " . $sql . "<br>" . mysqli_error($con);
    }

    mysqli_close($con); // Close the connection after use
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add New Row to sitemapcomio</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background-color: #f4f4f4; }
        .container { max-width: 900px; margin: auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); }
        h2 { text-align: center; color: #333; margin-bottom: 30px;}
        .message { padding: 10px; margin-bottom: 20px; border-radius: 5px; text-align: center; font-weight: bold; }
        .success { background-color: #d4edda; color: #155724; border: 1px solid #badbcc; }
        .error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .form-row { display: flex; flex-wrap: wrap; gap: 20px; margin-bottom: 10px; }
        .form-group { flex: 1 1 calc(50% - 10px); /* Two columns, accounting for gap */
                      min-width: 300px; /* Minimum width for readability */
                      margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; color: #555; }
        input[type="text"], input[type="number"], textarea, input[type="file"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
            font-size: 14px;
        }
        textarea { resize: vertical; min-height: 80px; }
        input[type="submit"] {
            background-color: #007bff;
            color: white;
            padding: 12px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            width: 100%;
            margin-top: 20px;
        }
        input[type="submit"]:hover {
            background-color: #0056b3;
        }
        /* Style for file input to make it consistent */
        input[type="file"] {
            padding: 8px;
            height: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>Add New Row to `sitemapcomio`</h2>

        <?php if ($message): ?>
            <div class="message <?php echo (strpos($message, 'Error') !== false) ? 'error' : 'success'; ?>">
                <?php echo $message; ?>
            </div>
        <?php endif; ?>

        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
            <div class="form-row">
                <div class="form-group">
                    <label for="urlslist">URLSLIST (e.g., "Interstellar BGM" will become "interstellar-bgm")</label>
                    <input type="text" id="urlslist" name="urlslist" placeholder="Enter a descriptive string for the URL slug" required>
                </div>

               
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label for="desc1">desc1</label>
                    <textarea id="desc1" name="desc1" placeholder="Short description"></textarea>
                </div>

               
            </div>

            <div class="form-row">
                
                <div class="form-group">
                    <label for="language">language</label>
                    <input type="text" id="language" name="language" placeholder="e.g., English, Hindi">
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label for="lyrics">lyrics</label>
                    <textarea id="lyrics" name="lyrics" placeholder="Full lyrics of a song"></textarea>
                </div>

                <div class="form-group">
                    <label for="tags">tags</label>
                    <textarea id="tags" name="tags" placeholder="Any known spelling mistakes"></textarea>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label for="album">album</label>
                    <input type="text" id="album" name="album" placeholder="Album name or related collection"></input>
                </div>

              
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label for="year">year</label>
                    <input type="number" id="year" name="year" placeholder="e.g., 2023">
                </div>

                <div class="form-group">
                    <label for="stars">stars</label>
                    <input  type="text" id="stars" name="stars" placeholder="e.g., Actor A, Actress B, Singer C"></input>
                </div>
            </div>

            <div class="form-group">
                <label for="musicdirectors">musicdirectors</label>
                <input  type="text" id="musicdirectors" name="musicdirectors" placeholder="Names of music directors"></input>
            </div>

            <div class="form-group">
                <label for="image_upload">Image (Optional):</label>
                <input type="file" id="image_upload" name="image_upload" accept="image/*">
            </div>

            <input type="submit" value="Add New Row">
        </form>
    </div>
</body>
</html>