<?php
require 'db.php'; // Database connection

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

// Check if the form is submitted
if (isset($_POST['submit'])) {
    // Check if a file is uploaded
    if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
        
        // Get file details
        $filePath = $_FILES['file']['tmp_name'];
        $fileName = $_FILES['file']['name'];
        $fileSize = $_FILES['file']['size'];

        // Generate a unique ID for the file
        $uniqueId = uniqid();

        // Define the upload directory
        $uploadDir = 'uploads/';
        $uploadPath = $uploadDir . $fileName;

        // Check if file already exists
        if (file_exists($uploadPath)) {
            die("File already exists.");
        }

        // Move uploaded file to the uploads directory
        if (!move_uploaded_file($filePath, $uploadPath)) {
            die("Error moving file to upload directory.");
        }

        // Insert file details into the database
        try {
            $stmt = $pdo->prepare("INSERT INTO files (unique_id, file_name, file_path, file_size) VALUES (?, ?, ?, ?)");
            $stmt->execute([$uniqueId, $fileName, $uploadPath, $fileSize]);

            // Check if the insert was successful
            if ($stmt->rowCount() > 0) {
                echo "File uploaded and data inserted successfully!";
            } else {
                echo "File uploaded but data insertion failed.";
            }
        } catch (PDOException $e) {
            die("Error with database query: " . $e->getMessage());
        }

        // Provide a unique link for sharing
        $link = "https://shareandhide.dev.bestseocompanymiami.com/access.php?file_id=" . $uniqueId;
        echo "Share this link: <a href='$link'>$link</a>";
    } else {
        die("No file uploaded or there was an error during upload.");
    }
} else {
    die("Form not submitted properly.");
}
?>