<?php
	
	// Verify nonce for CSRF protection
	if (!isset($_POST['golf_scores_nonce']) || !wp_verify_nonce($_POST['golf_scores_nonce'], 'golf_scores_submit')) {
		die('Security check failed. Please try again.');
	}
	
	// Sanitize and validate all input data
	$score_id = isset($_POST['score_id']) ? absint($_POST['score_id']) : 0;
	$date = isset($_POST['MyDate']) ? sanitize_text_field($_POST['MyDate']) : '';
	$tee = isset($_POST['tee']) ? sanitize_text_field(stripslashes($_POST['tee'])) : '';
	$holes = isset($_POST['holes']) ? absint($_POST['holes']) : 0;
	$gross_score = isset($_POST['gross']) ? sanitize_text_field($_POST['gross']) : '';
	$course = isset($_POST['course']) ? sanitize_text_field(stripslashes($_POST['course'])) : '';
	$handicap = isset($_POST['handicap']) ? sanitize_text_field($_POST['handicap']) : '';
	$comments = isset($_POST['comments']) ? sanitize_text_field(stripslashes($_POST['comments'])) : '';
	$user_id = isset($_POST['user_id']) ? absint($_POST['user_id']) : 0;
	$username = isset($_POST['user']) ? sanitize_text_field($_POST['user']) : '';
	$net_score = isset($_POST['net']) ? sanitize_text_field($_POST['net']) : '';
	$formType = isset($_POST['formType']) ? sanitize_text_field($_POST['formType']) : '';
	
	// Validate required fields
	if (empty($course) && $formType !== 'deleteRecord') {
		die('Course name is required.');
	}
	if (empty($date) && $formType !== 'deleteRecord') {
		die('Date is required.');
	}
	if ($holes !== 9 && $holes !== 18 && $formType !== 'deleteRecord') {
		die('Invalid number of holes. Must be 9 or 18.');
	}
	
	// Validate numeric fields
	if ($formType !== 'deleteRecord') {
		if (!is_numeric($gross_score) || $gross_score < 1 || $gross_score > 200) {
			die('Invalid gross score. Must be a number between 1 and 200.');
		}
		if (!is_numeric($handicap) || $handicap < -10 || $handicap > 54) {
			die('Invalid handicap. Must be a number between -10 and 54.');
		}
		if (!is_numeric($net_score) || $net_score < 1 || $net_score > 200) {
			die('Invalid net score. Must be a number between 1 and 200.');
		}
		
		// Validate date format (YYYY-MM-DD)
		if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
			die('Invalid date format. Use YYYY-MM-DD.');
		}
		
		// Validate user authorization
		if ($user_id <= 0) {
			die('Invalid user ID.');
		}
		
		// Check if current user has permission to modify this record
		$current_user_id = get_current_user_id();
		if (!$current_user_id) {
			die('You must be logged in to perform this action.');
		}
		
		// Users can only modify their own records unless they're an admin
		if ($user_id != $current_user_id && !current_user_can('manage_options')) {
			die('You do not have permission to modify this record.');
		}
		
		// For edit operations, verify the record exists and belongs to the user
		if ($formType === 'editRecord' && $score_id > 0) {
			$existing_score = $wpdb->get_row($wpdb->prepare(
				"SELECT user_id FROM {$wpdb->prefix}golfScores WHERE id = %d",
				$score_id
			));
			
			if (!$existing_score) {
				die('Score record not found.');
			}
			
			if ($existing_score->user_id != $current_user_id && !current_user_can('manage_options')) {
				die('You do not have permission to edit this record.');
			}
		}
	}
	
	
	// delete record
	if($formType == 'deleteRecord'){
		
	
	global $wpdb;
	$table_name = $wpdb->prefix . "golfScores";
	$wpdb->delete( $table_name, array( 'id' => $score_id ), array( '%d' ) );

	
	echo '<div class="golfScoresAlert">Round deleted.</div>';
	unset($gtask);
	} // end if round deleted.


	// insert new scores
	if($formType == 'newRecord'){
	
	global $wpdb;
	$table_name = $wpdb->prefix . "golfScores";
	$wpdb->insert( 
		$table_name, 
			array( 
				'date' => $date, 
				'course' => $course,
				'tee' => $tee,
				'holes' => $holes,
				'gross_score' => $gross_score,
				'handicap' => $handicap,
				'net_score' => $net_score,
				'user_id' => $user_id,
				'comments' => $comments
			
		)
	);
	
	echo '<div class="golfScoresAlert">Score of ' . $gross_score . ' at ' . $course . ' recorded.</div>';
	unset($gtask);
	} // end if new record
	
	
	//Update record 
	if($formType == 'updateRecord'){
	
	global $wpdb;
	$table_name = $wpdb->prefix . "golfScores";
	$wpdb->update( 
	$table_name, 
	array( 
			'date' => $date, 
			'course' => $course,
			'tee' => $tee,
			'holes' => $holes,
			'gross_score' => $gross_score,
			'handicap' => $handicap,
			'net_score' => $net_score,
			'user_id' => $user_id,
			'comments' => $comments
		
	), 
	array( 'id' => $score_id ), 
	array( 
		'%s',	// date
		'%s',	// course
		'%s',	// tee
		'%d',	// holes
		'%s',	// gross_score
		'%s',	// handicap
		'%s',	// net_score
		'%d',	// user_id
		'%s'	// comments
	), 
	array( '%d' ) 
);


	
	echo '<div class="golfScoresAlert">Round at ' . $course . ' updated!</div>';
	unset($gtask);

	} // end if update record
	
?>