<?php
/**
 * MachForm
 * 
 * © 2007–2025 Appnitro Software. All rights reserved.
 * 
 * This source code is proprietary and may not be copied, modified,
 * or distributed in any form without express written permission from Appnitro Software.
 * 
 * License information: https://www.machform.com/license-agreement/
 */
	require('includes/init-form.php');
	
	require('config.php');
	require('includes/db-core.php');
	require('includes/helper-functions.php');
	require('includes/filter-functions.php');

	$_POST = json_decode(file_get_contents('php://input'), true);
	
	$dbh = mf_connect_db();
	
	$form_id        = (int) $_POST['form_id'];
    $element_id     = (int) $_POST['element_id'];
    $file_name      = trim($_POST['file_name'] ?? '');
    $upload_token   = trim($_POST['upload_token'] ?? '');
    
    $file_token = trim($_POST['file_token'] ?? '');
	$file_token = preg_replace('/[^\da-z]/i', '', $file_token); //ensure only alphanumeric characters allowed

    $file_name      = "element_{$element_id}_{$file_token}-1-{$file_name}";
    
    //check if ap_form_xxx_listfiles table exist or not, if not exist create one
	$is_listfiles_table_exist = true;
	try{
			$params = array();
			
			$query = "select count(*) from ".MF_TABLE_PREFIX."form_{$form_id}_listfiles";
			$sth = $dbh->prepare($query);

			$sth->execute($params);
	}catch(PDOException $e) {
		$is_listfiles_table_exist = false;
	}

	if($is_listfiles_table_exist === false){
			
			//create table ap_form_xxx_listfiles
			try{
				$params = array();
				$query = "CREATE TABLE `".MF_TABLE_PREFIX."form_{$form_id}_listfiles` (
								  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
								  `date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
								  `file_token` text,
								  `file_content` text CHARACTER SET utf8mb4,
								  PRIMARY KEY (`id`),
								  KEY `file_token` (`file_token`(50))
								) DEFAULT CHARACTER SET utf8mb4;";
				$sth = $dbh->prepare($query);

				$sth->execute($params);
			}catch(PDOException $e) {
				//discard silently, in case the table already exist
			}
	}


	//insert the uploaded file record into ap_form_xxx_listfiles table
    $query = "INSERT INTO `".MF_TABLE_PREFIX."form_{$form_id}_listfiles` (file_token, file_content) VALUES (?, ?);";
    $params = array($file_token, $file_name);
				
	mf_do_query($query,$params,$dbh);
	
	
	header('Content-Type: application/json');
    echo json_encode(['status' => 'ok']);
	
?>