<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/secret.php';  // Load key dan iv dari file terpisah

$host = 'localhost';
$dbname = 'pojodmoz_callsa';
$username = 'pojodmoz_callUsr'; // sesuaikan dengan username database Anda
$password = 'PMFD9)xLqXBS'; // sesuaikan dengan password database Anda

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    die("Koneksi database gagal: " . $e->getMessage());
}

// Fungsi untuk membersihkan input
function sanitize_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

// Fungsi untuk generate CSRF token
function generateCSRFToken() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

// Fungsi untuk verifikasi CSRF token
function verifyCSRFToken($token) {
    if (!isset($_SESSION['csrf_token']) || $token !== $_SESSION['csrf_token']) {
        return false;
    }
    return true;
}

// Fungsi untuk cek login user
function checkUserLogin($table, $username) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM $table WHERE username = ? AND deleted_at IS NULL AND active = 'active'");
    $stmt->execute([$username]);
    return $stmt->fetch();
}

// Fungsi untuk enkripsi
function encryptPin($pin) {
    $encrypted = openssl_encrypt(
        $pin,
        'AES-256-CBC',
        AES_KEY,
        0,
        AES_IV
    );
    return base64_encode($encrypted);
}

// Fungsi untuk dekripsi
function decryptPin($encrypted) {
    $decrypted = openssl_decrypt(
        base64_decode($encrypted),
        'AES-256-CBC',
        AES_KEY,
        0,
        AES_IV
    );
    return $decrypted;
}
?> 