<?php
if (!defined('ABSPATH')) {
    exit;
}

    $error_message = '';
// Check user capability
if (!current_user_can('manage_options')) {
    $error_message = 'User not authorized - Administrator can send logo to us.';
}

function brandabean_handle_coffee_logo_upload() {
    // Security check
    if (!isset($_POST['brandabean_coffee_logo_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['brandabean_coffee_logo_nonce'])), 'brandabean_coffee_logo_upload')) {
       wp_die('Security check failed.');
    }

    // Get WooCommerce store email
    $email = get_option('admin_email');

    // Validate email
    if (!is_email($email)) {
        wp_die("Error: Invalid store email. To fix, go to WooCommerce settings.");
    }

    // Ensure file is uploaded
    if (!isset($_FILES["image"]) || empty($_FILES["image"]["name"])) {
        wp_die("Error: No file uploaded.");
    }

    // Check for upload errors
    if (isset($_FILES["image"]) || !empty($_FILES["image"]["error"])) {
    $file_error = sanitize_text_field($_FILES["image"]["error"]);
    }
    
    //unncessary but plugin check wants the isset
    if (isset($_FILES["image"]) || !empty($_FILES["image"]["tmp_name"])) {
    if (!file_exists(sanitize_text_field($_FILES["image"]["tmp_name"]))) {
    wp_die("Error: File missing after upload.");
        }
    }
    
    if ($file_error > 0) { 
        $error_messages = [
            UPLOAD_ERR_INI_SIZE   => "The file exceeds the upload_max_filesize directive in php.ini.",
            UPLOAD_ERR_FORM_SIZE  => "The file exceeds the MAX_FILE_SIZE directive in the HTML form.",
            UPLOAD_ERR_PARTIAL    => "The file was only partially uploaded.",
            UPLOAD_ERR_NO_FILE    => "No file was uploaded.",
            UPLOAD_ERR_NO_TMP_DIR => "Missing temporary folder on server.",
            UPLOAD_ERR_CANT_WRITE => "Failed to write file to disk. Check directory permissions.",
            UPLOAD_ERR_EXTENSION  => "A PHP extension stopped the upload."
        ];
        wp_die("Error: " . esc_html($error_messages[$file_error] ?? "Unknown upload error."));
    }

    // Sanitize file data
    if (!isset($_FILES["image"]) || !empty($_FILES["image"]["name"])) {
    $file_name = sanitize_file_name($_FILES["image"]["name"]);
    } else { wp_die('No image name'); }
    if (!isset($_FILES["image"]) || !empty($_FILES["image"]["tmp_name"])) {
    $file_tmp  = sanitize_text_field($_FILES["image"]["tmp_name"]);
    } else { wp_die('No image tmp_name'); }
    if (!isset($_FILES["image"]) || !empty($_FILES["image"]["size"])) {
    $file_size = is_int($_FILES["image"]["size"]);
    } else { wp_die('No image size'); }

    // Validate file type
    $file_info = wp_check_filetype($file_name, [
        'jpg'  => 'image/jpeg',
        'jpeg' => 'image/jpeg',
        'png'  => 'image/png'
    ]);

    if (!$file_info['ext']) {
        wp_die("Error: Invalid file type. Only JPG and PNG allowed.");
    }

    // Ensure valid file
    if (!file_exists($file_tmp) || !is_uploaded_file($file_tmp)) {
        wp_die("Error: Invalid file upload.");
    }

    $image_data = getimagesize($file_tmp);
    if (!$image_data) {
        wp_die("Error: Invalid image file.");
    }

    // Upload to WordPress media
    require_once ABSPATH . 'wp-admin/includes/file.php';
    
    // Check if the file exists before processing
    if (!file_exists(sanitize_text_field($_FILES["image"]["tmp_name"]))) {
    wp_die("Error: File missing before processing final upload.");
    }
    
    $upload_overrides = ['test_form' => false];
    $uploaded_file = wp_handle_upload($_FILES["image"], $upload_overrides);

    if (!$uploaded_file || isset($uploaded_file['error'])) {
        wp_die("Error: Upload failed - " . esc_html($uploaded_file['error']));
    }

    $file_path = $uploaded_file['file'];
    $file_url  = $uploaded_file['url'];
    $file_type = $uploaded_file['type'];

    // Insert image into Media Library
    $attachment = [
        'post_mime_type' => $file_type,
        'post_title'     => sanitize_file_name($file_name),
        'post_content'   => '',
        'post_status'    => 'inherit'
    ];

    $file_id = wp_insert_attachment($attachment, $file_path);
    require_once ABSPATH . 'wp-admin/includes/image.php';

    $attach_data = wp_generate_attachment_metadata($file_id, $file_path);
    wp_update_attachment_metadata($file_id, $attach_data);

    $image_url = wp_get_attachment_url($file_id);

    if (!$image_url) {
        wp_die("Error: Image attachment failed.");
    }

    // Send email notification - user has to check box to opt-in to sending their store email and logo image before form will process on front end (see line 180)
    $to      = "logosubmit@oldchicagocoffee.com"; // this is our public email, ok if seen in source.
    $subject = "New Logo Sent from " . get_bloginfo('name');
    $message = "Store Email: " . sanitize_email($email) . "\n\nLogo: " . esc_url($image_url);
    $headers = ['Content-Type: text/html; charset=UTF-8', 'From: ' . sanitize_email($email)];

    if (wp_mail($to, $subject, $message, $headers)) {
        echo '<p style="color: green; font-size: 24px;">Image sent successfully. The final step, if not already done, is to visit <b>Manage Your Products</b>.</p>';
    } else {
        echo '<p style="color: red; font-size: 24px;">Error sending email.</p>';
    }
}
add_action('admin_post_brandabean_coffee_logo_upload', 'brandabean_handle_coffee_logo_upload');
        $adm_url = admin_url( 'admin.php?page=' );
        $plu_url = plugin_dir_url(__FILE__);

    //upload of a logo image - verify nonce to activate function
    if (isset($_SERVER["REQUEST_METHOD"]) && $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit_logo'])) {
           if (!isset($_POST['brandabean_coffee_logo_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['brandabean_coffee_logo_nonce'])), 'brandabean_coffee_logo_upload')) {
            echo '<p style="color: red;">Security check failed on post.</p>';
            return;
        } else {
        brandabean_handle_coffee_logo_upload();
        }
    }
//start the div navigation menu and upload form
?>
<div class="wrap">
            <img src="<?php echo esc_url($plu_url) . 'static-images/dlogowide.png'; ?>" alt="Logo" style="max-width:100%; height:auto;"><br>
            <a href="<?php echo esc_url($adm_url) . 'coffee-dropship-trademarks'; ?>">
            <img src="<?php echo esc_url($plu_url) . 'static-images/button1.png'; ?>" alt="Read Me" style="max-width:100%; height:auto;"></a>
	    	<a href="<?php echo esc_url($adm_url) . 'coffee-dropship-how-this-works'; ?>">
            <img src="<?php echo esc_url($plu_url) . 'static-images/button4.png'; ?>" alt="How This Works" style="max-width:100%; height:auto;"></a>
	        <a href="<?php echo esc_url($adm_url) . 'brandabean-coffee-dropship_menu'; ?>">
            <img src="<?php echo esc_url($plu_url) . 'static-images/button2.png'; ?>" alt="Logo Upload" style="max-width:100%; height:auto;"></a>
            <img src="<?php echo esc_url($plu_url) . 'static-images/button3a.png'; ?>" alt="Logo Send" style="max-width:100%; height:auto;">
            <a href="<?php echo esc_url($adm_url) . 'coffee-dropship-products'; ?>">
            <img src="<?php echo esc_url($plu_url) . 'static-images/button5.png'; ?>" alt="Manage Products" style="max-width:100%; height:auto;"></a>
            </div>

<div id="upload-status"></div>
<div><h3>Send Us Your Logo</h3>
<img align="left" src="<?php echo esc_url($plu_url) . 'static-images/transfer.png'; ?>" alt="Logo Send" style="max-width:90%; height:auto;">
    <h4>Send your logo that will be printed on the coffee products.  This should be the same logo or image you will use on the products in your site.</h4>
    <p style="font-size: 16px;">Although you may have already uploaded your logo on a previous page, that does not send the logo to us directly. <br>
    The &quot; Add Your Logo To Products &quot; only places your logo or image upload on the products in your site.
    <br>We also need your logo sent in order to print it on the products.<br><br>When your site receives an order we print your sent image on the actual products shipped.<br>
    If you don't send us the logo we can't ship your orders.<br><br>This upload will include your store's email address and send to us.  
    <br>An auto responder will auto-reply to let you know your logo was received on our end.<br>If you don't receive the automatic reply message at your store's email reach out to us for help.<br>
    <br><br>NOTE: If your hosting does not support outgoing email the message to us with your logo will never send.
    <br>If you can update an order and your customer receives your message (shipping notice, receipt, etc.) your site email is working just fine.</p>
    </div>
            <label>
            <input type="checkbox" id="enableButtonCheckbox"> By checking this box I agree to share my store's email address and logo or image.  I also opt-in to receiving email regarding my logo and my customer's orders.
            </label>

                <br>

<form id="upload-form" action="" method="post" enctype="multipart/form-data">
    <input type="hidden" name="action" value="brandabean_coffee_logo_upload">
    <?php wp_nonce_field('brandabean_coffee_logo_upload', 'brandabean_coffee_logo_nonce'); ?>
    <label for="image">Find Your Logo Image: </label>
    <input type="file" name="image" id="image" accept=".jpg, .jpeg, .png" required><br><br>
    <input type="submit" name="submit_logo"  value="Send Us Your Logo" id="submitButton" disabled>
</form>
<?php
 if ($error_message): ?>
    <div class="error">
        <p><?php echo esc_html($error_message); ?></p>
    </div>
<?php else: ?>
    <?php endif; ?>