<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
auth_require_login();
$pdo = crm_pdo();
$page_title = 'Upload Manager';

$uploadDirFs = __DIR__ . '/../uploads/branding';
$uploadDirWeb = '/public/uploads/branding';
if (!is_dir($uploadDirFs)) @mkdir($uploadDirFs, 0775, true);

$ok = '';
$errors = [];

function gp_save_setting(PDO $pdo, string $key, string $value): void
{
    $stmt = $pdo->prepare("
        INSERT INTO settings (setting_key, setting_value)
        VALUES (:k, :v)
        ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
    ");
    $stmt->execute([':k' => $key, ':v' => $value]);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_FILES['brand_logo']['name']) && ($_FILES['brand_logo']['error'] ?? 1) === 0) {
        $safe = preg_replace('/[^A-Za-z0-9._-]/', '_', (string)$_FILES['brand_logo']['name']);
        $targetName = 'logo_' . time() . '_' . $safe;
        $targetFs = $uploadDirFs . '/' . $targetName;
        if (move_uploaded_file($_FILES['brand_logo']['tmp_name'], $targetFs)) {
            gp_save_setting($pdo, 'brand_logo', $uploadDirWeb . '/' . $targetName);
            $ok .= 'Logo uploaded. ';
        } else {
            $errors[] = 'Logo upload failed.';
        }
    }

    if (!empty($_FILES['brand_favicon']['name']) && ($_FILES['brand_favicon']['error'] ?? 1) === 0) {
        $safe = preg_replace('/[^A-Za-z0-9._-]/', '_', (string)$_FILES['brand_favicon']['name']);
        $targetName = 'favicon_' . time() . '_' . $safe;
        $targetFs = $uploadDirFs . '/' . $targetName;
        if (move_uploaded_file($_FILES['brand_favicon']['tmp_name'], $targetFs)) {
            gp_save_setting($pdo, 'brand_favicon', $uploadDirWeb . '/' . $targetName);
            $ok .= 'Favicon uploaded. ';
        } else {
            $errors[] = 'Favicon upload failed.';
        }
    }

    if (!empty($_FILES['background_image']['name']) && ($_FILES['background_image']['error'] ?? 1) === 0) {
        $safe = preg_replace('/[^A-Za-z0-9._-]/', '_', (string)$_FILES['background_image']['name']);
        $targetName = 'bg_' . time() . '_' . $safe;
        $targetFs = $uploadDirFs . '/' . $targetName;
        if (move_uploaded_file($_FILES['background_image']['tmp_name'], $targetFs)) {
            gp_save_setting($pdo, 'background_image', $uploadDirWeb . '/' . $targetName);
            gp_save_setting($pdo, 'background_type', 'image');
            $ok .= 'Background image uploaded. ';
        } else {
            $errors[] = 'Background upload failed.';
        }
    }
}

$currentLogo = '';
$currentBg = '';
$currentFavicon = '';

foreach (['brand_logo', 'background_image', 'brand_favicon'] as $k) {
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = :k LIMIT 1");
    $stmt->execute([':k' => $k]);
    $val = (string)($stmt->fetchColumn() ?: '');
    if ($k === 'brand_logo') $currentLogo = $val;
    if ($k === 'background_image') $currentBg = $val;
    if ($k === 'brand_favicon') $currentFavicon = $val;
}

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Upload Manager</h1>
    <span>Logo, favicon, and background image uploads</span>
  </div>
  <div class="page-header-actions">
    <a class="btn btn-secondary btn-sm" href="/public/settings/branding.php">Back to branding</a>
  </div>
</div>

<div class="grid-2">
  <div class="card">
    <?php if ($ok !== ''): ?>
      <div class="alert-danger" style="background:rgba(22,163,74,.15);color:#166534;border-color:rgba(22,163,74,.25)"><?php echo h(trim($ok)); ?></div>
    <?php endif; ?>
    <?php if ($errors): ?>
      <div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div>
    <?php endif; ?>

    <form method="post" enctype="multipart/form-data">
      <div class="form-grid">
        <div class="form-group">
          <label>Upload logo</label>
          <input type="file" name="brand_logo" accept="image/*">
        </div>
        <div class="form-group">
          <label>Upload favicon</label>
          <input type="file" name="brand_favicon" accept=".ico,image/png,image/x-icon">
        </div>
        <div class="form-group" style="grid-column:1/-1">
          <label>Upload background image</label>
          <input type="file" name="background_image" accept="image/*">
        </div>
      </div>
      <div class="form-actions">
        <button class="btn btn-primary" type="submit">Upload files</button>
      </div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Current assets</h1><span>Active uploaded branding files</span></div>
    <p><strong>Logo:</strong> <?php echo h($currentLogo ?: '-'); ?></p>
    <p><strong>Favicon:</strong> <?php echo h($currentFavicon ?: '-'); ?></p>
    <p><strong>Background:</strong> <?php echo h($currentBg ?: '-'); ?></p>
    <?php if ($currentLogo): ?><p><img src="<?php echo h($currentLogo); ?>" alt="" style="max-width:180px;max-height:80px"></p><?php endif; ?>
    <?php if ($currentBg): ?><p><img src="<?php echo h($currentBg); ?>" alt="" style="max-width:100%;max-height:220px;border-radius:14px"></p><?php endif; ?>
  </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
