<?php
// File: /fuelpos/admin/payment_types.php
require __DIR__ . '/../init.php';
require_login();
$pdo = pdo();

if (!function_exists('esc')) {
    function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
}

$messages = [];
$action = $_POST['action'] ?? $_GET['action'] ?? '';

// ============================================
// CREATE
// ============================================
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $type = trim($_POST['type'] ?? '');
    
    if (empty($type)) {
        $messages[] = ['type' => 'danger', 'text' => 'El nombre del tipo de pago es obligatorio.'];
    } else {
        try {
            $stmt = $pdo->prepare("INSERT INTO payment_types (type) VALUES (?)");
            $stmt->execute([$type]);
            $messages[] = ['type' => 'success', 'text' => 'Tipo de pago creado exitosamente.'];
        } catch (PDOException $e) {
            if ($e->getCode() == 23000) {
                $messages[] = ['type' => 'danger', 'text' => 'Este tipo de pago ya existe.'];
            } else {
                $messages[] = ['type' => 'danger', 'text' => 'Error al crear tipo de pago: ' . $e->getMessage()];
            }
        }
    }
}

// ============================================
// UPDATE
// ============================================
if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    $type = trim($_POST['type'] ?? '');
    
    if ($id <= 0) {
        $messages[] = ['type' => 'danger', 'text' => 'ID inválido.'];
    } elseif (empty($type)) {
        $messages[] = ['type' => 'danger', 'text' => 'El nombre del tipo de pago es obligatorio.'];
    } else {
        try {
            $stmt = $pdo->prepare("UPDATE payment_types SET type = ? WHERE id = ?");
            $stmt->execute([$type, $id]);
            $messages[] = ['type' => 'success', 'text' => 'Tipo de pago actualizado exitosamente.'];
        } catch (PDOException $e) {
            if ($e->getCode() == 23000) {
                $messages[] = ['type' => 'danger', 'text' => 'Este tipo de pago ya existe.'];
            } else {
                $messages[] = ['type' => 'danger', 'text' => 'Error al actualizar: ' . $e->getMessage()];
            }
        }
    }
}

// ============================================
// DELETE
// ============================================
if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    
    if ($id <= 0) {
        $messages[] = ['type' => 'danger', 'text' => 'ID inválido.'];
    } else {
        try {
            $stmt = $pdo->prepare("DELETE FROM payment_types WHERE id = ?");
            $stmt->execute([$id]);
            $messages[] = ['type' => 'success', 'text' => 'Tipo de pago eliminado exitosamente.'];
        } catch (PDOException $e) {
            $messages[] = ['type' => 'danger', 'text' => 'Error al eliminar: ' . $e->getMessage()];
        }
    }
}

// ============================================
// GET ALL
// ============================================
$stmt = $pdo->query("SELECT * FROM payment_types ORDER BY id ASC");
$paymentTypes = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ============================================
// GET ONE FOR EDIT
// ============================================
$editItem = null;
if (isset($_GET['edit'])) {
    $editId = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM payment_types WHERE id = ?");
    $stmt->execute([$editId]);
    $editItem = $stmt->fetch(PDO::FETCH_ASSOC);
}

?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>Gestionar Tipos de Pago</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
  <style>
    body {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      min-height: 100vh;
    }
    
    .container {
      max-width: 1000px;
    }
    
    .main-card {
      background: white;
      border-radius: 20px;
      padding: 30px;
      box-shadow: 0 20px 60px rgba(0,0,0,0.3);
      margin-top: 30px;
      margin-bottom: 30px;
    }
    
    .page-header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 25px;
      border-radius: 15px;
      margin-bottom: 30px;
    }
    
    .page-header h3 {
      margin: 0;
      font-weight: 700;
    }
    
    .badge-payment {
      font-size: 14px;
      padding: 8px 16px;
      border-radius: 8px;
      font-weight: 600;
    }
    
    .btn {
      border-radius: 10px;
      padding: 10px 20px;
      font-weight: 600;
      transition: all 0.3s ease;
    }
    
    .card {
      border: none;
      border-radius: 15px;
      box-shadow: 0 5px 15px rgba(0,0,0,0.08);
    }
    
    .table {
      background: white;
      border-radius: 10px;
      overflow: hidden;
    }
    
    .navbar {
      background: white !important;
      box-shadow: 0 4px 20px rgba(0,0,0,0.1);
    }
  </style>
</head>
<body>

<nav class="navbar navbar-light">
  <div class="container">
    <a class="navbar-brand fw-bold" href="<?= site('admin/index.php') ?>">
      <i class="bi bi-credit-card-fill"></i> Tipos de Pago
    </a>
    <div class="ms-auto">
      <a class="btn btn-outline-secondary btn-sm" href="<?= site('admin/index.php') ?>">
        <i class="bi bi-arrow-left"></i> Volver
      </a>
    </div>
  </div>
</nav>

<div class="container">
  <div class="main-card">
    
    <div class="page-header">
      <h3><i class="bi bi-credit-card-2-front-fill"></i> Gestionar Tipos de Pago</h3>
      <p class="mb-0 mt-2" style="opacity:0.9">Administra los métodos de pago disponibles en el sistema</p>
    </div>

    <?php foreach ($messages as $m): ?>
      <div class="alert alert-<?= esc($m['type']) ?> alert-dismissible fade show" role="alert">
        <?= esc($m['text']) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
    <?php endforeach; ?>

    <!-- CREAR NUEVO / EDITAR -->
    <div class="card mb-4">
      <div class="card-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
        <h5 class="mb-0">
          <i class="bi bi-<?= $editItem ? 'pencil-square' : 'plus-circle' ?>"></i>
          <?= $editItem ? 'Editar Tipo de Pago' : 'Crear Nuevo Tipo de Pago' ?>
        </h5>
      </div>
      <div class="card-body">
        <form method="post" class="row g-3">
          <input type="hidden" name="action" value="<?= $editItem ? 'update' : 'create' ?>">
          <?php if ($editItem): ?>
            <input type="hidden" name="id" value="<?= esc($editItem['id']) ?>">
          <?php endif; ?>
          
          <div class="col-md-8">
            <label class="form-label fw-bold">
              <i class="bi bi-tag-fill"></i> Nombre del Tipo de Pago <span class="text-danger">*</span>
            </label>
            <input 
              type="text" 
              class="form-control form-control-lg" 
              name="type" 
              placeholder="Ej: efectivo, tarjeta, transferencia" 
              value="<?= $editItem ? esc($editItem['type']) : '' ?>" 
              required
              maxlength="100"
            >
            <small class="text-muted">
              <i class="bi bi-info-circle"></i>
              Ejemplos: cash, card, transfer, external, cheque, etc.
            </small>
          </div>

          <div class="col-md-4 d-flex align-items-end gap-2">
            <button type="submit" class="btn btn-<?= $editItem ? 'primary' : 'success' ?> w-100">
              <i class="bi bi-<?= $editItem ? 'check-circle' : 'plus-circle' ?>"></i>
              <?= $editItem ? 'Actualizar' : 'Crear' ?>
            </button>
            <?php if ($editItem): ?>
              <a href="<?= site('admin/payment_types.php') ?>" class="btn btn-outline-secondary">
                <i class="bi bi-x-circle"></i> Cancelar
              </a>
            <?php endif; ?>
          </div>
        </form>
      </div>
    </div>

    <!-- LISTA DE TIPOS DE PAGO -->
    <div class="card">
      <div class="card-header bg-light">
        <h5 class="mb-0">
          <i class="bi bi-list-ul"></i> 
          Tipos de Pago Existentes 
          <span class="badge bg-primary"><?= count($paymentTypes) ?></span>
        </h5>
      </div>
      <div class="card-body">
        <?php if (empty($paymentTypes)): ?>
          <div class="alert alert-info">
            <i class="bi bi-info-circle-fill"></i>
            No hay tipos de pago registrados. Crea uno usando el formulario de arriba.
          </div>
        <?php else: ?>
          <div class="table-responsive">
            <table class="table table-hover align-middle">
              <thead class="table-dark">
                <tr>
                  <th style="width:80px"><i class="bi bi-hash"></i> ID</th>
                  <th><i class="bi bi-tag-fill"></i> Tipo de Pago</th>
                  <th style="width:180px"><i class="bi bi-calendar3"></i> Fecha Creación</th>
                  <th style="width:200px" class="text-end"><i class="bi bi-gear-fill"></i> Acciones</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($paymentTypes as $pt): ?>
                <tr>
                  <td><strong><?= esc($pt['id']) ?></strong></td>
                  <td>
                    <span class="badge badge-payment bg-primary">
                      <i class="bi bi-credit-card"></i> <?= esc($pt['type']) ?>
                    </span>
                  </td>
                  <td>
                    <small class="text-muted">
                      <i class="bi bi-clock"></i>
                      <?= isset($pt['created_at']) ? date('d/m/Y H:i', strtotime($pt['created_at'])) : '—' ?>
                    </small>
                  </td>
                  <td class="text-end">
                    <a 
                      href="?edit=<?= esc($pt['id']) ?>" 
                      class="btn btn-sm btn-outline-primary"
                      title="Editar"
                    >
                      <i class="bi bi-pencil-fill"></i> Editar
                    </a>
                    
                    <form method="post" style="display:inline" onsubmit="return confirm('¿Eliminar este tipo de pago?');">
                      <input type="hidden" name="action" value="delete">
                      <input type="hidden" name="id" value="<?= esc($pt['id']) ?>">
                      <button type="submit" class="btn btn-sm btn-outline-danger" title="Eliminar">
                        <i class="bi bi-trash-fill"></i> Eliminar
                      </button>
                    </form>
                  </td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <div class="mt-4">
      <a href="<?= site('admin/index.php') ?>" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left"></i> Volver al Panel Admin
      </a>
    </div>
    
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>