<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
date_default_timezone_set('Asia/Jakarta');

// Konfigurasi Database
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'db_pengajuanv2';

try {
    $pdo = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8mb4", $db_user, $db_pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
} catch (PDOException $e) {
    die("Koneksi Database Gagal: " . $e->getMessage());
}

// Helper Get Setting from DB
function getSetting($pdo, $key) {
    $stmt = $pdo->prepare("SELECT meta_value FROM tbl_pengaturan WHERE meta_key = ?");
    $stmt->execute([$key]);
    $res = $stmt->fetch();
    return $res ? $res->meta_value : '';
}

// Load Settings
define('FONNTE_TOKEN', getSetting($pdo, 'fonnte_token'));
$smtp_user_setting = getSetting($pdo, 'smtp_user');
$fallback_email = 'noreply@' . (isset($_SERVER['HTTP_HOST']) ? preg_replace('/:[0-9]+$/', '', $_SERVER['HTTP_HOST']) : 'localhost');
define('MAIL_SENDER', !empty($smtp_user_setting) ? $smtp_user_setting : $fallback_email);
define('MAIL_NAME', getSetting($pdo, 'app_title') ?: 'Sistem Pengajuan LENTERA');

// Helper URL
function base_url($path = '') {
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
    $host = $_SERVER['HTTP_HOST'];
    
    // Auto-detect base folder for hosting environments
    $doc_root = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);
    $dir = str_replace('\\', '/', __DIR__);
    $folder = str_replace($doc_root, '', $dir);
    
    return $protocol . "://" . $host . $folder . "/" . ltrim($path, '/');
}

// Helper Tanggal Indo
function tgl_indo($tanggal){
	$bulan = array (
		1 =>   'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
		'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'
	);
	$pecahkan = explode('-', $tanggal);
	return $pecahkan[2] . ' ' . $bulan[ (int)$pecahkan[1] ] . ' ' . $pecahkan[0];
}

// Helper Send WhatsApp via Fonnte
function sendWhatsApp($target, $message, $file_url = '') {
    if (empty(FONNTE_TOKEN) || FONNTE_TOKEN == 'TOKEN_FONNTE_ANDA_DISINI') return false;
    
    $post_data = array(
        'target' => $target,
        'message' => $message,
    );
    if (!empty($file_url)) {
        $post_data['url'] = $file_url;
    }

    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => 'https://api.fonnte.com/send',
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 10, // Prevent infinite hang causing 503
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'POST',
      CURLOPT_POSTFIELDS => $post_data,
      CURLOPT_HTTPHEADER => array(
        'Authorization: ' . FONNTE_TOKEN
      ),
      CURLOPT_SSL_VERIFYPEER => false,
      CURLOPT_SSL_VERIFYHOST => 0,
    ));

    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

// Helper Send Email
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

function sendEmail($to, $subject, $message, $attachment_path = '') {
    global $pdo;
    
    $smtp_host = getSetting($pdo, 'smtp_host');
    $smtp_user = getSetting($pdo, 'smtp_user');
    $smtp_pass = getSetting($pdo, 'smtp_pass');
    $smtp_port = getSetting($pdo, 'smtp_port');
    
    // Jika SMTP tidak dikonfigurasi, gunakan fungsi mail standar
    if (empty($smtp_host) || empty($smtp_user) || empty($smtp_pass)) {
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        $headers .= "From: " . MAIL_NAME . " <" . MAIL_SENDER . ">" . "\r\n";
        $headers .= "Reply-To: " . MAIL_SENDER . "\r\n";
        $headers .= "Return-Path: " . MAIL_SENDER . "\r\n";
        $headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
        
        // Parameter -f membantu mencegah spam flag di banyak mail server (mengatur Return-Path/Envelope Sender)
        return @mail($to, $subject, $message, $headers, "-f" . MAIL_SENDER);
    }

    require_once __DIR__ . '/PHPMailer/Exception.php';
    require_once __DIR__ . '/PHPMailer/PHPMailer.php';
    require_once __DIR__ . '/PHPMailer/SMTP.php';

    $mail = new PHPMailer(true);

    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host       = $smtp_host;
        $mail->SMTPAuth   = true;
        $mail->Username   = $smtp_user;
        $mail->Password   = $smtp_pass;
        $mail->SMTPSecure = ($smtp_port == 465) ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = $smtp_port;
        $mail->Timeout    = 10; // Prevent SMTP hang causing 503

        // Recipients
        $mail->setFrom($smtp_user, MAIL_NAME);
        $mail->addAddress($to);

        // Content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $message;

        // Attachment
        if (!empty($attachment_path) && file_exists($attachment_path)) {
            $mail->addAttachment($attachment_path);
        }

        $mail->send();
        return true;
    } catch (Exception $e) {
        // Simpan log error secara diam-diam agar tidak merusak response JSON
        error_log("Email Error: {$mail->ErrorInfo}");
        return false;
    }
}
?>
