<?php
// Database configuration untuk sistem call
define('DB_HOST', 'localhost');
define('DB_USER', 'pojodmoz_callUsr');
define('DB_PASS', 'PMFD9)xLqXBS');
define('DB_NAME', 'pojodmoz_callmain');

// Database configuration untuk autentikasi
define('DB_AUTH_HOST', 'localhost');
define('DB_AUTH_USER', 'pojodmoz_callUsr');
define('DB_AUTH_PASS', 'PMFD9)xLqXBS');
define('DB_AUTH_NAME', 'pojodmoz_callsa');

// Twilio configuration
define('TWILIO_SID', 'AC532142409665e2ef13e47e6853fbbae6');
define('TWILIO_TOKEN', 'dd8441ab23c23ed57f750e3eaec98df3');
define('TWILIO_NUMBER', '+17755516876');

// Base URL configuration
define('BASE_URL', 'https://callmain.pojok.website');

// Audio paths
define('AUDIO_UPLOAD_PATH', __DIR__ . '/../uploads/audio/');
define('AUDIO_PUBLIC_PATH', BASE_URL . '/uploads/audio/');

// Webhook URLs
define('WEBHOOK_URL', BASE_URL . '/webhook.php');

// Konfigurasi untuk database marketing
$config['mkt_db_host'] = 'localhost';
$config['mkt_db_name'] = 'pojodmoz_callmkt';
$config['mkt_db_user'] = 'pojodmoz_callUsr'; // Sesuaikan dengan username MySQL Anda
$config['mkt_db_pass'] = 'PMFD9)xLqXBS'; // Sesuaikan dengan password MySQL Anda

// Database connection untuk sistem call
try {
    $db = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8",
        DB_USER,
        DB_PASS
    );
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Database connection untuk autentikasi
try {
    $db_auth = new PDO(
        "mysql:host=" . DB_AUTH_HOST . ";dbname=" . DB_AUTH_NAME . ";charset=utf8",
        DB_AUTH_USER,
        DB_AUTH_PASS
    );
    $db_auth->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Test koneksi
    $test = $db_auth->query("SELECT 1");
    if (!$test) {
        error_log("Database connection test failed");
    }
} catch(PDOException $e) {
    error_log("Auth Connection failed: " . $e->getMessage());
    die("Auth Connection failed: " . $e->getMessage());
}

// Initialize Twilio client
require_once __DIR__ . '/../vendor/autoload.php';
use Twilio\Rest\Client;

function getTwilioClient() {
    static $client = null;
    if ($client === null) {
        $client = new Client(TWILIO_SID, TWILIO_TOKEN);
    }
    return $client;
}

// Helper functions
function sanitize_input($data) {
    return htmlspecialchars(strip_tags(trim($data)));
}

function get_audio_url($type) {
    global $db;
    $stmt = $db->prepare("SELECT file_path FROM audio_settings WHERE type = ?");
    $stmt->execute([$type]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($result) {
        return AUDIO_PUBLIC_PATH . $result['file_path'];
    }
    return null;
}

// Helper functions untuk soft delete
function softDelete($table, $id) {
    global $db_auth;
    try {
        $stmt = $db_auth->prepare("UPDATE $table SET deleted_at = NOW() WHERE id = ?");
        return $stmt->execute([$id]);
    } catch(PDOException $e) {
        error_log("Soft delete error: " . $e->getMessage());
        return false;
    }
}

// Helper untuk mengambil data aktif saja
function getActiveRecords($table, $conditions = "", $params = []) {
    global $db_auth;
    try {
        $sql = "SELECT * FROM $table WHERE deleted_at IS NULL";
        if ($conditions) {
            $sql .= " AND " . $conditions;
        }
        $stmt = $db_auth->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch(PDOException $e) {
        error_log("Get active records error: " . $e->getMessage());
        return [];
    }
}

// Update login query untuk hanya mengecek user yang belum dihapus
function checkUserLogin($table, $username) {
    global $db_auth;
    try {
        // Debug
        error_log("Checking login for user: $username in table: $table");
        
        $stmt = $db_auth->prepare("
            SELECT * FROM $table 
            WHERE username = ? 
            AND (active = 'active' OR active = 1)
            AND deleted_at IS NULL
        ");
        $stmt->execute([$username]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Debug
        if ($user) {
            error_log("User found: " . print_r($user, true));
        } else {
            error_log("User not found");
        }
        
        return $user;
    } catch(PDOException $e) {
        error_log("Check user login error: " . $e->getMessage());
        return null;
    }
}

// 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']) || !isset($token)) {
        return false;
    }
    return hash_equals($_SESSION['csrf_token'], $token);
}
?> 