<?php 
include ('includes/header.php');

//table name
$api_folder = "api/vpnfiles";
$download_path = "api/vpnfiles/";
$zipPath = 'api/ovpn_bundle.zip';
$page = "vpn.php";


createFolder($api_folder);


function createFolder($path, $permissions = 0777) {
    if (!is_dir($path)) {
        return mkdir($path, $permissions, true);
    }
    return false;
}

function downloadFile($url, $saveDir) {
    // Create directory if it doesn't exist
    if (!is_dir($saveDir)) {
        mkdir($saveDir, 0777, true);
    }

    // Initialize cURL
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);

    // Execute and get headers
    curl_exec($ch);
    $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $contentDisposition = null;

    // Get filename from Content-Disposition if available
    $headers = curl_getinfo($ch);
    $filename = null;

    // Try to extract Content-Disposition header manually
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($curl, $header) use (&$filename) {
        if (stripos($header, 'Content-Disposition:') !== false) {
            if (preg_match('/filename=["\']?([^"\']+)["\']?/', $header, $matches)) {
                $filename = $matches[1];
            }
        }
        return strlen($header);
    });

    curl_exec($ch);

    // Close curl
    curl_close($ch);

    // Fallback: get filename from URL if header not available
    if (!$filename) {
        $path = parse_url($url, PHP_URL_PATH);
        $filename = basename($path);
    }

    // Build full save path
    $filePath = $saveDir . $filename;
    
    
     // Only allow .ovpn files
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    if ($ext !== 'ovpn') {
        return ['success' => false, 'message' => 'Only .ovpn files are allowed.'];
    }

    // Now download the actual file
    $fileData = @file_get_contents($url);

    if ($fileData === false) {
        return ['success' => false, 'message' => 'Failed to download file.'];
    }

    file_put_contents($filePath, $fileData);

    return ['success' => true, 'file_path' => $filePath, 'file_name' => $filename];
}

function zipOnlyOvpnFiles($folderPath, $zipFilePath) {
    $folderPath = rtrim($folderPath, '/') . '/';
    if (!is_dir($folderPath)) {
        return ['success' => false, 'message' => 'Folder does not exist.'];
    }

    // Step 1: Delete all non-OVPN files
    $files = scandir($folderPath);
    foreach ($files as $file) {
        $filePath = $folderPath . $file;
        if (is_file($filePath)) {
            $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
            if ($ext !== 'ovpn') {
                unlink($filePath); // delete non-ovpn files
            }
        }
    }

    // Step 2: Create zip archive
    $zip = new ZipArchive();
    if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
        return ['success' => false, 'message' => 'Failed to create zip file.'];
    }

    // Add remaining .ovpn files to the zip
    $ovpnFiles = glob($folderPath . '*.ovpn');
    foreach ($ovpnFiles as $ovpnFile) {
        $zip->addFile($ovpnFile, basename($ovpnFile));
    }

    $zip->close();

    return ['success' => true, 'message' => 'ZIP created successfully.', 'zip_path' => $zipFilePath];
}


function report($status, $message){
    if($status == true){
       echo '<div class="alert alert-success"><h4><i class="icon fa fa-check"></i> '.$message.' </h4></div>'; 
      
    }else{
        echo '<div class="alert alert-danger"><h4><i class="icon fa fa-times"></i> '.$message.'</h4></div>';
        
    }
}

function movefile($target_dir) {
    if (substr($target_dir, -1) !== '/') {
        $target_dir .= '/';
    }

    if (!isset($_FILES['fileToUpload'])) {
        return ['success' => false, 'message' => 'No file uploaded.'];
    }

    $target_file = basename($_FILES['fileToUpload']['name']);
    $full_path = $target_dir . $target_file;
    $gtg = 1;
    $ft = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Check for existing file
    if (file_exists($full_path)) {
        return ['success' => false, 'message' => 'File with the same name already exists.'];
    }

    // Validate file size
    if ($_FILES["fileToUpload"]["size"] > 500000) {
        return ['success' => false, 'message' => 'File is too large.'];
    }

    // Validate file extension
    if ($ft !== 'ovpn') {
        return ['success' => false, 'message' => 'Only OVPN files are allowed.'];
    }

    // Upload file if no errors
    if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $full_path)) {
        $file_name = htmlspecialchars($target_file);
        return ['success' => true, 'file_name' => $file_name, 'message' => 'File uploaded successfully.'];
    } else {
        return ['success' => false, 'message' => 'Failed to upload file.'];
    }
}


if (isset($_POST['submit'])) {
	$url = $_POST['vpn_url'];
	$upload_type = $_POST['type'];
	
	if($upload_type == 'file'){
	    fileupload($download_path, $zipPath);
	}else{
	    urlupload($url, $download_path, $zipPath);
	}
	
}

function urlupload($url,$path,$zippath){
    $result = downloadFile($url, $path);
    if($result['success']){
       $zipresult = zipOnlyOvpnFiles($path,$zippath);
       if($zipresult['success']){
           savealldatadb($result['file_name']);
       }else{
          report($zipresult['success'],$result['message']);
       }
       
    }else{
        report($result['success'],$result['message']);
    }
}
function fileupload($path,$zippath){
    $result = movefile($path);
    if($result['success']){
       $zipresult =  zipOnlyOvpnFiles($path,$zippath);
       if($zipresult['success']){
           savealldatadb($result['file_name']);
       }else{
          report($zipresult['success'],$result['message']);
       }
    }else{
        report($result['success'],$result['message']);
    }
}

function savealldatadb($filename) {
    // Connect to the SQLite database
    $db = new SQLite3('api/.db.db');

    // Create the table if it doesn't exist
    $db->exec('CREATE TABLE IF NOT EXISTS vpn (
        id INTEGER PRIMARY KEY NOT NULL,
        location TEXT,
        file_name TEXT,
        username TEXT,
        password TEXT
    )');

    // Collect data from POST
    $location = isset($_POST['vpn_country']) ? $_POST['vpn_country'] : '';
    $username = isset($_POST['username']) ? $_POST['username'] : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';

    // Prepare and execute insert statement
    $stmt = $db->prepare('INSERT INTO vpn (location, file_name, username, password) VALUES (:location, :file_name, :username, :password)');
    $stmt->bindValue(':location', $location, SQLITE3_TEXT);
    $stmt->bindValue(':file_name', $filename, SQLITE3_TEXT);
    $stmt->bindValue(':username', $username, SQLITE3_TEXT);
    $stmt->bindValue(':password', $password, SQLITE3_TEXT);

    if ($stmt->execute()) {
        echo "<script>window.location.href='./vpn.php?status=1';</script>";
    } else {
        echo '<div class="alert alert-danger"><strong>❌ Error!</strong> Failed to save VPN data.</div>';
    }

    // Optional: Close DB
    $db->close();
}

?>


		<div class="col-md-8 mx-auto ctmain-table">
			<div class="card-body">
				<div class="card ctcard">
					<div class="card-header card-header-warning">
						<center>
							<h2><i class="icon icon-bullhorn"></i> OVPN Source </h2>
						</center>
					</div>
					
					<div class="card-body">
						<div class="col-12">
							<h3>Add OVPN Source</h3>
						</div>
							<form method="post" enctype="multipart/form-data">
							    <div class="form-group ctinput">
				                	<div class="form-group form-float form-group-lg ctinput">
                                        <div class="form-line">
                                            <label class="form-label"><strong>Location</strong></label>
				                			<input type="text" class="form-control" name="vpn_country" placeholder="Country / State">
				                		</div>
				                	</div>
				                </div>
                               <br>
                               <div>
                                   <label for="selector">Select OVPN Source</label>
                                   <select class="form-control ctinput"  style="width:auto;" name = "type" onchange="yesnoCheck(this);">
                                       <option value="url">URL</option>
                                       <option value="file">FILE</option>
                                   </select>
                               </div>
                               <br>
								<div id="loc" class="form-group ctinput">
									<label class="form-label " for="vpn_url">OVPN URL</label>
										<input class="form-control" name="vpn_url" placeholder="http://host.com/folder/poland.ovpn" type="text"/>
								</div>
								<div id="ftu" class="form-group"  style="display: none;">
                                   <label class="control-label " for="vpn_config">
                                       <strong>OVPN File</strong>
                                   </label>
                                   <div class="input-group">
                                       <input type="file" name="fileToUpload" id="fileToUpload" >
                                   </div>
                               </div>
                               <hr>
							   <strong>Only input user/pass if your App has the VPN mod otherwire it wont work</strong>
                                <div class="form-group ctinput">
                                    <label class="control-label " for="username">
                                        Embedded Username
                                    </label>
                                    <div class="input-group ctinput">
                                        <input class="form-control" id="username" name="username" placeholder="Enter Username" value='' type="text"/>
                                    </div>
                                </div>
                                <div class="form-group ctinput">
                                    <label class="control-label " for="password">
                                        Embedded Password 
                                    </label>
                                    <div class="input-group ctinput">
                                        <input class="form-control" id="password" name="password" placeholder="Enter Password" value='' type="text"/>
                                    </div>
                                </div>
								<div class="form-group ctinput">
									<center>
										<button class="btn btn-info " name="submit" type="submit">
											<i class="icon icon-check"></i> Submit
										</button>
									</center>
								</div>
							</form>
					</div>
				</div>
			</div>
		</div>



<?php include ('includes/footer.php');?>
<script>

function yesnoCheck(that){
    if (that.value == "url"){
        document.getElementById("loc").style.display = "block";
    }else{
        document.getElementById("loc").style.display = "none";
    }
    if (that.value == "file"){
        document.getElementById("ftu").style.display = "block";
    }else{
        document.getElementById("ftu").style.display = "none";
    }
}
</script>

</body>
</html>