<?php
function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
function redirect(string $url): void { header('Location: ' . $url); exit; }

function csrf_token(): string {
    if (empty($_SESSION['csrf_token'])) {
        try {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        } catch (Exception $e) {
            $_SESSION['csrf_token'] = bin2hex(uniqid('gp', true));
        }
    }
    return $_SESSION['csrf_token'];
}

function csrf_field(): string {
    return '<input type="hidden" name="csrf_token" value="' . h(csrf_token()) . '">';
}

function csrf_verify(string $token): bool {
    if (empty($_SESSION['csrf_token']) || empty($token)) return false;
    return hash_equals($_SESSION['csrf_token'], $token);
}

function gp_require_csrf(): void {
    $token = $_POST['csrf_token'] ?? '';
    if (!csrf_verify($token)) {
        http_response_code(419);
        die('CSRF token validation failed. Please refresh the page and try again.');
    }
}

function gp_log_action(PDO $pdo, string $action_type, string $entity_type = '', int $entity_id = 0, string $details = ''): void {
    try {
        $uid = (int)($_SESSION['auth_user']['id'] ?? 0);
        $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
        $stmt = $pdo->prepare("INSERT INTO system_logs (user_id, action_type, entity_type, entity_id, ip_address, details) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$uid, substr($action_type, 0, 100), substr($entity_type, 0, 50), $entity_id, $ip, $details]);

        if ($entity_type === 'project' && $entity_id > 0) {
            $stManager = $pdo->prepare("
                SELECT p.title, p.manager_id, u.email 
                FROM projects p 
                LEFT JOIN users u ON u.id = p.manager_id 
                WHERE p.id = ?
            ");
            $stManager->execute([$entity_id]);
            $mgr = $stManager->fetch();
            
            if ($mgr) {
                // Get updater info
                $updater = 'Άγνωστος χρήστης';
                $updaterEmail = '';
                if ($uid > 0) {
                    $stUser = $pdo->prepare("SELECT username, email FROM users WHERE id = ?");
                    $stUser->execute([$uid]);
                    $uInfo = $stUser->fetch();
                    if ($uInfo) {
                        $updater = $uInfo['username'];
                        $updaterEmail = $uInfo['email'];
                    }
                }

                $subject = "Ενημέρωση Έργου: " . $mgr['title'];
                $msg = "Γεια σας,\n\nΈγινε μια νέα ενέργεια στο έργο '{$mgr['title']}' από τον/την χρήστη: {$updater}.\n\nΕνέργεια/Πληροφορίες: {$details}\n\nΑυτή είναι μια αυτοματοποιημένη ειδοποίηση.\n\nGoPools CRM";
                
                $recipients = [];
                
                // Add Admin emails (if updater is not this admin)
                $stAdmins = $pdo->query("SELECT email FROM users WHERE role = 'admin' AND email != ''");
                while ($a = $stAdmins->fetch()) {
                    if ($a['email'] !== $updaterEmail) {
                        $recipients[] = $a['email'];
                    }
                }
                
                // Add Manager email (if updater is not manager)
                if (!empty($mgr['email']) && $mgr['email'] !== $updaterEmail) {
                    $recipients[] = $mgr['email'];
                }
                
                $recipients = array_unique($recipients);
                
                foreach ($recipients as $to) {
                    gp_send_email($to, $subject, $msg);
                }
            }
        }
    } catch (\Throwable $e) {}
}
function gp_send_email(string $to, string $subject, string $message): bool {
    $headers = [
        'MIME-Version: 1.0',
        'Content-type: text/plain; charset=utf-8',
        'From: GoPools CRM <projects@gopools.gr>',
        'X-Mailer: PHP/' . phpversion()
    ];
    return @mail($to, $subject, $message, implode("\r\n", $headers));
}

/**
 * Returns the absolute filesystem path to the uploads directory.
 * Works on both XAMPP (C:/xampp/htdocs/gopools/public/uploads)
 * and cPanel (/home/user/public_html/gopools/public/uploads)
 * 
 * @param string $subdir  Optional subdirectory, e.g. 'project_photos'
 */
function gp_upload_path(string $subdir = ''): string {
    // helpers/ -> app/ -> root -> public/uploads
    $base = dirname(__DIR__, 2) . '/public/uploads';
    $path = $subdir ? rtrim($base, '/') . '/' . ltrim($subdir, '/') : $base;
    if (!is_dir($path)) {
        @mkdir($path, 0755, true);
    }
    return $path;
}

/**
 * Returns the web-accessible URL to the uploads directory.
 * Auto-detects the app base from the request URI.
 *
 * @param string $subdir   Optional subdirectory, e.g. 'project_photos'
 * @param string $filename Optional filename
 */
function gp_upload_url(string $subdir = '', string $filename = ''): string {
    $scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
    // Find 'public' segment to determine base URL
    $pos = strpos($scriptName, '/public/');
    if ($pos !== false) {
        $appBase = substr($scriptName, 0, $pos);
    } else {
        $appBase = '';
    }
    $url = rtrim($appBase, '/') . '/public/uploads';
    if ($subdir)  $url .= '/' . ltrim($subdir, '/');
    if ($filename) $url .= '/' . ltrim($filename, '/');
    return $url;
}

