<?php
require_once __DIR__ . '/../config.php';
if (!defined('MDW_ADMIN_VERSION')) define('MDW_ADMIN_VERSION', '0.9.4');

function mdw_start_admin(): void {
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_name('MDWADMINSESSID');
        session_start();
    }
}

function mdw_is_logged_in(): bool {
    mdw_start_admin();
    return !empty($_SESSION['mdw_admin_logged_in']);
}

function mdw_require_login(): void {
    if (!mdw_is_logged_in()) {
        header('Location: login.php');
        exit;
    }
}

function mdw_h(string $value): string {
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

function mdw_read_json(string $file, array $fallback = []): array {
    if (!file_exists($file)) return $fallback;
    $raw = file_get_contents($file);
    $data = json_decode($raw, true);
    return is_array($data) ? $data : $fallback;
}

function mdw_write_json(string $file, array $data): bool {
    $dir = dirname($file);
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    return file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) !== false;
}

function mdw_slug(string $text): string {
    $text = strtolower(trim($text));
    $text = preg_replace('/[^a-z0-9]+/', '-', $text);
    return trim($text, '-') ?: 'item';
}

function mdw_flash(?string $message = null, string $type = 'success'): ?array {
    mdw_start_admin();
    if ($message !== null) {
        $_SESSION['mdw_flash'] = ['message' => $message, 'type' => $type];
        return null;
    }
    if (!empty($_SESSION['mdw_flash'])) {
        $flash = $_SESSION['mdw_flash'];
        unset($_SESSION['mdw_flash']);
        return $flash;
    }
    return null;
}

function mdw_data_file(string $name): string {
    return __DIR__ . '/../data/' . $name;
}

function mdw_settings(): array {
    $defaults = [
        'invoice_prefix' => 'MDW-INV',
        'invoice_year' => date('Y'),
        'next_invoice_number' => 1,
    ];
    $settings = mdw_read_json(mdw_data_file('settings.json'), []);
    return array_merge($defaults, is_array($settings) ? $settings : []);
}

function mdw_save_settings(array $settings): bool {
    return mdw_write_json(mdw_data_file('settings.json'), $settings);
}

function mdw_peek_next_invoice_number(): string {
    $settings = mdw_settings();
    $year = (string)($settings['invoice_year'] ?? date('Y'));
    if ($year !== date('Y')) {
        $year = date('Y');
        $settings['invoice_year'] = $year;
        $settings['next_invoice_number'] = 1;
    }
    $prefix = trim((string)($settings['invoice_prefix'] ?? 'MDW-INV')) ?: 'MDW-INV';
    $next = max(1, (int)($settings['next_invoice_number'] ?? 1));
    return $prefix . '-' . $year . '-' . str_pad((string)$next, 4, '0', STR_PAD_LEFT);
}

function mdw_claim_next_invoice_number(): string {
    $settings = mdw_settings();
    $year = (string)($settings['invoice_year'] ?? date('Y'));
    if ($year !== date('Y')) {
        $year = date('Y');
        $settings['invoice_year'] = $year;
        $settings['next_invoice_number'] = 1;
    }
    $prefix = trim((string)($settings['invoice_prefix'] ?? 'MDW-INV')) ?: 'MDW-INV';
    $next = max(1, (int)($settings['next_invoice_number'] ?? 1));
    $invoiceNumber = $prefix . '-' . $year . '-' . str_pad((string)$next, 4, '0', STR_PAD_LEFT);
    $settings['next_invoice_number'] = $next + 1;
    mdw_save_settings($settings);
    return $invoiceNumber;
}

function mdw_is_blank_invoice_number(string $value): bool {
    $value = trim($value);
    return $value === '' || stripos($value, 'auto') !== false || preg_match('/^MDW-\d{8}$/', $value);
}

function mdw_clients(): array {
    global $mdw_clients_file;
    $file = $mdw_clients_file ?? mdw_data_file('clients.json');
    return mdw_read_json($file, []);
}

function mdw_client_name(array $clients, string $clientId): string {
    foreach ($clients as $client) {
        if (($client['id'] ?? '') === $clientId) return (string)($client['business_name'] ?: ($client['client_name'] ?? ''));
    }
    return '';
}

function mdw_render_header(string $title): void {
    $flash = mdw_flash();
    $currentPage = basename($_SERVER['PHP_SELF'] ?? 'index.php');
    $isDocPage = str_starts_with($currentPage, 'document') || $currentPage === 'documents.php';
    $navClass = function(string $page) use ($currentPage): string {
        return $currentPage === $page ? ' class="active"' : '';
    };
    ?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?php echo mdw_h($title); ?> | MDW Admin</title>
  <link rel="stylesheet" href="assets/admin.css">
</head>
<body>
<header class="mdwa-mobilebar">
  <button class="mdwa-menu-toggle" type="button" aria-label="Open admin menu" aria-controls="mdwa-sidebar" aria-expanded="false" onclick="mdwToggleMenu()">☰</button>
  <div class="mdwa-mobile-title">
    <strong>Murdock DevWorks Admin</strong>
    <span><?php echo mdw_h($title); ?></span>
  </div>
  <a class="mdwa-view-site" href="../" target="_blank" rel="noopener">View Site</a>
</header>
<div class="mdwa-overlay" onclick="mdwCloseMenu()" aria-hidden="true"></div>
<div class="mdwa-layout">
<aside class="mdwa-sidebar" id="mdwa-sidebar">
  <div class="mdwa-brand">
    <img class="mdwa-logo-icon" src="../images/logo/murdock-devworks-icon.png" alt="Murdock DevWorks" onerror="this.style.display='none'">
    <div class="mdwa-brand-text">
      <strong class="mdwa-brand-name"><span>Murdock</span><span>DevWorks</span></strong>
      <span class="mdwa-brand-admin">Admin</span>
      <span class="mdwa-brand-page"><?php echo mdw_h($title); ?></span>
    </div>
  </div>

  <nav class="mdwa-nav" aria-label="Admin navigation">
    <a href="index.php"<?php echo $navClass('index.php'); ?>>Dashboard</a>
    <a href="clients.php"<?php echo $navClass('clients.php'); ?>>Clients</a>

    <details class="mdwa-nav-flyout" <?php echo $isDocPage ? 'open' : ''; ?>>
      <summary class="<?php echo $isDocPage ? 'active' : ''; ?>">Documents</summary>
      <div class="mdwa-flyout-panel">
        <a href="documents.php"<?php echo $navClass('documents.php'); ?>>Templates</a>
        <a href="document-edit.php"<?php echo $currentPage === 'document-edit.php' ? ' class="active"' : ''; ?>>New Document</a>
        <a href="documents.php#saved-documents">Saved Documents</a>
        <a href="invoices-export.php"<?php echo $navClass('invoices-export.php'); ?>>Invoice CSV</a>
      </div>
    </details>

    <a href="projects.php"<?php echo $navClass('projects.php'); ?>>Projects</a>
    <a href="downloads.php"<?php echo $navClass('downloads.php'); ?>>Downloads</a>
    <a href="updater.php"<?php echo $navClass('updater.php'); ?>>Updater</a>
    <a href="../" target="_blank" rel="noopener">View Website</a>
    <a class="logout" href="logout.php">Logout</a>
  </nav>
</aside>
<section class="mdwa-content">
<main class="mdwa-shell">
<?php if ($flash): ?>
  <div class="alert <?php echo mdw_h($flash['type']); ?>"><?php echo mdw_h($flash['message']); ?></div>
<?php endif; ?>
    <?php
}

function mdw_render_footer(): void {
    ?>
</main>
<footer class="mdwa-footer">Murdock DevWorks Admin v<?php echo mdw_h(MDW_ADMIN_VERSION); ?> &mdash; separate from Ecommerce Templates</footer>
</section>
</div>
<script>
function mdwToggleMenu(){
  var body = document.body;
  var expanded = body.classList.toggle('mdwa-menu-open');
  var btn = document.querySelector('.mdwa-menu-toggle');
  if(btn){ btn.setAttribute('aria-expanded', expanded ? 'true' : 'false'); }
}
function mdwCloseMenu(){
  document.body.classList.remove('mdwa-menu-open');
  var btn = document.querySelector('.mdwa-menu-toggle');
  if(btn){ btn.setAttribute('aria-expanded','false'); }
}
document.addEventListener('keydown', function(e){ if(e.key === 'Escape') mdwCloseMenu(); });
document.querySelectorAll('.mdwa-nav a').forEach(function(link){
  link.addEventListener('click', function(){ if(window.innerWidth <= 900) mdwCloseMenu(); });
});
</script>
</body>
</html>
    <?php
}

function mdw_is_excluded(string $relativePath, array $exclusions): bool {
    $relativePath = ltrim(str_replace('\\', '/', $relativePath), '/');
    foreach ($exclusions as $rule) {
        $rule = ltrim(str_replace('\\', '/', $rule), '/');
        if (str_ends_with($rule, '/')) {
            if (str_starts_with($relativePath, $rule)) return true;
        } elseif ($relativePath === $rule) {
            return true;
        }
    }
    return false;
}
