<?php
/**
 * Admin Gift Products Page
 * Manage gift product rules
 */

$pageTitle = 'Produse Cadou';

require_once __DIR__ . '/includes/init.php';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/../../includes/Product.php';

$db = Database::getInstance();
$productObj = new Product();

$message = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_rule':
                $buyProductId = intval($_POST['buy_product_id'] ?? 0);
                $buyQuantity = intval($_POST['buy_quantity'] ?? 1);
                $giftProductId = intval($_POST['gift_product_id'] ?? 0);
                $giftQuantity = intval($_POST['gift_quantity'] ?? 1);
                $minOrderValue = !empty($_POST['min_order_value']) ? floatval($_POST['min_order_value']) : null;
                $isActive = isset($_POST['is_active']) ? 1 : 0;
                
                if ($buyProductId && $giftProductId) {
                    $db->execute(
                        "INSERT INTO gift_products (buy_product_id, buy_quantity, gift_product_id, gift_quantity, 
                         min_order_value, is_active, created_at)
                         VALUES (?, ?, ?, ?, ?, ?, NOW())",
                        [$buyProductId, $buyQuantity, $giftProductId, $giftQuantity, $minOrderValue, $isActive]
                    );
                    $message = 'Regula a fost adăugată cu succes!';
                } else {
                    $error = 'Produsul de cumpărat și produsul cadou sunt obligatorii!';
                }
                break;
            case 'update_rule':
                $ruleId = intval($_POST['rule_id'] ?? 0);
                $buyProductId = intval($_POST['buy_product_id'] ?? 0);
                $buyQuantity = intval($_POST['buy_quantity'] ?? 1);
                $giftProductId = intval($_POST['gift_product_id'] ?? 0);
                $giftQuantity = intval($_POST['gift_quantity'] ?? 1);
                $minOrderValue = !empty($_POST['min_order_value']) ? floatval($_POST['min_order_value']) : null;
                $isActive = isset($_POST['is_active']) ? 1 : 0;
                
                if ($ruleId && $buyProductId && $giftProductId) {
                    $db->execute(
                        "UPDATE gift_products SET buy_product_id = ?, buy_quantity = ?, gift_product_id = ?, 
                         gift_quantity = ?, min_order_value = ?, is_active = ?, updated_at = NOW() WHERE id = ?",
                        [$buyProductId, $buyQuantity, $giftProductId, $giftQuantity, $minOrderValue, $isActive, $ruleId]
                    );
                    $message = 'Regula a fost actualizată cu succes!';
                }
                break;
            case 'delete_rule':
                $ruleId = intval($_POST['rule_id'] ?? 0);
                if ($ruleId) {
                    $db->execute("DELETE FROM gift_products WHERE id = ?", [$ruleId]);
                    $message = 'Regula a fost ștearsă cu succes!';
                }
                break;
        }
    }
}

// Get all gift product rules
$rules = $db->fetchAll(
    "SELECT gp.*, 
            bp.name as buy_product_name, bp.sku as buy_product_sku,
            giftp.name as gift_product_name, giftp.sku as gift_product_sku
     FROM gift_products gp
     LEFT JOIN products bp ON gp.buy_product_id = bp.id
     LEFT JOIN products giftp ON gp.gift_product_id = giftp.id
     ORDER BY gp.created_at DESC"
);

// Get all products for dropdowns
$products = $db->fetchAll("SELECT id, name, sku FROM products WHERE is_active = 1 ORDER BY name");
?>

<div class="content">
  <div class="px-3 px-xxl-4 py-3 py-lg-4">
    <div class="card mb-3">
      <div class="card-header">
        <div class="row flex-between-center">
          <div class="col-auto">
            <h5 class="mb-0">Produse Cadou</h5>
          </div>
          <div class="col-auto">
            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addRuleModal">
              <span class="fas fa-plus me-1"></span>Adaugă regulă
            </button>
          </div>
        </div>
      </div>
      <div class="card-body">
        <?php if ($message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
          <?php echo htmlspecialchars($message); ?>
          <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        <?php if ($error): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
          <?php echo htmlspecialchars($error); ?>
          <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <div class="table-responsive">
          <table class="table table-sm mb-0">
            <thead class="bg-body-tertiary">
              <tr>
                <th>Cumpără</th>
                <th>Cantitate</th>
                <th>Primește</th>
                <th>Cantitate</th>
                <th>Valoare minimă comandă</th>
                <th>Status</th>
                <th>Acțiuni</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($rules)): ?>
              <tr>
                <td colspan="7" class="text-center py-4">Nu există reguli pentru produse cadou.</td>
              </tr>
              <?php else: ?>
              <?php foreach ($rules as $rule): ?>
              <tr>
                <td>
                  <div><?php echo htmlspecialchars($rule['buy_product_name'] ?? 'N/A'); ?></div>
                  <small class="text-600"><?php echo htmlspecialchars($rule['buy_product_sku'] ?? ''); ?></small>
                </td>
                <td><?php echo number_format($rule['buy_quantity']); ?></td>
                <td>
                  <div><?php echo htmlspecialchars($rule['gift_product_name'] ?? 'N/A'); ?></div>
                  <small class="text-600"><?php echo htmlspecialchars($rule['gift_product_sku'] ?? ''); ?></small>
                </td>
                <td><?php echo number_format($rule['gift_quantity']); ?></td>
                <td>
                  <?php if ($rule['min_order_value']): ?>
                  <?php echo number_format($rule['min_order_value'], 2); ?> RON
                  <?php else: ?>
                  <span class="text-600">N/A</span>
                  <?php endif; ?>
                </td>
                <td>
                  <?php if ($rule['is_active']): ?>
                  <span class="badge badge-subtle-success">Activ</span>
                  <?php else: ?>
                  <span class="badge badge-subtle-danger">Inactiv</span>
                  <?php endif; ?>
                </td>
                <td>
                  <button class="btn btn-sm btn-falcon-default" data-bs-toggle="modal" data-bs-target="#editRuleModal<?php echo $rule['id']; ?>">
                    <span class="fas fa-edit"></span>
                  </button>
                  <form method="POST" class="d-inline" onsubmit="return confirm('Ești sigur că vrei să ștergi această regulă?');">
                    <input type="hidden" name="action" value="delete_rule">
                    <input type="hidden" name="rule_id" value="<?php echo $rule['id']; ?>">
                    <button type="submit" class="btn btn-sm btn-falcon-default text-danger">
                      <span class="fas fa-trash"></span>
                    </button>
                  </form>
                </td>
              </tr>
              <?php endforeach; ?>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Add Rule Modal -->
<div class="modal fade" id="addRuleModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Adaugă regulă produs cadou</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST">
        <div class="modal-body">
          <input type="hidden" name="action" value="add_rule">
          <div class="row">
            <div class="col-md-6 mb-3">
              <label class="form-label">Cumpără produs <span class="text-danger">*</span></label>
              <select class="form-select" name="buy_product_id" required>
                <option value="">Selectează produs</option>
                <?php foreach ($products as $product): ?>
                <option value="<?php echo $product['id']; ?>">
                  <?php echo htmlspecialchars($product['name'] . ' (' . $product['sku'] . ')'); ?>
                </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">Cantitate <span class="text-danger">*</span></label>
              <input type="number" class="form-control" name="buy_quantity" value="1" min="1" required>
            </div>
          </div>
          <div class="row">
            <div class="col-md-6 mb-3">
              <label class="form-label">Primește produs cadou <span class="text-danger">*</span></label>
              <select class="form-select" name="gift_product_id" required>
                <option value="">Selectează produs</option>
                <?php foreach ($products as $product): ?>
                <option value="<?php echo $product['id']; ?>">
                  <?php echo htmlspecialchars($product['name'] . ' (' . $product['sku'] . ')'); ?>
                </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">Cantitate cadou <span class="text-danger">*</span></label>
              <input type="number" class="form-control" name="gift_quantity" value="1" min="1" required>
            </div>
          </div>
          <div class="mb-3">
            <label class="form-label">Valoare minimă comandă (RON)</label>
            <input type="number" class="form-control" name="min_order_value" step="0.01" min="0" placeholder="Opțional">
            <small class="text-600">Lăsați gol dacă nu doriți o valoare minimă</small>
          </div>
          <div class="mb-3">
            <div class="form-check">
              <input type="checkbox" class="form-check-input" name="is_active" id="is_active_add" checked>
              <label class="form-check-label" for="is_active_add">Regulă activă</label>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Anulează</button>
          <button type="submit" class="btn btn-primary">Adaugă</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Edit Rule Modals -->
<?php foreach ($rules as $rule): ?>
<div class="modal fade" id="editRuleModal<?php echo $rule['id']; ?>" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Editează regulă produs cadou</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST">
        <div class="modal-body">
          <input type="hidden" name="action" value="update_rule">
          <input type="hidden" name="rule_id" value="<?php echo $rule['id']; ?>">
          <div class="row">
            <div class="col-md-6 mb-3">
              <label class="form-label">Cumpără produs <span class="text-danger">*</span></label>
              <select class="form-select" name="buy_product_id" required>
                <option value="">Selectează produs</option>
                <?php foreach ($products as $product): ?>
                <option value="<?php echo $product['id']; ?>" <?php echo ($rule['buy_product_id'] == $product['id']) ? 'selected' : ''; ?>>
                  <?php echo htmlspecialchars($product['name'] . ' (' . $product['sku'] . ')'); ?>
                </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">Cantitate <span class="text-danger">*</span></label>
              <input type="number" class="form-control" name="buy_quantity" value="<?php echo $rule['buy_quantity']; ?>" min="1" required>
            </div>
          </div>
          <div class="row">
            <div class="col-md-6 mb-3">
              <label class="form-label">Primește produs cadou <span class="text-danger">*</span></label>
              <select class="form-select" name="gift_product_id" required>
                <option value="">Selectează produs</option>
                <?php foreach ($products as $product): ?>
                <option value="<?php echo $product['id']; ?>" <?php echo ($rule['gift_product_id'] == $product['id']) ? 'selected' : ''; ?>>
                  <?php echo htmlspecialchars($product['name'] . ' (' . $product['sku'] . ')'); ?>
                </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">Cantitate cadou <span class="text-danger">*</span></label>
              <input type="number" class="form-control" name="gift_quantity" value="<?php echo $rule['gift_quantity']; ?>" min="1" required>
            </div>
          </div>
          <div class="mb-3">
            <label class="form-label">Valoare minimă comandă (RON)</label>
            <input type="number" class="form-control" name="min_order_value" step="0.01" min="0" value="<?php echo $rule['min_order_value'] ?? ''; ?>" placeholder="Opțional">
            <small class="text-600">Lăsați gol dacă nu doriți o valoare minimă</small>
          </div>
          <div class="mb-3">
            <div class="form-check">
              <input type="checkbox" class="form-check-input" name="is_active" id="is_active_<?php echo $rule['id']; ?>" <?php echo $rule['is_active'] ? 'checked' : ''; ?>>
              <label class="form-check-label" for="is_active_<?php echo $rule['id']; ?>">Regulă activă</label>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Anulează</button>
          <button type="submit" class="btn btn-primary">Salvează</button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php endforeach; ?>

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

