<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Database Connection
$servername = "localhost";
$username = "root"; 
$password = "";     
$dbname = "grovia";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $company_name = $_POST['company_name'];
    
    // 1. Sanitize the company name for a folder name (removes special characters and spaces)
    $folder_name = preg_replace('/[^A-Za-z0-9_\-]/', '_', $company_name);
    $base_dir = "../uploads/company_data/";
    $temp_dir="uploads/company_data/";
    $company_dir = $base_dir . $folder_name . "/";
    $upload_dir = $temp_dir . $folder_name . "/";

    // 2. Create the directory if it doesn't exist
    if (!is_dir($company_dir)) {
        // 0777 gives full read/write permissions
        mkdir($company_dir, 0777, true); 
    }

    // 3. Define target paths for the logos inside the new folder
    $left_logo_name = "left_logo_" . time() . "_" . basename($_FILES["left_logo"]["name"]);
    $left_target = $company_dir . $left_logo_name;
    $upload_left_target = $upload_dir . $left_logo_name;
    
    $right_logo_name = "right_logo_" . time() . "_" . basename($_FILES["right_logo"]["name"]);
    $right_target = $company_dir . $right_logo_name;
    $upload_right_target = $upload_dir . $right_logo_name;

    // 4. Move uploaded files to the new company-specific folder
    if (move_uploaded_file($_FILES["left_logo"]["tmp_name"], $left_target) && 
        move_uploaded_file($_FILES["right_logo"]["tmp_name"], $right_target)) {
        
        // Escape for SQL safety
        $safe_company_name = $conn->real_escape_string($company_name);
        
        // 5. SQL Insert
        $sql = "INSERT INTO company (company_name, left_logo, right_logo) 
                VALUES ('$safe_company_name', '$upload_left_target', '$upload_right_target')";

        if ($conn->query($sql) === TRUE) {
            $_SESSION['msg'] = "Success! Files has been Uploaded on server";
            $_SESSION['msg_type'] = "success";
        } else {
            $_SESSION['msg'] = "DB Error: " . $conn->error;
            $_SESSION['msg_type'] = "error";
        }
    } else {
        $_SESSION['msg'] = "Failed to upload images to the company folder. Check folder permissions.";
        $_SESSION['msg_type'] = "error";
    }

    $conn->close();
    header("Location: ../add-company.php");
    exit();
}
?>