<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_login();
header('Content-Type: application/json');

$mysqli = db();
$action = $_GET['action'] ?? $_POST['action'] ?? 'get';

function ensure_admin_settings() { if (!has_role(['admin','super_admin'])) json_response(['message'=>'Forbidden'], 403); }

// Ensure a row exists
function ensure_row($mysqli){
  $res = $mysqli->query('SELECT id FROM shop_settings LIMIT 1');
  if ($res && $row = $res->fetch_assoc()) return (int)$row['id'];
  $mysqli->query("INSERT INTO shop_settings (company_name,address_line,city_country,company_email,phone) VALUES ('Granite Warehouse','Warehouse Address Line','City, Country','', '-')");
  return (int)$mysqli->insert_id;
}

// Ensure logo_url column exists
function ensure_logo_column($mysqli){
  $res = $mysqli->query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '".$mysqli->real_escape_string(DB_NAME)."' AND TABLE_NAME='shop_settings' AND COLUMN_NAME='logo_url'");
  if (!$res || !$res->fetch_assoc()) {
    $mysqli->query("ALTER TABLE shop_settings ADD COLUMN logo_url VARCHAR(255) NULL AFTER phone");
  }
}

ensure_logo_column($mysqli);

switch ($action) {
  case 'get':
    $id = ensure_row($mysqli);
    $stmt = $mysqli->prepare('SELECT id, company_name, address_line, city_country, company_email, phone, logo_url FROM shop_settings WHERE id = ?');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    json_response(['data' => $row]);
    break;
  case 'update':
    ensure_admin_settings();
    if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message' => 'Invalid CSRF'], 400);
    $id = (int)($_POST['id'] ?? 0);
    if (!$id) { $id = ensure_row($mysqli); }
    $company_name = trim($_POST['company_name'] ?? '');
    $address_line = trim($_POST['address_line'] ?? '');
    $city_country = trim($_POST['city_country'] ?? '');
    $company_email = trim($_POST['company_email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    if ($company_name === '' || $address_line === '' || $city_country === '' || $phone === '') {
      json_response(['message' => 'All fields are required'], 400);
    }
    // Handle logo upload if provided
    $logoUrl = null; $oldLogo = null;
    if (!empty($_FILES['logo']) && is_uploaded_file($_FILES['logo']['tmp_name'])) {
      $file = $_FILES['logo'];
      if ($file['error'] !== UPLOAD_ERR_OK) json_response(['message'=>'Logo upload failed'], 400);
      $finfo = finfo_open(FILEINFO_MIME_TYPE);
      $mime = finfo_file($finfo, $file['tmp_name']);
      finfo_close($finfo);
      $allowed = ['image/png'=>'png','image/jpeg'=>'jpg','image/webp'=>'webp'];
      if (!isset($allowed[$mime])) json_response(['message'=>'Invalid logo type. Allowed: PNG, JPG, WEBP'], 400);
      if ($file['size'] > 5*1024*1024) json_response(['message'=>'Logo too large (max 5MB)'], 400);
      $ext = $allowed[$mime];
      $upDir = realpath(__DIR__ . '/..') . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'logo';
      if (!is_dir($upDir)) { @mkdir($upDir, 0775, true); }
      $name = 'logo_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
      $dest = $upDir . DIRECTORY_SEPARATOR . $name;
      if (!move_uploaded_file($file['tmp_name'], $dest)) json_response(['message'=>'Failed to store logo'], 500);
      // Fetch old logo to delete if present
      $stmt0 = $mysqli->prepare('SELECT logo_url FROM shop_settings WHERE id=?');
      $stmt0->bind_param('i', $id); $stmt0->execute(); $oldLogo = ($stmt0->get_result()->fetch_assoc()['logo_url'] ?? null); $stmt0->close();
      $logoUrl = 'assets/uploads/logo/' . $name;
      // Delete old file if exists and under uploads/logo
      if ($oldLogo && strpos($oldLogo, 'assets/uploads/logo/') === 0) {
        $oldPath = realpath(__DIR__ . '/..' . DIRECTORY_SEPARATOR . $oldLogo);
        if ($oldPath && is_file($oldPath)) { @unlink($oldPath); }
      }
    }

    if ($logoUrl !== null) {
      $stmt = $mysqli->prepare('UPDATE shop_settings SET company_name=?, address_line=?, city_country=?, company_email=?, phone=?, logo_url=? WHERE id=?');
      $stmt->bind_param('ssssssi', $company_name, $address_line, $city_country, $company_email, $phone, $logoUrl, $id);
    } else {
      $stmt = $mysqli->prepare('UPDATE shop_settings SET company_name=?, address_line=?, city_country=?, company_email=?, phone=? WHERE id=?');
      $stmt->bind_param('sssssi', $company_name, $address_line, $city_country, $company_email, $phone, $id);
    }
    if (!$stmt->execute()) json_response(['message'=>$stmt->error], 500);
    // Return updated row
    $stmt2 = $mysqli->prepare('SELECT id, company_name, address_line, city_country, company_email, phone, logo_url FROM shop_settings WHERE id = ?');
    $stmt2->bind_param('i', $id); $stmt2->execute(); $row = $stmt2->get_result()->fetch_assoc();
    json_response(['message'=>'Updated', 'data'=>$row]);
    break;
  default:
    json_response(['message'=>'Invalid action'], 400);
}
