<?php
session_start();

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header('Location: index.php');
    exit;
}

include('includes/header.php');

// Crear base de datos codigos_reseller.db si no existe
$db_path = 'api/codigos_reseller.db';
if (!file_exists($db_path)) {
    $db_codes = new SQLite3($db_path);
    $db_codes->exec('
        CREATE TABLE reseller_codes (
            id INTEGER PRIMARY KEY,
            code TEXT NOT NULL UNIQUE,
            reseller_name TEXT NOT NULL,
            created_at TEXT NOT NULL,
            is_active INTEGER NOT NULL DEFAULT 1
        )
    ');
    $db_codes->close();
}

// Conectar a la base de datos de códigos
class SQLiteWrapperCodes {
    private $db;
    public function __construct($path) {
        $this->db = new SQLite3($path);
    }
    public function select($table, $columns, $where = '', $order = '', $params = []) {
        $query = "SELECT $columns FROM $table";
        if ($where) $query .= " WHERE $where";
        if ($order) $query .= " ORDER BY $order";
        $stmt = $this->db->prepare($query);
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        $result = $stmt->execute();
        $rows = [];
        while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
            $rows[] = $row;
        }
        return $rows;
    }
    public function insert($table, $data) {
        $columns = implode(', ', array_keys($data));
        $placeholders = ':' . implode(', :', array_keys($data));
        $query = "INSERT INTO $table ($columns) VALUES ($placeholders)";
        $stmt = $this->db->prepare($query);
        foreach ($data as $key => $value) {
            $stmt->bindValue(":$key", $value);
        }
        return $stmt->execute();
    }
    public function update($table, $data, $where, $params) {
        $set = implode(', ', array_map(fn($k) => "$k = :$k", array_keys($data)));
        $query = "UPDATE $table SET $set WHERE $where";
        $stmt = $this->db->prepare($query);
        foreach ($data as $key => $value) {
            $stmt->bindValue(":$key", $value);
        }
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        return $stmt->execute();
    }
    public function delete($table, $where, $params) {
        $query = "DELETE FROM $table WHERE $where";
        $stmt = $this->db->prepare($query);
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        return $stmt->execute();
    }
    public function close() {
        $this->db->close();
    }
}

$db_codes = new SQLiteWrapperCodes($db_path);

// Funciones para CSRF
function generate_csrf_token() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function verify_csrf_token($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// Generar código único
function generate_unique_code($db_codes) {
    $chars = '0123456789';
    do {
        $code = '';
        for ($i = 0; $i < 6; $i++) {
            $code .= $chars[random_int(0, strlen($chars) - 1)];
        }
        $existing = $db_codes->select('reseller_codes', '*', 'code = :code', '', [':code' => $code]);
    } while (!empty($existing));
    return $code;
}

// Procesar acciones
$status = $_GET['status'] ?? '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verify_csrf_token($_POST['csrf_token'])) {
    // Generar nuevo código
    if (isset($_POST['submit'])) {
        $reseller_name = filter_input(INPUT_POST, 'reseller_name', FILTER_SANITIZE_STRING);
        if (!empty($reseller_name)) {
            $code = generate_unique_code($db_codes);
            $data = [
                'code' => $code,
                'reseller_name' => $reseller_name,
                'created_at' => date('c'),
                'is_active' => 1
            ];
            if ($db_codes->insert('reseller_codes', $data)) {
                echo "<script>window.location.href='".basename($_SERVER['SCRIPT_NAME'])."?status=1'</script>";
            } else {
                $error = "❌ Error al generar el código";
            }
        } else {
            $error = "❌ El nombre del reseller es requerido";
        }
    }

    // Actualizar código
    if (isset($_POST['submitU'])) {
        $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
        $reseller_name = filter_input(INPUT_POST, 'reseller_name', FILTER_SANITIZE_STRING);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        $regenerate = isset($_POST['regenerate']) ? 1 : 0;

        if ($id && !empty($reseller_name)) {
            $data = [
                'reseller_name' => $reseller_name,
                'is_active' => $is_active
            ];
            if ($regenerate) {
                $data['code'] = generate_unique_code($db_codes);
                $data['created_at'] = date('c');
            }
            if ($db_codes->update('reseller_codes', $data, 'id = :id', [':id' => $id])) {
                echo "<script>window.location.href='".basename($_SERVER['SCRIPT_NAME'])."?status=1'</script>";
            } else {
                $error = "❌ Error al actualizar el código";
            }
        } else {
            $error = "❌ ID inválido o nombre del reseller requerido";
        }
    }

    // Eliminar código
    if (isset($_POST['delete'])) {
        $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
        if ($id) {
            if ($db_codes->delete('reseller_codes', 'id = :id', [':id' => $id])) {
                echo "<script>window.location.href='".basename($_SERVER['SCRIPT_NAME'])."?status=2'</script>";
            } else {
                $error = "❌ Error al eliminar el código";
            }
        } else {
            $error = "❌ ID inválido";
        }
    }

    // Inactivar/Activar código
    if (isset($_POST['toggle_active'])) {
        $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
        $new_status = filter_input(INPUT_POST, 'new_status', FILTER_VALIDATE_INT);
        if ($id && in_array($new_status, [0, 1])) {
            if ($db_codes->update('reseller_codes', ['is_active' => $new_status], 'id = :id', [':id' => $id])) {
                echo "<script>window.location.href='".basename($_SERVER['SCRIPT_NAME'])."?status=1'</script>";
            } else {
                $error = "❌ Error al cambiar el estado del código";
            }
        } else {
            $error = "❌ ID o estado inválido";
        }
    }
}

// Obtener códigos para mostrar o editar
$codes = $db_codes->select('reseller_codes', '*', '', 'id DESC');
$codeU = isset($_GET['update']) ? $db_codes->select('reseller_codes', '*', 'id = :id', '', [':id' => $_GET['update']]) : [];

?>

<!-- Modal para confirmación de eliminación -->
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Confirmar</h2>
            </div>
            <div class="modal-body">
                ¿Realmente desea eliminar este código?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                <form method="POST" style="display: inline;">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(generate_csrf_token()); ?>">
                    <input type="hidden" name="delete" value="1">
                    <input type="hidden" name="id" id="delete-id">
                    <button type="submit" class="btn btn-danger">Eliminar</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Mensajes de estado -->
<?php if ($status == 1) { ?>
    <div class="alert alert-success text-center">✅ Operación realizada correctamente</div>
<?php } elseif ($status == 2) { ?>
    <div class="alert alert-danger text-center">✅ Código eliminado correctamente</div>
<?php } elseif (isset($error)) { ?>
    <div class="alert alert-danger text-center"><?php echo htmlspecialchars($error); ?></div>
<?php } ?>

<?php if (isset($_GET['create'])) { ?>
    <!-- Formulario para generar nuevo código -->
    <div class="col-md-8 mx-auto">
        <div class="card-body">
            <div class="card bg-primary text-white">
                <div class="card-header card-header-warning">
                    <center>
                        <h2><i class="fa fa-key"></i> Generar Código de Reseller</h2>
                    </center>
                </div>
                <div class="card-body">
                    <div class="col-12">
                        <h3>Generar Nuevo Código</h3>
                    </div>
                    <form method="POST">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(generate_csrf_token()); ?>">
                        <div class="form-group">
                            <label class="form-label">Nombre del Reseller</label>
                            <input class="form-control" name="reseller_name" placeholder="Nombre del Reseller" type="text" required>
                        </div>
                        <div class="form-group">
                            <p>Al hacer clic en "Generar", se creará un código de 6 dígitos único asociado a este reseller.</p>
                        </div>
                        <div class="form-group">
                            <center>
                                <button class="btn btn-info" name="submit" type="submit">
                                    <i class="fa fa-check"></i> Generar
                                </button>
                            </center>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
<?php } elseif (isset($_GET['update']) && !empty($codeU)) { ?>
    <!-- Formulario para editar código -->
    <div class="col-md-8 mx-auto">
        <div class="card-body">
            <div class="card bg-primary text-white">
                <div class="card-header card-header-warning">
                    <center>
                        <h2><i class="fa fa-key"></i> Editar Código de Reseller</h2>
                    </center>
                </div>
                <div class="card-body">
                    <div class="col-12">
                        <h3>Editar Código</h3>
                    </div>
                    <form method="POST">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(generate_csrf_token()); ?>">
                        <input type="hidden" name="id" value="<?php echo htmlspecialchars($codeU[0]['id']); ?>">
                        <div class="form-group">
                            <label class="form-label">Nombre del Reseller</label>
                            <input class="form-control" name="reseller_name" placeholder="Nombre del Reseller" type="text" value="<?php echo htmlspecialchars($codeU[0]['reseller_name']); ?>" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Código</label>
                            <input class="form-control" value="<?php echo htmlspecialchars($codeU[0]['code']); ?>" disabled>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Estado</label>
                            <div class="checkbox">
                                <label><input type="checkbox" name="is_active" <?php echo $codeU[0]['is_active'] ? 'checked' : ''; ?>> Activo</label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Regenerar Código</label>
                            <div class="checkbox">
                                <label><input type="checkbox" name="regenerate"> Generar un nuevo código</label>
                            </div>
                        </div>
                        <div class="form-group">
                            <center>
                                <button class="btn btn-info" name="submitU" type="submit">
                                    <i class="fa fa-check"></i> Guardar
                                </button>
                            </center>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
<?php } else { ?>
    <!-- Tabla principal de códigos -->
    <div class="col-md-12 mx-auto">
        <div class="card-body">
            <div class="card bg-primary text-white">
                <div class="card-header card-header-warning">
                    <center>
                        <h2><i class="fa fa-key"></i> Códigos de Reseller</h2>
                    </center>
                </div>
                <div class="card-body">
                    <div class="col-12">
                        <center>
                            <a href="./<?php echo basename($_SERVER['SCRIPT_NAME']); ?>?create" class="btn btn-info">
                                <i class="fa fa-plus"></i> Nuevo Código
                            </a>
                        </center>
                    </div>
                    <br>
                    <div class="table-responsive">
                        <table class="table table-striped table-sm">
                            <thead style="color:white!important">
                                <tr>
                                    <th>ID</th>
                                    <th>Código</th>
                                    <th>Nombre del Reseller</th>
                                    <th>Fecha de Creación</th>
                                    <th>Estado</th>
                                    <th>Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($codes as $row) { ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($row['id']); ?></td>
                                        <td><?php echo htmlspecialchars($row['code']); ?></td>
                                        <td><?php echo htmlspecialchars($row['reseller_name']); ?></td>
                                        <td><?php echo htmlspecialchars($row['created_at']); ?></td>
                                        <td><?php echo $row['is_active'] ? 'Activo' : 'Inactivo'; ?></td>
                                        <td>
                                            <a class="btn btn-info btn-ok" href="./<?php echo basename($_SERVER['SCRIPT_NAME']); ?>?update=<?php echo $row['id']; ?>">
                                                <i class="fa fa-pencil-square-o"></i>
                                            </a>
                                            <form method="POST" style="display: inline;">
                                                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(generate_csrf_token()); ?>">
                                                <input type="hidden" name="toggle_active" value="1">
                                                <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                                                <input type="hidden" name="new_status" value="<?php echo $row['is_active'] ? 0 : 1; ?>">
                                                <button type="submit" class="btn <?php echo $row['is_active'] ? 'btn-warning' : 'btn-success'; ?> btn-ok">
                                                    <?php echo $row['is_active'] ? '<i class="fa fa-ban"></i> Inactivar' : '<i class="fa fa-check-circle"></i> Activar'; ?>
                                                </button>
                                            </form>
                                            <a class="btn btn-danger btn-ok" href="#" data-href="./<?php echo basename($_SERVER['SCRIPT_NAME']); ?>?delete=<?php echo $row['id']; ?>" data-toggle="modal" data-target="#confirm-delete" onclick="document.getElementById('delete-id').value = '<?php echo $row['id']; ?>'">
                                                <i class="fa fa-trash-o"></i>
                                            </a>
                                        </td>
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
<?php } ?>

<?php include('includes/footer.php'); ?>
<script>
    // Configurar el ID para eliminación en el modal
    $('#confirm-delete').on('show.bs.modal', function(e) {
        var dataHref = $(e.relatedTarget).data('href');
        $(this).find('.btn-ok').attr('href', dataHref);
    });
</script>
</body>
</html>