<?php
// gabinete/src/actions/employees/update.php
declare(strict_types=1);
session_start();

require_once __DIR__ . '/../../config/db.php';

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
  header('Location: ' . BASE_URL . '/src/views/employees/colaboradores.php');
  exit;
}

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$id || $id <= 0) {
  $_SESSION['errors'] = ['ID do colaborador inválido.'];
  header('Location: ' . BASE_URL . '/src/views/employees/colaboradores.php');
  exit;
}

// Helpers
function br_money_to_decimal(?string $v): string {
  $v = $v ?? '0';
  $v = preg_replace('/[^\d,\.]/', '', $v) ?: '0';
  $v = str_replace('.', '', $v);
  $v = str_replace(',', '.', $v);
  return $v === '' ? '0' : $v;
}
function random_filename(string $ext): string {
  return bin2hex(random_bytes(8)) . '.' . strtolower($ext);
}

// Campos
$full_name     = trim($_POST['full_name'] ?? '');
$cpf           = trim($_POST['cpf'] ?? '');
$rg            = trim($_POST['rg'] ?? '');
$birth_date    = $_POST['birth_date'] ?: null;
$phone_number  = trim($_POST['phone_number'] ?? '');
$address       = trim($_POST['address'] ?? '');
$job_title     = trim($_POST['job_title'] ?? '');
$salary        = br_money_to_decimal($_POST['salary'] ?? '0');
$hire_date     = $_POST['hire_date'] ?: null;
$contract_type = $_POST['contract_type'] ?? '';
$status        = $_POST['status'] ?? 'ativo';
$cost_center   = trim($_POST['cost_center'] ?? '');
$bank_name     = trim($_POST['bank_name'] ?? '');
$agency_number = trim($_POST['agency_number'] ?? '');
$account_number= trim($_POST['account_number'] ?? '');

$currentPhotoPath = $_POST['current_photo_path'] ?? null;
$removePhoto      = !empty($_POST['remove_photo']);
$errors = [];

// Validações (alinhado ao schema)
if ($full_name === '')  $errors[] = 'Informe o nome completo.';
if ($cpf === '')        $errors[] = 'Informe o CPF.';
if ($rg === '')         $errors[] = 'Informe o RG.';
if (!$birth_date)       $errors[] = 'Informe a data de nascimento.';
if ($address === '')    $errors[] = 'Informe o endereço.';
if ($phone_number === '') $errors[] = 'Informe o telefone.';
if ($job_title === '')  $errors[] = 'Informe o cargo.';
if ($salary === '' || !is_numeric($salary)) $errors[] = 'Salário inválido.';
if (!$hire_date)        $errors[] = 'Informe a data de admissão.';
if (!in_array($contract_type, ['CLT','PJ','Estagiário','Terceirizado'], true)) {
  $errors[] = 'Tipo de contrato inválido.';
}
if (!in_array($status, ['ativo','inativo','demitido'], true)) {
  $errors[] = 'Status inválido.';
}
if ($bank_name === '')     $errors[] = 'Informe o banco.';
if ($agency_number === '') $errors[] = 'Informe a agência.';
if ($account_number === '')$errors[] = 'Informe a conta.';

// Upload/remoção de foto
$newPhotoPath = $currentPhotoPath;

if (!empty($_FILES['photo']['name'])) {
  $tmp  = $_FILES['photo']['tmp_name'];
  $size = (int)($_FILES['photo']['size'] ?? 0);
  $name = (string)($_FILES['photo']['name'] ?? '');
  $ext  = strtolower(pathinfo($name, PATHINFO_EXTENSION));

  if ($size > 5 * 1024 * 1024) {
    $errors[] = 'A imagem excede 5MB.';
  }
  if (!in_array($ext, ['jpg','jpeg','png','webp'], true)) {
    $errors[] = 'Formato inválido. Use JPG, JPEG, PNG ou WEBP.';
  }

  if (is_uploaded_file($tmp)) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime  = finfo_file($finfo, $tmp);
    finfo_close($finfo);
    if (strpos((string)$mime, 'image/') !== 0) {
      $errors[] = 'O arquivo selecionado não é uma imagem válida.';
    }
  } else {
    $errors[] = 'Upload inválido.';
  }

  if (!$errors) {
    $publicRoot = dirname(__DIR__, 3) . '/public';
    $destDir    = $publicRoot . '/uploads/employees';
    if (!is_dir($destDir) && !mkdir($destDir, 0755, true)) {
      $errors[] = 'Não foi possível criar a pasta de uploads.';
    } else {
      $fileName = random_filename($ext);
      $destPath = $destDir . '/' . $fileName;

      if (!move_uploaded_file($tmp, $destPath)) {
        $errors[] = 'Falha ao salvar o upload.';
      } else {
        if (!empty($currentPhotoPath)) {
          $old = $publicRoot . '/' . ltrim($currentPhotoPath, '/');
          if (is_file($old)) @unlink($old);
        }
        $newPhotoPath = 'uploads/employees/' . $fileName;
      }
    }
  }
}

if ($removePhoto && empty($_FILES['photo']['name'])) {
  $publicRoot = dirname(__DIR__, 3) . '/public';
  if (!empty($currentPhotoPath)) {
    $old = $publicRoot . '/' . ltrim($currentPhotoPath, '/');
    if (is_file($old)) @unlink($old);
  }
  $newPhotoPath = null;
}

if ($errors) {
  $_SESSION['errors'] = $errors;
  $_SESSION['old']    = $_POST;
  header('Location: ' . BASE_URL . '/employees/' . $id . '/edit');
  exit;
}

// UPDATE
try {
  $sql = "
    UPDATE employees
       SET full_name      = :full_name,
           cpf            = :cpf,
           rg             = :rg,
           birth_date     = :birth_date,
           phone_number   = :phone_number,
           address        = :address,
           job_title      = :job_title,
           salary         = :salary,
           hire_date      = :hire_date,
           contract_type  = :contract_type,
           status         = :status,
           cost_center    = :cost_center,
           bank_name      = :bank_name,
           agency_number  = :agency_number,
           account_number = :account_number,
           photo_path     = :photo_path,
           updated_at     = NOW()
     WHERE id = :id
     LIMIT 1
  ";
  $stmt = $pdo->prepare($sql);
  $stmt->execute([
    ':full_name'     => $full_name,
    ':cpf'           => $cpf,
    ':rg'            => $rg,
    ':birth_date'    => $birth_date,
    ':phone_number'  => $phone_number,
    ':address'       => $address,
    ':job_title'     => $job_title,
    ':salary'        => $salary,
    ':hire_date'     => $hire_date,
    ':contract_type' => $contract_type,
    ':status'        => $status,
    ':cost_center'   => $cost_center !== '' ? $cost_center : null,
    ':bank_name'     => $bank_name,
    ':agency_number' => $agency_number,
    ':account_number'=> $account_number,
    ':photo_path'    => $newPhotoPath,
    ':id'            => $id,
  ]);
} catch (Throwable $e) {
  $_SESSION['errors'] = ['Erro ao salvar: ' . $e->getMessage()];
  $_SESSION['old']    = $_POST;
  header('Location: ' . BASE_URL . '/employees/' . $id . '/edit');
  exit;
}

header('Location: ' . BASE_URL . '/employees/' . $id);
exit;
