<?php
session_start();
include 'includes/dbconn.php'; // Ensure this is the correct path to your database connection file

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["file"])) {
    // Get company_id from the session
    $company_id = isset($_SESSION['company_id']) ? $_SESSION['company_id'] : null;

    // Fetch company name from the database
    $company_name = ''; // Default to an empty string if not found
    if ($company_id) {
        $stmt = $conn->prepare("SELECT name FROM companies WHERE company_id = ?");
        $stmt->bind_param("i", $company_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result && $row = $result->fetch_assoc()) {
            $company_name = $row['name'];
        }
        $stmt->close();
    }

    if (!$company_name) {
        echo "Company name not found.";
        exit;
    }

    // Sanitize company name to be file-system friendly
    $company_name = preg_replace('/[^A-Za-z0-9\-]/', '', $company_name);

    $target_dir = "uploads/"; // Ensure this directory exists and is writable
    $base_filename = 'transactions - ' . $company_name . '-' . $company_id . '.csv';
    $target_file = $target_dir . $base_filename;

    // Create uploads directory if it doesn't exist
    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0755, true);
    }

    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        exit;
    }

    // Check if the file is a CSV
    $fileType = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
    if (strtolower($fileType) !== 'csv') {
        echo "Sorry, only CSV files are allowed.";
        exit;
    }

    // Attempt to move the uploaded file to the target directory
    if (!move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        error_log("Could not move file to $target_file");
        error_log("File upload error: " . $_FILES["file"]["error"]);
        echo "Sorry, there was an error uploading your file.";
        exit;
    }

    echo "The file " . htmlspecialchars($base_filename) . " has been uploaded.";

    // Read the CSV file and store its data
    $csvData = []; // Initialize an array to hold CSV data
    if (($handle = fopen($target_file, 'r')) !== FALSE) {
        while (($data = fgetcsv($handle)) !== FALSE) {
            $csvData[] = $data;
        }
        fclose($handle);
    }

    // Store the data in a session variable
    $_SESSION['csv_data'] = $csvData;

    // Redirect to the page for editing the CSV data
    header("Location: edit_csv_data.php");
    exit;
}
?>
