<?php
/**
 * Document Signing System Configuration
 * Auto-generated configuration file
 */

// Database Configuration
define('DB_HOST', 'localhost');
define('DB_USER', 'topche10_sign');
define('DB_PASS', '!LochsonG100!');
define('DB_NAME', 'topche10_document_signing');
define('DB_CHARSET', 'utf8mb4');

// Base URL
define('BASE_URL', 'https://homeofficestyles.com/docusign/');

// Security Configuration
define('ENCRYPTION_KEY', bin2hex(random_bytes(16)));
define('SECRET_KEY', bin2hex(random_bytes(32)));
define('SESSION_LIFETIME', 3600);
define('MAX_SIGNATURE_SIZE', 5242880); // 5MB

// File Paths
define('UPLOAD_DIR', dirname(__FILE__) . '/uploads/');
define('PDF_DIR', dirname(__FILE__) . '/uploads/pdfs/');
define('SIGNATURE_DIR', dirname(__FILE__) . '/uploads/signatures/');
define('TEMPLATE_DIR', dirname(__FILE__) . '/uploads/templates/');
define('LOG_DIR', dirname(__FILE__) . '/logs/');

// Email Configuration
define('MAIL_METHOD', 'disabled');
define('MAIL_FROM_EMAIL', 'noreply@garage.com');
define('MAIL_FROM_NAME', 'Document Signing');
define('SMTP_HOST', '');
define('SMTP_PORT', 587);
define('SMTP_USER', '');
define('SMTP_PASS', '');

// PDF Generation Settings
define('PDF_AUTHOR', 'Document Signing System');
define('PDF_TITLE', 'Signed Document');
define('PDF_FONT_SIZE', 10);
define('PDF_FONT_FAMILY', 'helvetica');

// Security Settings
define('ALLOW_IP_VERIFICATION', true);
define('LOG_ALL_ACTIONS', true);
define('REQUIRE_HTTPS', false);
define('SIGNATURE_VALIDITY_DAYS', 365);

// Document Settings
define('DOCUMENTS_PER_PAGE', 20);
define('ARCHIVE_AFTER_DAYS', 90);

// Initialize directories
foreach ([UPLOAD_DIR, PDF_DIR, SIGNATURE_DIR, TEMPLATE_DIR, LOG_DIR] as $dir) {
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }
}

// Database Connection
try {
    $pdo = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET,
        DB_USER,
        DB_PASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_PERSISTENT => false
        ]
    );
} catch (PDOException $e) {
    die('Database connection failed: ' . $e->getMessage());
}

// Helper Functions - wrapped to prevent redeclaration errors
if (!function_exists('get_client_ip')) {
    function get_client_ip() {
        if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
            return $_SERVER['HTTP_CF_CONNECTING_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
        }
        return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    }
}

if (!function_exists('get_user_agent')) {
    function get_user_agent() {
        return $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
    }
}

if (!function_exists('generate_secure_token')) {
    function generate_secure_token($length = 32) {
        return bin2hex(random_bytes($length));
    }
}

if (!function_exists('hash_signature')) {
    function hash_signature($signature_data) {
        return hash('sha256', $signature_data . SECRET_KEY);
    }
}

if (!function_exists('verify_csrf_token')) {
    function verify_csrf_token($token) {
        return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
    }
}

if (!function_exists('set_csrf_token')) {
    function set_csrf_token() {
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = generate_secure_token();
        }
        return $_SESSION['csrf_token'];
    }
}

if (!function_exists('sanitize_input')) {
    function sanitize_input($input) {
        return htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('log_action')) {
    function log_action($user_id, $document_id, $action, $details = '') {
        global $pdo;
        try {
            $stmt = $pdo->prepare("
                INSERT INTO audit_log (user_id, document_id, action, details, ip_address, user_agent, created_at)
                VALUES (?, ?, ?, ?, ?, ?, NOW())
            ");
            $stmt->execute([
                $user_id,
                $document_id,
                $action,
                $details,
                get_client_ip(),
                get_user_agent()
            ]);
        } catch (Exception $e) {
            error_log("Audit log error: " . $e->getMessage());
        }
    }
}

if (!function_exists('is_logged_in')) {
    function is_logged_in() {
        return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
    }
}

if (!function_exists('get_current_user')) {
    function get_current_user() {
        if (!is_logged_in()) {
            return null;
        }
        global $pdo;
        try {
            $stmt = $pdo->prepare("SELECT id, username, email, role, garage_name FROM users WHERE id = ?");
            $stmt->execute([$_SESSION['user_id']]);
            return $stmt->fetch();
        } catch (Exception $e) {
            return null;
        }
    }
}

if (!function_exists('redirect')) {
    function redirect($url) {
        header('Location: ' . $url);
        exit;
    }
}

if (!function_exists('json_response')) {
    function json_response($data, $status_code = 200) {
        http_response_code($status_code);
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }
}
?>