<?php
/*
 * Million Dollar Script Two
 *
 * @author      Ryan Rhode
 * @copyright   (C) 2025, Ryan Rhode
 * @license     https://opensource.org/licenses/GPL-3.0 GNU General Public License, version 3
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *
 *    Million Dollar Script
 *    Pixels to Profit: Ignite Your Revolution
 *    https://milliondollarscript.com/
 *
 */

use MillionDollarScript\Classes\Data\Options;
use MillionDollarScript\Classes\Language\Language;
use MillionDollarScript\Classes\Orders\Orders;
use MillionDollarScript\Classes\Payment\Currency;
use MillionDollarScript\Classes\System\Functions;
use MillionDollarScript\Classes\System\Utility;

defined( 'ABSPATH' ) or exit;

mds_wp_login_check();

require_once MDS_CORE_PATH . "include/ads.inc.php";

global $BID, $f2;

$BID = $f2->bid();

if ( class_exists( 'Imagick' ) ) {
	$imagine = new Imagine\Imagick\Imagine();
} else if ( function_exists( 'gd_info' ) ) {
	$imagine = new Imagine\Gd\Imagine();
}

$banner_data  = load_banner_constants( $BID );
$has_packages = banner_get_packages( $BID );

$size        = [];
$reqsize     = [];
$pixel_count = 0;
$block_size  = 0;
if ( isset( $_FILES['graphic'] ) && $_FILES['graphic']['tmp_name'] != '' ) {
	// Use comprehensive security validation
	$validation = \MillionDollarScript\Classes\System\FileValidator::validate_image_upload( $_FILES['graphic'] );
	
	if ( ! $validation['valid'] ) {
		global $mds_error;
		$mds_error = Language::get( 'File upload error: ' ) . $validation['error'];
		
		// Log security violation attempt
		error_log( 'MDS Security: Invalid upload attempt by user ' . get_current_user_id() . ': ' . $validation['error'] );
		
		// Don't return early - let the page display with error message
	}

	// File passed all security validations, proceed with upload processing
	global $wpdb;
	
	// Only proceed with file processing if validation passed
	if ( $validation['valid'] ) {
		// After all security validations pass, ensure the file is copied to the expected standard location
		// This ensures compatibility with existing code that expects files in the standard images directory
		$standard_upload_dir = Utility::get_upload_path() . "images/";
		$standard_filename = 'tmp_' . Orders::get_current_order_id() . '.png';
		$standard_file_path = $standard_upload_dir . $standard_filename;
		
		// Ensure the standard directory exists
		if ( ! file_exists( $standard_upload_dir ) ) {
			wp_mkdir_p( $standard_upload_dir );
		}
		
		// Copy the validated uploaded file to the standard location expected by the rest of the system
		if ( ! copy( $_FILES['graphic']['tmp_name'], $standard_file_path ) ) {
			global $mds_error;
			$mds_error = Language::get( 'Failed to prepare uploaded file for processing. Please try again.' );
		}
		
		$order_id      = Orders::get_current_order_id();
		$image_data    = file_get_contents( $_FILES['graphic']['tmp_name'] );
		$ad_id         = insert_ad_data( $order_id, false, $image_data );
		$sql_completed = $wpdb->prepare( "SELECT * FROM " . MDS_DB_PREFIX . "orders WHERE user_id=%d AND ad_id=%d", get_current_user_id(), intval( $ad_id ) );
		$row           = $wpdb->get_row( $sql_completed, ARRAY_A );
		if ( $row ) {
			if ( $row['status'] != 'completed' ) {
				$blocks                    = explode( ',', $row['blocks'] );
				$size                      = Utility::get_pixel_image_size( $order_id );
				$pixels                    = $size['x'] * $size['y'];
				$_REQUEST['change_pixels'] = true;

			}
		}
	}
}

$tmp_image_file = Orders::get_tmp_img_name();

if ( $tmp_image_file && file_exists( $tmp_image_file ) ) {
	try {
		$image = $imagine->open( $tmp_image_file );
	} catch ( Exception $e ) {
		if ( isset( $_POST['mds_dest'] ) && isset( $_FILES ) ) {
			global $mds_error;
			$mds_error = Language::get( "There was an error with the image file." );

			// Don't return early - let the page display with error message
		}
	}
}

$cannot_get_package = false;

$order_id = Orders::get_current_order_id();

if ( $order_id == null ) {
	Orders::no_orders();
	wp_die();
}

$package_id = intval( $_REQUEST['package'] ?? 0 );
if ( $package_id == 0 ) {
	$package_id = get_order_package( $order_id );
}

if ( $has_packages && ! empty( $package_id ) ) {

	// check to make sure this advertiser can order this package
	if ( can_user_get_package( get_current_user_id(), $package_id ) ) {

		$sql = $wpdb->prepare( "SELECT quantity FROM " . MDS_DB_PREFIX . "orders WHERE order_id=%d", $order_id );
		$quantity = $wpdb->get_var( $sql );
		if ( $wpdb->last_error ) {
			wp_die( esc_html( $wpdb->last_error ) );
		}

		$block_count = $quantity / ( $banner_data['block_width'] * $banner_data['block_height'] );

		// Now update the order (overwrite the total & days_expire with the package)
		$pack  = get_package( $package_id );
		$total = $pack['price'] * $block_count;

		// convert & round off
		$total = Currency::convert_to_default_currency( $pack['currency'], $total );

		$wpdb->update(
			MDS_DB_PREFIX . 'orders',
			[
				'package_id' => $package_id,
				'price' => floatval( $total ),
				'days_expire' => intval( $pack['days_expire'] ),
				'currency' => Currency::get_default_currency()
			],
			[ 'order_id' => intval( $order_id ) ],
			[ '%d', '%f', '%d', '%s' ],
			[ '%d' ]
		);
		if ( $wpdb->last_error ) {
			wp_die( esc_html( $wpdb->last_error ) );
		}
	} else {
		$selected_pack       = $package_id;
		$_REQUEST['package'] = '';
		$cannot_get_package  = true;
	}
}

// After processing file upload successfully, we don't need to return early
// The page should continue to show the uploaded image and "Write Your Ad" button

require_once MDS_CORE_PATH . "html/header.php";

global $wpdb;

// check to make sure MIN_BLOCKS were selected.
$current_user_id = get_current_user_id();
$order_id        = intval( $order_id );
$BID             = intval( $BID );

// Use the same logic as order.php - check for reserved blocks for this user and banner
// Then also check with order_id as a fallback
$sql = $wpdb->prepare( "SELECT block_id FROM " . MDS_DB_PREFIX . "blocks WHERE user_id=%d AND status='reserved' AND banner_id=%d", $current_user_id, $BID );
$res = $wpdb->get_results( $sql );

// If no reserved blocks found, try checking by order_id
if ( empty( $res ) ) {
	$sql = $wpdb->prepare( "SELECT block_id FROM " . MDS_DB_PREFIX . "blocks WHERE user_id=%d AND order_id=%d AND banner_id=%d", $current_user_id, $order_id, $BID );
	$res = $wpdb->get_results( $sql );
}

// If still nothing, fall back to orders.blocks CSV which is authoritative for selection
$count = 0;
if ( ! empty( $res ) ) {
	$count = count( $res );
} else {
$order_blocks_csv = $wpdb->get_var( $wpdb->prepare( "SELECT blocks FROM " . MDS_DB_PREFIX . "orders WHERE order_id=%d AND banner_id=%d", $order_id, $BID ) );
	if ( $order_blocks_csv !== null && $order_blocks_csv !== '' ) {
		$csv_arr = array_filter( array_map( 'trim', explode( ',', $order_blocks_csv ) ), static function ( $v ) { return $v !== ''; } );
		$count   = count( $csv_arr );
	}
}

$not_enough_blocks = $count < $banner_data['G_MIN_BLOCKS'];

Language::out_replace(
	'<p>1. <a href="%ORDER_URL%?BID=%BID%">Select Your pixels</a> -> 2. <b>Image Upload</b> -> 3. Write Your Ad -> 4. Confirm Order -> 5. Payment</p>',
	[ '%BID%', '%ORDER_URL%' ],
	[ $BID, Utility::get_page_url( 'order' ) ]
);
?>
    <p id="select_status"><?php echo( $cannot_sel ?? "" ); ?></p>
<?php
/*
$sql = "SELECT * FROM " . MDS_DB_PREFIX . "banners order by `name` ";
$res = $wpdb->get_results( $sql );

if ( count( $res ) > 1 ) {
	?>
    <div class="fancy-heading"><?php Language::out( 'Available Grids' ); ?></div>
    <div class="mds-select-intro">
		<?php
		Language::out_replace(
			'%GRID_COUNT%',
			count( $res ),
			'<p>There are <b>%GRID_COUNT%</b> different grids served by this website! Select the image which you would like to publish your pixels to:</p>'
		);
		?>
    </div>
	<?php display_banner_selecton_form( $BID, get_current_order_id(), $res, 'upload' );
	//
	// if ( ! isset( $_REQUEST['banner_change'] ) && ( ! isset( $_REQUEST['jEditOrder'] ) || $_REQUEST['jEditOrder'] !== 'true' ) ) {
	// 	// If multiple banners only display the selection form first
	// 	require_once MDS_CORE_PATH . "html/footer.php";
	//
	// 	return;
	// }
*/

if ( isset( $order_exists ) && $order_exists ) {
	Language::out_replace(
		'<p>Note: You have placed some pixels on order, but it was not confirmed (green blocks). <a href="%MANAGE_URL%">Manage Pixels</a></p>',
		'%MANAGE_URL%',
		Utility::get_page_url( 'manage' )
	);
}

// $has_packages = banner_get_packages( $BID );
// if ( $has_packages ) {
// 	display_package_options_table( $BID, '', false );
// } else {
// 	display_price_table( $BID );
// }

$sql = $wpdb->prepare(
	"SELECT * FROM " . MDS_DB_PREFIX . "orders WHERE order_id=%d AND banner_id=%d",
	intval( Orders::get_current_order_id() ),
	intval( $BID )
);
$order_row = $wpdb->get_row( $sql, ARRAY_A );
if ( $wpdb->last_error ) {
	wp_die( esc_html( $wpdb->last_error ) );
}

// Ensure reserved rows exist for this order before rendering the grid
if ( $order_row && ! empty( $order_row['blocks'] ) ) {
	$res_count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM " . MDS_DB_PREFIX . "blocks WHERE order_id=%d AND banner_id=%d AND status='reserved'", intval( $order_id ), intval( $BID ) ) );
	if ( $res_count === 0 ) {
		\MillionDollarScript\Classes\Orders\Orders::reserve_pixels_for_temp_order( $order_row );
	}
}

if ( ! $order_row ) {
	// Check for any new orders
	$order_row = Orders::find_new_order();
	if ( $order_row == null || $not_enough_blocks ) {

		// Nothing found or not enough blocks
		if ( $not_enough_blocks ) {
			Functions::not_enough_blocks( Orders::get_current_order_id(), $banner_data['G_MIN_BLOCKS'] );
		} else {
			Language::out_replace(
				'<p>You have no pixels selected on order! Please <a href="%ORDER_URL%?BID=%BID%">select some pixels here</a>.</p>',
				[ '%ORDER_URL%', '%BID%' ],
				[ Utility::get_page_url( 'order' ), $BID ]
			);
		}

		return;
	}
}
$price = $order_row['price'] . ' ' . $order_row['currency'];

?>
    <div class="fancy-heading"><?php Language::out( 'Upload your pixel image' ); ?></div>
<?php
Language::out_replace(
	'<p>- Upload a GIF, JPEG or PNG graphics file<br/>
- Click "Browse" to find your file on your computer, then click "Upload".<br/>
- Once uploaded, you will be able to position your file over the grid.<br/></p>',
	'%TOTAL_COST%',
	$price
);
?>
    <p>
    <form method='post' action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" enctype="multipart/form-data">
		<?php wp_nonce_field( 'mds-form' ); ?>
        <input type="hidden" name="action" value="mds_form_submission">
        <input type="hidden" name="mds_dest" value="upload">
		<?php Language::out( '<p><strong>Upload your pixels:</strong></p>' ); ?>
        <input type='file' accept="image/*" name='graphic' style=' font-size:14px;width:200px;'/>
        <input type='hidden' name='BID' value='<?php echo $BID; ?>'/>
        <input type='hidden' name='package' value='<?php echo $package_id; ?>'/>
        <input type="hidden" name="selected_pixels" value=''>
        <input type="hidden" name="order_id" value="<?php echo $order_id; ?>">
        <input class="mds-button mds_upload_image" type='submit' value='<?php echo esc_attr( Language::get( 'Upload' ) ); ?>'
               style=' font-size:18px;'/>
    </form>

<?php

if ( ! empty( $image ) ) {

	?>

    <div class="fancy-heading"><?php Language::out( 'Your Uploaded Pixels' ); ?></div>
    <p>
		<?php
		if ( Options::get_option( 'show_uploaded_image_in_advanced_mode', 'yes' ) == 'yes' ) {
			echo "<img class='mds_pointer_graphic' style=\"border:0;\" src='" . esc_url( Utility::get_page_url( 'get-pointer-graphic', [ 'BID' => $BID ] ) ) . "' alt=\"\" /><br />";

			if ( empty( $size ) ) {
				$tmp_size = getimagesize( $tmp_image_file );
				$size     = array( "x" => $tmp_size[0], "y" => $tmp_size[1] );
				unset( $tmp_size );
			}

			Language::out_replace(
				'The uploaded image is %WIDTH% pixels wide and %HEIGHT% pixels high.',
				[ '%WIDTH%', '%HEIGHT%' ],
				[ $size['x'], $size['y'] ]
			);

			?>
			<br/>
			<?php
		}

		if ( empty( $reqsize ) ) {
			$reqsize = [
				'x' => $order_row['quantity'] / $banner_data['BLK_WIDTH'],
				'y' => $order_row['quantity'] / $banner_data['BLK_HEIGHT']
			];
		}

		if ( empty( $pixel_count ) ) {
			$pixel_count = $order_row['quantity'];
		}

		if ( empty( $block_size ) ) {
			$block_size = $order_row['quantity'] / ( $banner_data['BLK_WIDTH'] * $banner_data['BLK_HEIGHT'] );
		}

		// if image should be resized automatically make it fit within grid max/min block settings
		if ( Options::get_option( 'resize' ) != 'YES' ) {
			if ( ( $block_size > $banner_data['G_MAX_BLOCKS'] ) && ( $banner_data['G_MAX_BLOCKS'] > 0 ) ) {

				$limit = $banner_data['G_MAX_BLOCKS'] * $banner_data['BLK_WIDTH'] * $banner_data['BLK_HEIGHT'];

				Language::out_replace(
					'<strong style="color:red;">Sorry, the uploaded image is too big. This image has %COUNT% pixels... A limit of %MAX_PIXELS% pixels per order is set.</strong>',
					[ '%MAX_PIXELS%', '%COUNT%' ],
					[ $limit, $pixel_count ]
				);

				unset( $tmp_image_file );
			} else if ( ( $block_size < $banner_data['G_MIN_BLOCKS'] ) && ( $banner_data['G_MIN_BLOCKS'] > 0 ) ) {

				Language::out_replace(
					'<strong style="color:red;">Sorry, you are required to upload an image with at least %MIN_PIXELS% pixels. This image only has %COUNT% pixels...</strong>',
					[ '%MIN_PIXELS%', '%COUNT%' ],
					[
						$banner_data['G_MIN_BLOCKS'] * $banner_data['BLK_WIDTH'] * $banner_data['BLK_HEIGHT'],
						$pixel_count
					]
				);

				unset( $tmp_image_file );
			}
		}

		Language::out_replace(
			'The uploaded image will require you to purchase %PIXEL_COUNT% pixels from the map which is exactly %BLOCK_COUNT% blocks.',
			[ '%PIXEL_COUNT%', '%BLOCK_COUNT%' ],
			[ $pixel_count, $block_size ]
		);

		?>
        <br/>
		<?php

		Language::out_replace(
			'This will cost you %TOTAL_COST%.',
			[ '%PIXEL_COUNT%', '%BLOCK_COUNT%', '%TOTAL_COST%' ],
			[ $pixel_count, $block_size, $price ]
		);

		?>

    </p>
	<?php

	function display_edit_order_button( $order_id ) {
		global $BID;
		?>
        <input type='button' value="<?php echo esc_attr( Language::get( 'Edit Order' ) ); ?>"
               onclick="window.location='<?php echo esc_url( Utility::get_page_url( 'order', [ 'BID' => $BID, 'order_id' => $order_id ] ) ); ?>'">
		<?php
	}

	$mds_order_id = Orders::get_current_order_id();

	// Check for any new orders
	$order_row = Orders::find_new_order();

if ( $order_row == null || ( $order_row['status'] != 'new' && ( $order_row['order_id'] == '' ) || ( ( $order_row['status'] != 'new' && $order_row['quantity'] == '0' ) ) ) || $not_enough_blocks ) {
		if ( $not_enough_blocks ) {
			Functions::not_enough_blocks( $mds_order_id, $banner_data['G_MIN_BLOCKS'] );
		} else {
			Language::out_replace(
				'<p>You have no pixels selected on order! Please <a href="%ORDER_URL%?BID=%BID%">select some pixels here</a>.</p>',
				[ '%ORDER_URL%', '%BID%' ],
				[ Utility::get_page_url( 'order' ), $BID ]
			);
		}
	} else {
		if ( isset( $image ) ) {

			?>
            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" name="form1">
				<?php wp_nonce_field( 'mds-form' ); ?>
                <input type="hidden" name="action" value="mds_form_submission">
                <input type="hidden" name="mds_dest" value="write-ad">
                <input type="hidden" name="package" value="<?php echo $package_id; ?>">
                <input type="hidden" name="selected_pixels" value='<?php echo isset($_POST['selected_pixels']) ? esc_attr($_POST['selected_pixels']) : ''; ?>'>
                <input type="hidden" name="order_id" value="<?php echo $order_id; ?>">
                <input type="hidden" value="<?php echo $BID; ?>" name="BID">
                <input type="submit" class='mds-write big_button' name='submit_button2' id='submit_button2'
                       value='<?php echo esc_attr( Language::get( 'Write Your Ad' ) ); ?>'>
            </form>
            <!--suppress HtmlRequiredAltAttribute, HtmlUnknownAnchorTarget -->
            <img src="<?php echo esc_url( Utility::get_page_url( 'show-map', [ 'BID' => $BID, 'time' => time() ] ) ); ?>"
                 width="<?php echo( $banner_data['G_WIDTH'] * $banner_data['BLK_WIDTH'] ); ?>"
                 height="<?php echo( $banner_data['G_HEIGHT'] * $banner_data['BLK_HEIGHT'] ); ?>" usemap="#main"/>
			<?php
		}
	}
}

require_once MDS_CORE_PATH . "html/footer.php";