<?php
// Database Configuration
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'crm_casa_style');
define('DB_CHARSET', 'utf8mb4');

// Application Configuration
define('APP_NAME', 'BlidStore');define('APP_FULL_NAME', 'BlidStore — Magazin online');
define('APP_URL', 'http://localhost/Efim/crm-php');
define('UPLOAD_DIR', __DIR__ . '/../uploads/');

// Session Configuration
define('SESSION_TIMEOUT', 3600); // 1 hour

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

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Database Connection
try {
    $db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    
    if ($db->connect_error) {
        die("Database connection failed: " . $db->connect_error);
    }
    
    $db->set_charset(DB_CHARSET);
} catch (Exception $e) {
    die("Connection Error: " . $e->getMessage());
}

// Helper: Check if user is logged in
function isLoggedIn() {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

// Helper: Get current user
function getCurrentUser() {
    global $db;
    if (!isLoggedIn()) {
        return null;
    }
    $user_id = (int)$_SESSION['user_id'];
    $result = $db->query("SELECT * FROM users WHERE id = $user_id");
    if (!$result) {
        return null;
    }
    $user = $result->fetch_assoc();
    
    // If user is inactive, clear session
    if ($user && !$user['active']) {
        session_destroy();
        return null;
    }
    
    return $user;
}

// Helper: Check if user has permission
function hasPermission($role) {
    $user = getCurrentUser();
    if (!$user) return false;
    if ($user['role'] == 'admin') return true;
    return $user['role'] == $role;
}

// Helper: Escape string for database
function escape($str) {
    global $db;
    return $db->real_escape_string($str);
}

// Helper: Format price
function formatPrice($price) {
    return number_format($price, 2, '.', '') . ' lei';
}

// Helper: Format date
function formatDate($date) {
    if (empty($date)) return '—';
    return date('d.m.Y', strtotime($date));
}

// Helper: Generate ID
function generateId($table) {
    global $db;
    $result = $db->query("SELECT MAX(id) as max_id FROM $table");
    $row = $result->fetch_assoc();
    return ($row['max_id'] ?? 0) + 1;
}

// Helper: Get full client name
function getClientName($first_name, $last_name = '') {
    $name = trim($first_name . ' ' . $last_name);
    return empty($name) ? 'Client necunoscut' : $name;
}

// Helper: Redirect to login
function redirectToLogin() {
    header("Location: " . APP_URL . "/login.php");
    exit;
}

// Helper: Redirect with message
function redirectWithMessage($url, $message, $type = 'success') {
    $_SESSION['message'] = ['text' => $message, 'type' => $type];
    header("Location: $url");
    exit;
}

// Helper: Get message and clear
function getAndClearMessage() {
    if (isset($_SESSION['message'])) {
        $msg = $_SESSION['message'];
        unset($_SESSION['message']);
        return $msg;
    }
    return null;
}

// API Response
function jsonResponse($data, $status = 200) {
    header('Content-Type: application/json');
    http_response_code($status);
    echo json_encode($data);
    exit;
}

// Error handler
function handleError($message, $status = 400) {
    jsonResponse(['success' => false, 'error' => $message], $status);
}

// Success handler
function handleSuccess($data = [], $message = 'Success') {
    jsonResponse(['success' => true, 'message' => $message, 'data' => $data], 200);
}

// Audit Log: Log user actions
function auditLog($action, $entity_type, $entity_id, $entity_name = '', $old_values = [], $new_values = []) {
    global $db;
    
    $user = getCurrentUser();
    $user_id = $user ? $user['id'] : null;
    
    // Get client IP
    $ip_address = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    if (strpos($ip_address, ',') !== false) {
        $ip_address = explode(',', $ip_address)[0];
    }
    $ip_address = trim($ip_address);
    $ip_address = escape($ip_address);
    
    // Get user agent
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
    $user_agent = escape(substr($user_agent, 0, 500));
    
    // Convert arrays to JSON
    $old_values_json = !empty($old_values) ? json_encode($old_values) : null;
    $new_values_json = !empty($new_values) ? json_encode($new_values) : null;
    
    $action = escape($action);
    $entity_type = escape($entity_type);
    $entity_id = (int)$entity_id;
    $entity_name = escape(substr($entity_name, 0, 500));
    
    // Prepare JSON values (NULL if empty, otherwise quoted JSON string)
    $old_values_sql = $old_values_json ? "'" . $db->real_escape_string($old_values_json) . "'" : "NULL";
    $new_values_sql = $new_values_json ? "'" . $db->real_escape_string($new_values_json) . "'" : "NULL";
    
    $query = "INSERT INTO audit_logs (user_id, action, entity_type, entity_id, entity_name, old_values, new_values, ip_address, user_agent) 
              VALUES ($user_id, '$action', '$entity_type', $entity_id, '$entity_name', $old_values_sql, $new_values_sql, '$ip_address', '$user_agent')";
    
    $db->query($query);
}
?>
