<?php
session_start();
// Database Configuration
define('DB_HOST', 'localhost');
define('DB_NAME', 'sms_marketing_db');
define('DB_USER', 'root');
define('DB_PASS', ''); // Update with later

// Database Connection
try {
    $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
    $pdo = new PDO($dsn, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Database Connection Failed: " . $e->getMessage());
}

// Fetch SMS Configuration from DB
$db_settings = [];
try {
    $stmt = $pdo->query("SELECT * FROM settings");
    while ($row = $stmt->fetch()) {
        $db_settings[$row['setting_key']] = $row['setting_value'];
    }
} catch (PDOException $e) {
    // If table doesn't exist yet, we'll use defaults or fail gracefully
}

// Define SMS Constants (DB > JSON/Default)
define('SMS_API_KEY', $db_settings['sms_api_key'] ?? 'CHANGEME');
define('SMS_SENDER_ID', $db_settings['sms_sender_id'] ?? 'CHANGEME');
define('SMS_API_URL_ONE', $db_settings['sms_url_one'] ?? 'http://bulksmsbd.net/api/smsapi');
define('SMS_API_URL_MANY', $db_settings['sms_url_many'] ?? 'http://bulksmsbd.net/api/smsapimany');
define('SMS_BALANCE_URL', $db_settings['sms_balance_url'] ?? 'http://bulksmsbd.net/api/getBalanceApi');

// App Configuration
define('APP_NAME', 'SMS Marketing App');

// Dynamic BASE_URL Detection
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
$host = $_SERVER['HTTP_HOST'];
$script_name = $_SERVER['SCRIPT_NAME'];

// We want to find the root of the application. 
// Standard structure: ProjectRoot/public/...
$root_web_path = dirname($script_name);

// Logic: Find '/public/' in the path and strip it and everything after it.
$public_pos = strpos($script_name, '/public/');

if ($public_pos !== false) {
    $root_web_path = substr($script_name, 0, $public_pos);
} else {
    // Fallback: If 'public' is not in URL
    if ($root_web_path == '/' || $root_web_path == '\\') {
        $root_web_path = '';
    }
}

// FIX: Explicitly handle test.khatifoodbazar.com if dynamic detection fails
if ($host === 'test.khatifoodbazar.com') {
    $root_web_path = ''; // Root of subdomain is often the app root
}

// Ensure leading slash for root path if it's not empty and doesn't have it (though substr usually preserves it)
// Ensure NO trailing slash for consistency (we add it later)
$root_web_path = rtrim($root_web_path, '/');

define('BASE_URL', $protocol . '://' . $host . $root_web_path . '/');
define('COOKIE_LIFETIME', 1296000); // 15 days in seconds

// Error Reporting (Disable in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);


?>