import os
import sys

file_path = r'c:\xampp\htdocs\extract\admin\api\send_test_email.php'

# Remove if exists
if os.path.exists(file_path):
    os.remove(file_path)
    print("File removed")

# Create new file
code = '''<?php
header('Content-Type: application/json');
session_start();

if(!isset($_SESSION['user_role']) || $_SESSION['user_role']!=='admin') {
  exit(json_encode(['success'=>false,'message'=>'Forbidden']));
}

require_once dirname(dirname(dirname(__FILE__))).'/config/config.php';
require_once dirname(dirname(dirname(__FILE__))).'/classes/Database.php';

$db = Database::getInstance();
$email = filter_var($_POST['test_email']??'', FILTER_VALIDATE_EMAIL);

if(!$email) {
  exit(json_encode(['success'=>false,'message'=>'Invalid email']));
}

$s = [];
foreach(['mail_host','mail_username','mail_from_email','mail_from_name','mail_port','mail_encryption'] as $k) {
  $r = $db->fetch('SELECT setting_value FROM admin_settings WHERE setting_key=?',[$k]);
  if($r) $s[$k]=$r['setting_value'];
}

$p = $db->fetch('SELECT setting_value FROM admin_settings WHERE setting_key=?',['mail_password_encrypted']);
$pwd = $p ? base64_decode($p['setting_value']) : '';

if(!$s['mail_host'] || !$s['mail_username'] || !$pwd) {
  exit(json_encode(['success'=>false,'message'=>'Email not configured']));
}

$h = 'From: '.$s['mail_from_name'].' <'.$s['mail_from_email'].'>\\r\\nContent-Type: text/plain; charset=UTF-8\\r\\n';
$b = 'Test email sent at '.date('Y-m-d H:i:s');

if(mail($email, 'Test Email - Advanced Mobile Info', $b, $h)) {
  exit(json_encode(['success'=>true,'message'=>'Email sent to '.$email]));
} else {
  exit(json_encode(['success'=>false,'message'=>'Failed to send']));
}
?>'''

with open(file_path, 'w', encoding='utf-8') as f:
    f.write(code)

print("File created successfully")
print(f"File size: {os.path.getsize(file_path)} bytes")
