<?php
// File: config.php
// Database configuration and common functions

// Error reporting for development (disable in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Set timezone
date_default_timezone_set('Asia/Colombo');

// Database credentials (OLD - commented out)
// define('DB_HOST', 'localhost');
// define('DB_NAME', 'playbdqv_engweb');
// define('DB_USER', 'playbdqv_engweb');
// define('DB_PASS', 'playbdqv_engweb');

// Database credentials (OLD - howdoyou.space - commented out)
// define('DB_HOST', 'localhost');
// define('DB_NAME', 'playbdqv_ensipayments');
// define('DB_USER', 'playbdqv_ensipayments');
// define('DB_PASS', 'playbdqv_ensipayments');

// Database credentials (ensi.online - ACTIVE)
define('DB_HOST', 'localhost');
define('DB_NAME', 'moodkuqp_ensi');
define('DB_USER', 'moodkuqp_ensi');
define('DB_PASS', 'moodkuqp_ensi');

// Database connection with UTF-8 support for Sinhala
function getDBConnection() {
    try {
        $conn = new PDO(
            "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
            DB_USER,
            DB_PASS,
            [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci"
            ]
        );
        return $conn;
    } catch(PDOException $e) {
        error_log("Database connection failed: " . $e->getMessage());
        return null;
    }
}

// CORS headers for mobile app
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Content-Type: application/json; charset=utf-8');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Get JSON input
function getJsonInput() {
    $json = file_get_contents('php://input');
    return json_decode($json, true);
}

// Send JSON response
function sendResponse($success, $message, $data = null, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data,
        'status_code' => $statusCode
    ], JSON_UNESCAPED_UNICODE);
    exit();
}

// Validate email
function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

// Generate 4-digit verification code
function generateVerificationCode() {
    return str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
}

// Hash password
function hashPassword($password) {
    return password_hash($password, PASSWORD_DEFAULT);
}

// Verify password
function verifyPassword($password, $hash) {
    return password_verify($password, $hash);
}

// Clean and sanitize input
function sanitizeInput($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
    return $data;
}

// Generate secure token
function generateSecureToken($length = 32) {
    return bin2hex(random_bytes($length));
}

// Log activity (for debugging)
function logActivity($message) {
    $logFile = __DIR__ . '/logs/activity.log';
    $timestamp = date('Y-m-d H:i:s');
    $logMessage = "[$timestamp] $message" . PHP_EOL;
    
    // Create logs directory if it doesn't exist
    if (!file_exists(__DIR__ . '/logs')) {
        mkdir(__DIR__ . '/logs', 0755, true);
    }
    
    file_put_contents($logFile, $logMessage, FILE_APPEND);
}
?>
